0.9.6.31:
[sbcl.git] / src / pcl / methods.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26
27 ;;; methods
28 ;;;
29 ;;; Methods themselves are simple inanimate objects. Most properties of
30 ;;; methods are immutable, methods cannot be reinitialized. The following
31 ;;; properties of methods can be changed:
32 ;;;   METHOD-GENERIC-FUNCTION
33 ;;;   METHOD-FUNCTION       ??
34
35 (defmethod method-function ((method standard-method))
36   (or (slot-value method 'function)
37       (let ((fmf (slot-value method 'fast-function)))
38         (unless fmf ; The :BEFORE SHARED-INITIALIZE method prevents this.
39           (error "~S doesn't seem to have a METHOD-FUNCTION." method))
40         (setf (slot-value method 'function)
41               (method-function-from-fast-function fmf)))))
42
43 (defmethod accessor-method-class ((method standard-accessor-method))
44   (car (slot-value method 'specializers)))
45
46 (defmethod accessor-method-class ((method standard-writer-method))
47   (cadr (slot-value method 'specializers)))
48
49 ;;; initialization
50 ;;;
51 ;;; Error checking is done in before methods. Because of the simplicity of
52 ;;; standard method objects the standard primary method can fill the slots.
53 ;;;
54 ;;; Methods are not reinitializable.
55
56 (define-condition metaobject-initialization-violation 
57     (reference-condition simple-condition)
58   ())  
59
60 (macrolet ((def (name args control)
61                `(defmethod ,name ,args
62                  (declare (ignore initargs))
63                  (error 'metaobject-initialization-violation
64                   :format-control ,(format nil "~@<~A~@:>" control )
65                   :format-arguments (list ',name)
66                   :references (list '(:amop :initialization "Method"))))))
67   (def reinitialize-instance ((method method) &rest initargs)
68     "Method objects cannot be redefined by ~S.")
69   (def change-class ((method method) new &rest initargs)
70     "Method objects cannot be redefined by ~S.")
71   ;; FIXME: NEW being a subclass of METHOD.
72   (def update-instance-for-redefined-class ((method method) added discarded 
73                                             plist &rest initargs)
74     "No behaviour specified for ~S on method objects.")
75   (def update-instance-for-different-class (old (new method) &rest initargs)
76     "No behaviour specified for ~S on method objects.")
77   (def update-instance-for-different-class ((old method) new &rest initargs)
78     "No behaviour specified for ~S on method objects."))
79   
80 (defmethod legal-documentation-p ((object standard-method) x)
81   (if (or (null x) (stringp x))
82       t
83       "a string or NULL"))
84
85 (defmethod legal-lambda-list-p ((object standard-method) x)
86   (declare (ignore x))
87   t)
88
89 (defmethod legal-method-function-p ((object standard-method) x)
90   (if (functionp x)
91       t
92       "a function"))
93
94 (defmethod legal-qualifiers-p ((object standard-method) x)
95   (flet ((improper-list ()
96            (return-from legal-qualifiers-p "Is not a proper list.")))
97     (dolist-carefully (q x improper-list)
98       (let ((ok (legal-qualifier-p object q)))
99         (unless (eq ok t)
100           (return-from legal-qualifiers-p
101             (format nil "Contains ~S which ~A" q ok)))))
102     t))
103
104 (defmethod legal-qualifier-p ((object standard-method) x)
105   (if (and x (atom x))
106       t
107       "is not a non-null atom"))
108
109 (defmethod legal-slot-name-p ((object standard-method) x)
110   (cond ((not (symbolp x)) "is not a symbol")
111         (t t)))
112
113 (defmethod legal-specializers-p ((object standard-method) x)
114   (flet ((improper-list ()
115            (return-from legal-specializers-p "Is not a proper list.")))
116     (dolist-carefully (s x improper-list)
117       (let ((ok (legal-specializer-p object s)))
118         (unless (eq ok t)
119           (return-from legal-specializers-p
120             (format nil "Contains ~S which ~A" s ok)))))
121     t))
122
123 (defvar *allow-experimental-specializers-p* nil)
124
125 (defmethod legal-specializer-p ((object standard-method) x)
126   (if (if *allow-experimental-specializers-p*
127           (specializerp x)
128           (or (classp x)
129               (eql-specializer-p x)))
130       t
131       "is neither a class object nor an EQL specializer"))
132
133 (defmethod shared-initialize :before ((method standard-method)
134                                       slot-names
135                                       &key qualifiers
136                                            lambda-list
137                                            specializers
138                                            function
139                                            fast-function
140                                            documentation)
141   (declare (ignore slot-names))
142   (flet ((lose (initarg value string)
143            (error "when initializing the method ~S:~%~
144                    The ~S initialization argument was: ~S.~%~
145                    which ~A."
146                   method initarg value string)))
147     (let ((check-qualifiers    (legal-qualifiers-p method qualifiers))
148           (check-lambda-list   (legal-lambda-list-p method lambda-list))
149           (check-specializers  (legal-specializers-p method specializers))
150           (check-fun (legal-method-function-p method
151                                               (or function
152                                                   fast-function)))
153           (check-documentation (legal-documentation-p method documentation)))
154       (unless (eq check-qualifiers t)
155         (lose :qualifiers qualifiers check-qualifiers))
156       (unless (eq check-lambda-list t)
157         (lose :lambda-list lambda-list check-lambda-list))
158       (unless (eq check-specializers t)
159         (lose :specializers specializers check-specializers))
160       (unless (eq check-fun t)
161         (lose :function function check-fun))
162       (unless (eq check-documentation t)
163         (lose :documentation documentation check-documentation)))))
164
165 (defmethod shared-initialize :before ((method standard-accessor-method)
166                                       slot-names
167                                       &key slot-name slot-definition)
168   (declare (ignore slot-names))
169   (unless slot-definition
170     (let ((legalp (legal-slot-name-p method slot-name)))
171       ;; FIXME: nasty convention; should be renamed to ILLEGAL-SLOT-NAME-P and
172       ;; ILLEGALP, and the convention redone to be less twisty
173       (unless (eq legalp t)
174         (error "The value of the :SLOT-NAME initarg ~A." legalp)))))
175
176 (defmethod shared-initialize :after ((method standard-method) slot-names
177                                      &rest initargs
178                                      &key qualifiers method-spec plist)
179   (declare (ignore slot-names method-spec plist))
180   (initialize-method-function initargs nil method)
181   (setf (plist-value method 'qualifiers) qualifiers)
182   #+ignore
183   (setf (slot-value method 'closure-generator)
184         (method-function-closure-generator (slot-value method 'function))))
185
186 (defmethod shared-initialize :after ((method standard-accessor-method)
187                                      slot-names
188                                      &key)
189   (declare (ignore slot-names))
190   (with-slots (slot-name slot-definition)
191     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 (defun real-add-method (generic-function method &optional skip-dfun-update-p)
490   (when (method-generic-function method)
491     (error "~@<The method ~S is already part of the generic ~
492             function ~S; it can't be added to another generic ~
493             function until it is removed from the first one.~@:>"
494            method (method-generic-function method)))
495   (flet ((similar-lambda-lists-p (method-a method-b)
496            (multiple-value-bind (a-nreq a-nopt a-keyp a-restp)
497                (analyze-lambda-list (method-lambda-list method-a))
498              (multiple-value-bind (b-nreq b-nopt b-keyp b-restp)
499                  (analyze-lambda-list (method-lambda-list method-b))
500                (and (= a-nreq b-nreq)
501                     (= a-nopt b-nopt)
502                     (eq (or a-keyp a-restp)
503                         (or b-keyp b-restp)))))))
504       (let* ((name (generic-function-name generic-function))
505              (qualifiers (method-qualifiers method))
506              (specializers (method-specializers method))
507              (existing (get-method generic-function
508                                    qualifiers
509                                    specializers
510                                    nil)))
511
512         ;; If there is already a method like this one then we must get
513         ;; rid of it before proceeding.  Note that we call the generic
514         ;; function REMOVE-METHOD to remove it rather than doing it in
515         ;; some internal way.
516         (when (and existing (similar-lambda-lists-p existing method))
517           (remove-method generic-function existing))
518
519         (setf (method-generic-function method) generic-function)
520         (pushnew method (generic-function-methods generic-function))
521         (dolist (specializer specializers)
522           (add-direct-method specializer method))
523
524         ;; KLUDGE: SET-ARG-INFO contains the error-detecting logic for
525         ;; detecting attempts to add methods with incongruent lambda
526         ;; lists.  However, according to Gerd Moellmann on cmucl-imp,
527         ;; it also depends on the new method already having been added
528         ;; to the generic function.  Therefore, we need to remove it
529         ;; again on error:
530         (let ((remove-again-p t))
531           (unwind-protect
532                (progn
533                  (set-arg-info generic-function :new-method method)
534                  (setq remove-again-p nil))
535             (when remove-again-p
536               (remove-method generic-function method))))
537
538         ;; KLUDGE II: ANSI saith that it is not an error to add a
539         ;; method with invalid qualifiers to a generic function of the
540         ;; wrong kind; it's only an error at generic function
541         ;; invocation time; I dunno what the rationale was, and it
542         ;; sucks.  Nevertheless, it's probably a programmer error, so
543         ;; let's warn anyway. -- CSR, 2003-08-20
544         (let ((mc (generic-function-method-combination generic-functioN)))
545           (cond
546             ((eq mc *standard-method-combination*)
547              (when (and qualifiers
548                         (or (cdr qualifiers)
549                             (not (memq (car qualifiers)
550                                        '(:around :before :after)))))
551                (warn "~@<Invalid qualifiers for standard method combination ~
552                       in method ~S:~2I~_~S.~@:>"
553                      method qualifiers)))
554             ((short-method-combination-p mc)
555              (let ((mc-name (method-combination-type mc)))
556                (when (or (null qualifiers)
557                          (cdr qualifiers)
558                          (and (neq (car qualifiers) :around)
559                               (neq (car qualifiers) mc-name)))
560                  (warn "~@<Invalid qualifiers for ~S method combination ~
561                         in method ~S:~2I~_~S.~@:>"
562                        mc-name method qualifiers))))))
563
564         (unless skip-dfun-update-p
565           (update-ctors 'add-method
566                         :generic-function generic-function
567                         :method method)
568           (update-dfun generic-function))
569         (map-dependents generic-function
570                         (lambda (dep)
571                           (update-dependent generic-function
572                                             dep 'add-method method)))
573         generic-function)))
574
575 (defun real-remove-method (generic-function method)
576   (when  (eq generic-function (method-generic-function method))
577     (let* ((name (generic-function-name generic-function))
578            (specializers (method-specializers method))
579            (methods (generic-function-methods generic-function))
580            (new-methods (remove method methods)))
581       (setf (method-generic-function method) nil)
582       (setf (generic-function-methods generic-function) new-methods)
583       (dolist (specializer (method-specializers method))
584         (remove-direct-method specializer method))
585       (set-arg-info generic-function)
586       (update-ctors 'remove-method
587                     :generic-function generic-function
588                     :method method)
589       (update-dfun generic-function)
590       (map-dependents generic-function
591                       (lambda (dep)
592                         (update-dependent generic-function
593                                           dep 'remove-method method)))
594       generic-function)))
595 \f
596 (defun compute-applicable-methods-function (generic-function arguments)
597   (values (compute-applicable-methods-using-types
598            generic-function
599            (types-from-args generic-function arguments 'eql))))
600
601 (defmethod compute-applicable-methods
602     ((generic-function generic-function) arguments)
603   (values (compute-applicable-methods-using-types
604            generic-function
605            (types-from-args generic-function arguments 'eql))))
606
607 (defmethod compute-applicable-methods-using-classes
608     ((generic-function generic-function) classes)
609   (compute-applicable-methods-using-types
610    generic-function
611    (types-from-args generic-function classes 'class-eq)))
612
613 (defun proclaim-incompatible-superclasses (classes)
614   (setq classes (mapcar (lambda (class)
615                           (if (symbolp class)
616                               (find-class class)
617                               class))
618                         classes))
619   (dolist (class classes)
620     (dolist (other-class classes)
621       (unless (eq class other-class)
622         (pushnew other-class (class-incompatible-superclass-list class))))))
623
624 (defun superclasses-compatible-p (class1 class2)
625   (let ((cpl1 (cpl-or-nil class1))
626         (cpl2 (cpl-or-nil class2)))
627     (dolist (sc1 cpl1 t)
628       (dolist (ic (class-incompatible-superclass-list sc1))
629         (when (memq ic cpl2)
630           (return-from superclasses-compatible-p nil))))))
631
632 (mapc
633  #'proclaim-incompatible-superclasses
634  '(;; superclass class
635    (built-in-class std-class structure-class) ; direct subclasses of pcl-class
636    (standard-class funcallable-standard-class)
637    ;; superclass metaobject
638    (class eql-specializer class-eq-specializer method method-combination
639     generic-function slot-definition)
640    ;; metaclass built-in-class
641    (number sequence character           ; direct subclasses of t, but not array
642     standard-object structure-object)   ;                        or symbol
643    (number array character symbol       ; direct subclasses of t, but not
644     standard-object structure-object)   ;                        sequence
645    (complex float rational)             ; direct subclasses of number
646    (integer ratio)                      ; direct subclasses of rational
647    (list vector)                        ; direct subclasses of sequence
648    (cons null)                          ; direct subclasses of list
649    (string bit-vector)                  ; direct subclasses of vector
650    ))
651 \f
652 (defmethod same-specializer-p ((specl1 specializer) (specl2 specializer))
653   nil)
654
655 (defmethod same-specializer-p ((specl1 class) (specl2 class))
656   (eq specl1 specl2))
657
658 (defmethod specializer-class ((specializer class))
659   specializer)
660
661 (defmethod same-specializer-p ((specl1 class-eq-specializer)
662                                (specl2 class-eq-specializer))
663   (eq (specializer-class specl1) (specializer-class specl2)))
664
665 (defmethod same-specializer-p ((specl1 eql-specializer)
666                                (specl2 eql-specializer))
667   (eq (specializer-object specl1) (specializer-object specl2)))
668
669 (defmethod specializer-class ((specializer eql-specializer))
670   (class-of (slot-value specializer 'object)))
671
672 (defvar *in-gf-arg-info-p* nil)
673 (setf (gdefinition 'arg-info-reader)
674       (let ((mf (initialize-method-function
675                  (make-internal-reader-method-function
676                   'standard-generic-function 'arg-info)
677                  t)))
678         (lambda (&rest args) (funcall mf args nil))))
679
680
681 (defun error-need-at-least-n-args (function n)
682   (error 'simple-program-error
683          :format-control "~@<The function ~2I~_~S ~I~_requires ~
684                           at least ~W argument~:P.~:>"
685          :format-arguments (list function n)))
686
687 (defun types-from-args (generic-function arguments &optional type-modifier)
688   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
689       (get-generic-fun-info generic-function)
690     (declare (ignore applyp metatypes nkeys))
691     (let ((types-rev nil))
692       (dotimes-fixnum (i nreq)
693         i
694         (unless arguments
695           (error-need-at-least-n-args (generic-function-name generic-function)
696                                       nreq))
697         (let ((arg (pop arguments)))
698           (push (if type-modifier `(,type-modifier ,arg) arg) types-rev)))
699       (values (nreverse types-rev) arg-info))))
700
701 (defun get-wrappers-from-classes (nkeys wrappers classes metatypes)
702   (let* ((w wrappers) (w-tail w) (mt-tail metatypes))
703     (dolist (class (if (listp classes) classes (list classes)))
704       (unless (eq t (car mt-tail))
705         (let ((c-w (class-wrapper class)))
706           (unless c-w (return-from get-wrappers-from-classes nil))
707           (if (eql nkeys 1)
708               (setq w c-w)
709               (setf (car w-tail) c-w
710                     w-tail (cdr w-tail)))))
711       (setq mt-tail (cdr mt-tail)))
712     w))
713
714 (defun sdfun-for-caching (gf classes)
715   (let ((types (mapcar #'class-eq-type classes)))
716     (multiple-value-bind (methods all-applicable-and-sorted-p)
717         (compute-applicable-methods-using-types gf types)
718       (let ((generator (get-secondary-dispatch-function1
719                         gf methods types nil t all-applicable-and-sorted-p)))
720         (make-callable gf methods generator
721                        nil (mapcar #'class-wrapper classes))))))
722
723 (defun value-for-caching (gf classes)
724   (let ((methods (compute-applicable-methods-using-types
725                    gf (mapcar #'class-eq-type classes))))
726     (method-function-get (or (method-fast-function (car methods))
727                              (method-function (car methods)))
728                          :constant-value)))
729
730 (defun default-secondary-dispatch-function (generic-function)
731   (lambda (&rest args)
732     (let ((methods (compute-applicable-methods generic-function args)))
733       (if methods
734           (let ((emf (get-effective-method-function generic-function
735                                                     methods)))
736             (invoke-emf emf args))
737           (apply #'no-applicable-method generic-function args)))))
738
739 (defun list-eq (x y)
740   (loop (when (atom x) (return (eq x y)))
741         (when (atom y) (return nil))
742         (unless (eq (car x) (car y)) (return nil))
743         (setq x (cdr x)
744               y (cdr y))))
745
746 (defvar *std-cam-methods* nil)
747
748 (defun compute-applicable-methods-emf (generic-function)
749   (if (eq *boot-state* 'complete)
750       (let* ((cam (gdefinition 'compute-applicable-methods))
751              (cam-methods (compute-applicable-methods-using-types
752                            cam (list `(eql ,generic-function) t))))
753         (values (get-effective-method-function cam cam-methods)
754                 (list-eq cam-methods
755                          (or *std-cam-methods*
756                              (setq *std-cam-methods*
757                                    (compute-applicable-methods-using-types
758                                     cam (list `(eql ,cam) t)))))))
759       (values #'compute-applicable-methods-function t)))
760
761 (defun compute-applicable-methods-emf-std-p (gf)
762   (gf-info-c-a-m-emf-std-p (gf-arg-info gf)))
763
764 (defvar *old-c-a-m-gf-methods* nil)
765
766 (defun update-all-c-a-m-gf-info (c-a-m-gf)
767   (let ((methods (generic-function-methods c-a-m-gf)))
768     (if (and *old-c-a-m-gf-methods*
769              (every (lambda (old-method)
770                       (member old-method methods))
771                     *old-c-a-m-gf-methods*))
772         (let ((gfs-to-do nil)
773               (gf-classes-to-do nil))
774           (dolist (method methods)
775             (unless (member method *old-c-a-m-gf-methods*)
776               (let ((specl (car (method-specializers method))))
777                 (if (eql-specializer-p specl)
778                     (pushnew (specializer-object specl) gfs-to-do)
779                     (pushnew (specializer-class specl) gf-classes-to-do)))))
780           (map-all-generic-functions
781            (lambda (gf)
782              (when (or (member gf gfs-to-do)
783                        (dolist (class gf-classes-to-do nil)
784                          (member class
785                                  (class-precedence-list (class-of gf)))))
786                (update-c-a-m-gf-info gf)))))
787         (map-all-generic-functions #'update-c-a-m-gf-info))
788     (setq *old-c-a-m-gf-methods* methods)))
789
790 (defun update-gf-info (gf)
791   (update-c-a-m-gf-info gf)
792   (update-gf-simple-accessor-type gf))
793
794 (defun update-c-a-m-gf-info (gf)
795   (unless (early-gf-p gf)
796     (multiple-value-bind (c-a-m-emf std-p)
797         (compute-applicable-methods-emf gf)
798       (let ((arg-info (gf-arg-info gf)))
799         (setf (gf-info-static-c-a-m-emf arg-info) c-a-m-emf)
800         (setf (gf-info-c-a-m-emf-std-p arg-info) std-p)))))
801
802 (defun update-gf-simple-accessor-type (gf)
803   (let ((arg-info (gf-arg-info gf)))
804     (setf (gf-info-simple-accessor-type arg-info)
805           (let* ((methods (generic-function-methods gf))
806                  (class (and methods (class-of (car methods))))
807                  (type (and class
808                             (cond ((eq class
809                                        *the-class-standard-reader-method*)
810                                    'reader)
811                                   ((eq class
812                                        *the-class-standard-writer-method*)
813                                    'writer)
814                                   ((eq class
815                                        *the-class-standard-boundp-method*)
816                                    'boundp)))))
817             (when (and (gf-info-c-a-m-emf-std-p arg-info)
818                        type
819                        (dolist (method (cdr methods) t)
820                          (unless (eq class (class-of method)) (return nil)))
821                        (eq (generic-function-method-combination gf)
822                            *standard-method-combination*))
823               type)))))
824
825
826 ;;; CMUCL (Gerd's PCL, 2002-04-25) comment:
827 ;;;
828 ;;; Return two values.  First value is a function to be stored in
829 ;;; effective slot definition SLOTD for reading it with
830 ;;; SLOT-VALUE-USING-CLASS, setting it with (SETF
831 ;;; SLOT-VALUE-USING-CLASS) or testing it with
832 ;;; SLOT-BOUNDP-USING-CLASS.  GF is one of these generic functions,
833 ;;; TYPE is one of the symbols READER, WRITER, BOUNDP.  CLASS is
834 ;;; SLOTD's class.
835 ;;;
836 ;;; Second value is true if the function returned is one of the
837 ;;; optimized standard functions for the purpose, which are used
838 ;;; when only standard methods are applicable.
839 ;;;
840 ;;; FIXME: Change all these wacky function names to something sane.
841 (defun get-accessor-method-function (gf type class slotd)
842   (let* ((std-method (standard-svuc-method type))
843          (str-method (structure-svuc-method type))
844          (types1 `((eql ,class) (class-eq ,class) (eql ,slotd)))
845          (types (if (eq type 'writer) `(t ,@types1) types1))
846          (methods (compute-applicable-methods-using-types gf types))
847          (std-p (null (cdr methods))))
848     (values
849      (if std-p
850          (get-optimized-std-accessor-method-function class slotd type)
851          (let* ((optimized-std-fun
852                  (get-optimized-std-slot-value-using-class-method-function
853                   class slotd type))
854                 (method-alist
855                  `((,(car (or (member std-method methods)
856                               (member str-method methods)
857                               (bug "error in ~S"
858                                    'get-accessor-method-function)))
859                     ,optimized-std-fun)))
860                 (wrappers
861                  (let ((wrappers (list (wrapper-of class)
862                                        (class-wrapper class)
863                                        (wrapper-of slotd))))
864                    (if (eq type 'writer)
865                        (cons (class-wrapper *the-class-t*) wrappers)
866                        wrappers)))
867                 (sdfun (get-secondary-dispatch-function
868                         gf methods types method-alist wrappers)))
869            (get-accessor-from-svuc-method-function class slotd sdfun type)))
870      std-p)))
871
872 ;;; used by OPTIMIZE-SLOT-VALUE-BY-CLASS-P (vector.lisp)
873 (defun update-slot-value-gf-info (gf type)
874   (unless *new-class*
875     (update-std-or-str-methods gf type))
876   (when (and (standard-svuc-method type) (structure-svuc-method type))
877     (flet ((update-class (class)
878              (when (class-finalized-p class)
879                (dolist (slotd (class-slots class))
880                  (compute-slot-accessor-info slotd type gf)))))
881       (if *new-class*
882           (update-class *new-class*)
883           (map-all-classes #'update-class 'slot-object)))))
884
885 (defvar *standard-slot-value-using-class-method* nil)
886 (defvar *standard-setf-slot-value-using-class-method* nil)
887 (defvar *standard-slot-boundp-using-class-method* nil)
888 (defvar *condition-slot-value-using-class-method* nil)
889 (defvar *condition-setf-slot-value-using-class-method* nil)
890 (defvar *condition-slot-boundp-using-class-method* nil)
891 (defvar *structure-slot-value-using-class-method* nil)
892 (defvar *structure-setf-slot-value-using-class-method* nil)
893 (defvar *structure-slot-boundp-using-class-method* nil)
894
895 (defun standard-svuc-method (type)
896   (case type
897     (reader *standard-slot-value-using-class-method*)
898     (writer *standard-setf-slot-value-using-class-method*)
899     (boundp *standard-slot-boundp-using-class-method*)))
900
901 (defun set-standard-svuc-method (type method)
902   (case type
903     (reader (setq *standard-slot-value-using-class-method* method))
904     (writer (setq *standard-setf-slot-value-using-class-method* method))
905     (boundp (setq *standard-slot-boundp-using-class-method* method))))
906
907 (defun condition-svuc-method (type)
908   (case type
909     (reader *condition-slot-value-using-class-method*)
910     (writer *condition-setf-slot-value-using-class-method*)
911     (boundp *condition-slot-boundp-using-class-method*)))
912
913 (defun set-condition-svuc-method (type method)
914   (case type
915     (reader (setq *condition-slot-value-using-class-method* method))
916     (writer (setq *condition-setf-slot-value-using-class-method* method))
917     (boundp (setq *condition-slot-boundp-using-class-method* method))))
918
919 (defun structure-svuc-method (type)
920   (case type
921     (reader *structure-slot-value-using-class-method*)
922     (writer *structure-setf-slot-value-using-class-method*)
923     (boundp *structure-slot-boundp-using-class-method*)))
924
925 (defun set-structure-svuc-method (type method)
926   (case type
927     (reader (setq *structure-slot-value-using-class-method* method))
928     (writer (setq *structure-setf-slot-value-using-class-method* method))
929     (boundp (setq *structure-slot-boundp-using-class-method* method))))
930
931 (defun update-std-or-str-methods (gf type)
932   (dolist (method (generic-function-methods gf))
933     (let ((specls (method-specializers method)))
934       (when (and (or (not (eq type 'writer))
935                      (eq (pop specls) *the-class-t*))
936                  (every #'classp specls))
937         (cond ((and (eq (class-name (car specls)) 'std-class)
938                     (eq (class-name (cadr specls)) 'standard-object)
939                     (eq (class-name (caddr specls))
940                         'standard-effective-slot-definition))
941                (set-standard-svuc-method type method))
942               ((and (eq (class-name (car specls)) 'condition-class)
943                     (eq (class-name (cadr specls)) 'condition)
944                     (eq (class-name (caddr specls))
945                         'condition-effective-slot-definition))
946                (set-condition-svuc-method type method))
947               ((and (eq (class-name (car specls)) 'structure-class)
948                     (eq (class-name (cadr specls)) 'structure-object)
949                     (eq (class-name (caddr specls))
950                         'structure-effective-slot-definition))
951                (set-structure-svuc-method type method)))))))
952
953 (defun mec-all-classes-internal (spec precompute-p)
954   (cons (specializer-class spec)
955         (and (classp spec)
956              precompute-p
957              (not (or (eq spec *the-class-t*)
958                       (eq spec *the-class-slot-object*)
959                       (eq spec *the-class-standard-object*)
960                       (eq spec *the-class-structure-object*)))
961              (let ((sc (class-direct-subclasses spec)))
962                (when sc
963                  (mapcan (lambda (class)
964                            (mec-all-classes-internal class precompute-p))
965                          sc))))))
966
967 (defun mec-all-classes (spec precompute-p)
968   (let ((classes (mec-all-classes-internal spec precompute-p)))
969     (if (null (cdr classes))
970         classes
971         (let* ((a-classes (cons nil classes))
972                (tail classes))
973           (loop (when (null (cdr tail))
974                   (return (cdr a-classes)))
975                 (let ((class (cadr tail))
976                       (ttail (cddr tail)))
977                   (if (dolist (c ttail nil)
978                         (when (eq class c) (return t)))
979                       (setf (cdr tail) (cddr tail))
980                       (setf tail (cdr tail)))))))))
981
982 (defun mec-all-class-lists (spec-list precompute-p)
983   (if (null spec-list)
984       (list nil)
985       (let* ((car-all-classes (mec-all-classes (car spec-list)
986                                                precompute-p))
987              (all-class-lists (mec-all-class-lists (cdr spec-list)
988                                                    precompute-p)))
989         (mapcan (lambda (list)
990                   (mapcar (lambda (c) (cons c list)) car-all-classes))
991                 all-class-lists))))
992
993 (defun make-emf-cache (generic-function valuep cache classes-list new-class)
994   (let* ((arg-info (gf-arg-info generic-function))
995          (nkeys (arg-info-nkeys arg-info))
996          (metatypes (arg-info-metatypes arg-info))
997          (wrappers (unless (eq nkeys 1) (make-list nkeys)))
998          (precompute-p (gf-precompute-dfun-and-emf-p arg-info))
999          (default '(default)))
1000     (flet ((add-class-list (classes)
1001              (when (or (null new-class) (memq new-class classes))
1002                (let ((wrappers (get-wrappers-from-classes
1003                                 nkeys wrappers classes metatypes)))
1004                  (when (and wrappers
1005                             (eq default (probe-cache cache wrappers default)))
1006                    (let ((value (cond ((eq valuep t)
1007                                        (sdfun-for-caching generic-function
1008                                                           classes))
1009                                       ((eq valuep :constant-value)
1010                                        (value-for-caching generic-function
1011                                                           classes)))))
1012                      (setq cache (fill-cache cache wrappers value))))))))
1013       (if classes-list
1014           (mapc #'add-class-list classes-list)
1015           (dolist (method (generic-function-methods generic-function))
1016             (mapc #'add-class-list
1017                   (mec-all-class-lists (method-specializers method)
1018                                        precompute-p))))
1019       cache)))
1020
1021 (defmacro class-test (arg class)
1022   (cond
1023     ((eq class *the-class-t*) t)
1024     ((eq class *the-class-slot-object*)
1025      `(not (typep (classoid-of ,arg) 'built-in-classoid)))
1026     ((eq class *the-class-standard-object*)
1027      `(or (std-instance-p ,arg) (fsc-instance-p ,arg)))
1028     ((eq class *the-class-funcallable-standard-object*)
1029      `(fsc-instance-p ,arg))
1030     (t
1031      `(typep ,arg ',(class-name class)))))
1032
1033 (defmacro class-eq-test (arg class)
1034   `(eq (class-of ,arg) ',class))
1035
1036 (defmacro eql-test (arg object)
1037   `(eql ,arg ',object))
1038
1039 (defun dnet-methods-p (form)
1040   (and (consp form)
1041        (or (eq (car form) 'methods)
1042            (eq (car form) 'unordered-methods))))
1043
1044 ;;; This is CASE, but without gensyms.
1045 (defmacro scase (arg &rest clauses)
1046   `(let ((.case-arg. ,arg))
1047      (cond ,@(mapcar (lambda (clause)
1048                        (list* (cond ((null (car clause))
1049                                      nil)
1050                                     ((consp (car clause))
1051                                      (if (null (cdar clause))
1052                                          `(eql .case-arg.
1053                                                ',(caar clause))
1054                                          `(member .case-arg.
1055                                                   ',(car clause))))
1056                                     ((member (car clause) '(t otherwise))
1057                                      `t)
1058                                     (t
1059                                      `(eql .case-arg. ',(car clause))))
1060                               nil
1061                               (cdr clause)))
1062                      clauses))))
1063
1064 (defmacro mcase (arg &rest clauses) `(scase ,arg ,@clauses))
1065
1066 (defun generate-discrimination-net (generic-function methods types sorted-p)
1067   (let* ((arg-info (gf-arg-info generic-function))
1068          (c-a-m-emf-std-p (gf-info-c-a-m-emf-std-p arg-info))
1069          (precedence (arg-info-precedence arg-info)))
1070     (generate-discrimination-net-internal
1071      generic-function methods types
1072      (lambda (methods known-types)
1073        (if (or sorted-p
1074                (and c-a-m-emf-std-p
1075                     (block one-order-p
1076                       (let ((sorted-methods nil))
1077                         (map-all-orders
1078                          (copy-list methods) precedence
1079                          (lambda (methods)
1080                            (when sorted-methods (return-from one-order-p nil))
1081                            (setq sorted-methods methods)))
1082                         (setq methods sorted-methods))
1083                       t)))
1084            `(methods ,methods ,known-types)
1085            `(unordered-methods ,methods ,known-types)))
1086      (lambda (position type true-value false-value)
1087        (let ((arg (dfun-arg-symbol position)))
1088          (if (eq (car type) 'eql)
1089              (let* ((false-case-p (and (consp false-value)
1090                                        (or (eq (car false-value) 'scase)
1091                                            (eq (car false-value) 'mcase))
1092                                        (eq arg (cadr false-value))))
1093                     (false-clauses (if false-case-p
1094                                        (cddr false-value)
1095                                        `((t ,false-value))))
1096                     (case-sym (if (and (dnet-methods-p true-value)
1097                                        (if false-case-p
1098                                            (eq (car false-value) 'mcase)
1099                                            (dnet-methods-p false-value)))
1100                                   'mcase
1101                                   'scase))
1102                     (type-sym `(,(cadr type))))
1103                `(,case-sym ,arg
1104                            (,type-sym ,true-value)
1105                            ,@false-clauses))
1106              `(if ,(let ((arg (dfun-arg-symbol position)))
1107                      (case (car type)
1108                        (class    `(class-test    ,arg ,(cadr type)))
1109                        (class-eq `(class-eq-test ,arg ,(cadr type)))))
1110                   ,true-value
1111                   ,false-value))))
1112      #'identity)))
1113
1114 (defun class-from-type (type)
1115   (if (or (atom type) (eq (car type) t))
1116       *the-class-t*
1117       (case (car type)
1118         (and (dolist (type (cdr type) *the-class-t*)
1119                (when (and (consp type) (not (eq (car type) 'not)))
1120                  (return (class-from-type type)))))
1121         (not *the-class-t*)
1122         (eql (class-of (cadr type)))
1123         (class-eq (cadr type))
1124         (class (cadr type)))))
1125
1126 (defun precompute-effective-methods (gf caching-p &optional classes-list-p)
1127   (let* ((arg-info (gf-arg-info gf))
1128          (methods (generic-function-methods gf))
1129          (precedence (arg-info-precedence arg-info))
1130          (*in-precompute-effective-methods-p* t)
1131          (classes-list nil))
1132     (generate-discrimination-net-internal
1133      gf methods nil
1134      (lambda (methods known-types)
1135        (when methods
1136          (when classes-list-p
1137            (push (mapcar #'class-from-type known-types) classes-list))
1138          (let ((no-eql-specls-p (not (methods-contain-eql-specializer-p
1139                                       methods))))
1140            (map-all-orders
1141             methods precedence
1142             (lambda (methods)
1143               (get-secondary-dispatch-function1
1144                gf methods known-types
1145                nil caching-p no-eql-specls-p))))))
1146      (lambda (position type true-value false-value)
1147        (declare (ignore position type true-value false-value))
1148        nil)
1149      (lambda (type)
1150        (if (and (consp type) (eq (car type) 'eql))
1151            `(class-eq ,(class-of (cadr type)))
1152            type)))
1153     classes-list))
1154
1155 ;;; We know that known-type implies neither new-type nor `(not ,new-type).
1156 (defun augment-type (new-type known-type)
1157   (if (or (eq known-type t)
1158           (eq (car new-type) 'eql))
1159       new-type
1160       (let ((so-far (if (and (consp known-type) (eq (car known-type) 'and))
1161                         (cdr known-type)
1162                         (list known-type))))
1163         (unless (eq (car new-type) 'not)
1164           (setq so-far
1165                 (mapcan (lambda (type)
1166                           (unless (*subtypep new-type type)
1167                             (list type)))
1168                         so-far)))
1169         (if (null so-far)
1170             new-type
1171             `(and ,new-type ,@so-far)))))
1172
1173 (defun generate-discrimination-net-internal
1174     (gf methods types methods-function test-fun type-function)
1175   (let* ((arg-info (gf-arg-info gf))
1176          (precedence (arg-info-precedence arg-info))
1177          (nreq (arg-info-number-required arg-info))
1178          (metatypes (arg-info-metatypes arg-info)))
1179     (labels ((do-column (p-tail contenders known-types)
1180                (if p-tail
1181                    (let* ((position (car p-tail))
1182                           (known-type (or (nth position types) t)))
1183                      (if (eq (nth position metatypes) t)
1184                          (do-column (cdr p-tail) contenders
1185                                     (cons (cons position known-type)
1186                                           known-types))
1187                          (do-methods p-tail contenders
1188                                      known-type () known-types)))
1189                    (funcall methods-function contenders
1190                             (let ((k-t (make-list nreq)))
1191                               (dolist (index+type known-types)
1192                                 (setf (nth (car index+type) k-t)
1193                                       (cdr index+type)))
1194                               k-t))))
1195              (do-methods (p-tail contenders known-type winners known-types)
1196                ;; CONTENDERS
1197                ;;   is a (sorted) list of methods that must be discriminated.
1198                ;; KNOWN-TYPE
1199                ;;   is the type of this argument, constructed from tests
1200                ;;   already made.
1201                ;; WINNERS
1202                ;;   is a (sorted) list of methods that are potentially
1203                ;;   applicable after the discrimination has been made.
1204                (if (null contenders)
1205                    (do-column (cdr p-tail)
1206                               winners
1207                               (cons (cons (car p-tail) known-type)
1208                                     known-types))
1209                    (let* ((position (car p-tail))
1210                           (method (car contenders))
1211                           (specl (nth position (method-specializers method)))
1212                           (type (funcall type-function
1213                                          (type-from-specializer specl))))
1214                      (multiple-value-bind (app-p maybe-app-p)
1215                          (specializer-applicable-using-type-p type known-type)
1216                        (flet ((determined-to-be (truth-value)
1217                                 (if truth-value app-p (not maybe-app-p)))
1218                               (do-if (truth &optional implied)
1219                                 (let ((ntype (if truth type `(not ,type))))
1220                                   (do-methods p-tail
1221                                     (cdr contenders)
1222                                     (if implied
1223                                         known-type
1224                                         (augment-type ntype known-type))
1225                                     (if truth
1226                                         (append winners `(,method))
1227                                         winners)
1228                                     known-types))))
1229                          (cond ((determined-to-be nil) (do-if nil t))
1230                                ((determined-to-be t)   (do-if t   t))
1231                                (t (funcall test-fun position type
1232                                            (do-if t) (do-if nil))))))))))
1233       (do-column precedence methods ()))))
1234
1235 (defun compute-secondary-dispatch-function (generic-function net &optional
1236                                             method-alist wrappers)
1237   (function-funcall (compute-secondary-dispatch-function1 generic-function net)
1238                     method-alist wrappers))
1239
1240 (defvar *eq-case-table-limit* 15)
1241 (defvar *case-table-limit* 10)
1242
1243 (defun compute-mcase-parameters (case-list)
1244   (unless (eq t (caar (last case-list)))
1245     (error "The key for the last case arg to mcase was not T"))
1246   (let* ((eq-p (dolist (case case-list t)
1247                  (unless (or (eq (car case) t)
1248                              (symbolp (caar case)))
1249                    (return nil))))
1250          (len (1- (length case-list)))
1251          (type (cond ((= len 1)
1252                       :simple)
1253                      ((<= len
1254                           (if eq-p
1255                               *eq-case-table-limit*
1256                               *case-table-limit*))
1257                       :assoc)
1258                      (t
1259                       :hash-table))))
1260     (list eq-p type)))
1261
1262 (defmacro mlookup (key info default &optional eq-p type)
1263   (unless (or (eq eq-p t) (null eq-p))
1264     (bug "Invalid eq-p argument: ~S" eq-p))
1265   (ecase type
1266     (:simple
1267      `(if (locally
1268             (declare (optimize (inhibit-warnings 3)))
1269             (,(if eq-p 'eq 'eql) ,key (car ,info)))
1270           (cdr ,info)
1271           ,default))
1272     (:assoc
1273      `(dolist (e ,info ,default)
1274         (when (locally
1275                 (declare (optimize (inhibit-warnings 3)))
1276                 (,(if eq-p 'eq 'eql) (car e) ,key))
1277           (return (cdr e)))))
1278     (:hash-table
1279      `(gethash ,key ,info ,default))))
1280
1281 (defun net-test-converter (form)
1282   (if (atom form)
1283       (default-test-converter form)
1284       (case (car form)
1285         ((invoke-effective-method-function invoke-fast-method-call)
1286          '.call.)
1287         (methods
1288          '.methods.)
1289         (unordered-methods
1290          '.umethods.)
1291         (mcase
1292          `(mlookup ,(cadr form)
1293                    nil
1294                    nil
1295                    ,@(compute-mcase-parameters (cddr form))))
1296         (t (default-test-converter form)))))
1297
1298 (defun net-code-converter (form)
1299   (if (atom form)
1300       (default-code-converter form)
1301       (case (car form)
1302         ((methods unordered-methods)
1303          (let ((gensym (gensym)))
1304            (values gensym
1305                    (list gensym))))
1306         (mcase
1307          (let ((mp (compute-mcase-parameters (cddr form)))
1308                (gensym (gensym)) (default (gensym)))
1309            (values `(mlookup ,(cadr form) ,gensym ,default ,@mp)
1310                    (list gensym default))))
1311         (t
1312          (default-code-converter form)))))
1313
1314 (defun net-constant-converter (form generic-function)
1315   (or (let ((c (methods-converter form generic-function)))
1316         (when c (list c)))
1317       (if (atom form)
1318           (default-constant-converter form)
1319           (case (car form)
1320             (mcase
1321              (let* ((mp (compute-mcase-parameters (cddr form)))
1322                     (list (mapcar (lambda (clause)
1323                                     (let ((key (car clause))
1324                                           (meth (cadr clause)))
1325                                       (cons (if (consp key) (car key) key)
1326                                             (methods-converter
1327                                              meth generic-function))))
1328                                   (cddr form)))
1329                     (default (car (last list))))
1330                (list (list* :mcase mp (nbutlast list))
1331                      (cdr default))))
1332             (t
1333              (default-constant-converter form))))))
1334
1335 (defun methods-converter (form generic-function)
1336   (cond ((and (consp form) (eq (car form) 'methods))
1337          (cons '.methods.
1338                (get-effective-method-function1 generic-function (cadr form))))
1339         ((and (consp form) (eq (car form) 'unordered-methods))
1340          (default-secondary-dispatch-function generic-function))))
1341
1342 (defun convert-methods (constant method-alist wrappers)
1343   (if (and (consp constant)
1344            (eq (car constant) '.methods.))
1345       (funcall (cdr constant) method-alist wrappers)
1346       constant))
1347
1348 (defun convert-table (constant method-alist wrappers)
1349   (cond ((and (consp constant)
1350               (eq (car constant) :mcase))
1351          (let ((alist (mapcar (lambda (k+m)
1352                                 (cons (car k+m)
1353                                       (convert-methods (cdr k+m)
1354                                                        method-alist
1355                                                        wrappers)))
1356                               (cddr constant)))
1357                (mp (cadr constant)))
1358            (ecase (cadr mp)
1359              (:simple
1360               (car alist))
1361              (:assoc
1362               alist)
1363              (:hash-table
1364               (let ((table (make-hash-table :test (if (car mp) 'eq 'eql))))
1365                 (dolist (k+m alist)
1366                   (setf (gethash (car k+m) table) (cdr k+m)))
1367                 table)))))))
1368
1369 (defun compute-secondary-dispatch-function1 (generic-function net
1370                                              &optional function-p)
1371   (cond
1372    ((and (eq (car net) 'methods) (not function-p))
1373     (get-effective-method-function1 generic-function (cadr net)))
1374    (t
1375     (let* ((name (generic-function-name generic-function))
1376            (arg-info (gf-arg-info generic-function))
1377            (metatypes (arg-info-metatypes arg-info))
1378            (applyp (arg-info-applyp arg-info))
1379            (fmc-arg-info (cons (length metatypes) applyp))
1380            (arglist (if function-p
1381                         (make-dfun-lambda-list metatypes applyp)
1382                         (make-fast-method-call-lambda-list metatypes applyp))))
1383       (multiple-value-bind (cfunction constants)
1384           (get-fun1 `(lambda
1385                       ,arglist
1386                       ,@(unless function-p
1387                           `((declare (ignore .pv-cell.
1388                                              .next-method-call.))))
1389                       (locally (declare #.*optimize-speed*)
1390                                (let ((emf ,net))
1391                                  ,(make-emf-call metatypes applyp 'emf))))
1392                     #'net-test-converter
1393                     #'net-code-converter
1394                     (lambda (form)
1395                       (net-constant-converter form generic-function)))
1396         (lambda (method-alist wrappers)
1397           (let* ((alist (list nil))
1398                  (alist-tail alist))
1399             (dolist (constant constants)
1400               (let* ((a (or (dolist (a alist nil)
1401                               (when (eq (car a) constant)
1402                                 (return a)))
1403                             (cons constant
1404                                   (or (convert-table
1405                                        constant method-alist wrappers)
1406                                       (convert-methods
1407                                        constant method-alist wrappers)))))
1408                      (new (list a)))
1409                 (setf (cdr alist-tail) new)
1410                 (setf alist-tail new)))
1411             (let ((function (apply cfunction (mapcar #'cdr (cdr alist)))))
1412               (if function-p
1413                   function
1414                   (make-fast-method-call
1415                    :function (set-fun-name function `(sdfun-method ,name))
1416                    :arg-info fmc-arg-info))))))))))
1417
1418 (defvar *show-make-unordered-methods-emf-calls* nil)
1419
1420 (defun make-unordered-methods-emf (generic-function methods)
1421   (when *show-make-unordered-methods-emf-calls*
1422     (format t "~&make-unordered-methods-emf ~S~%"
1423             (generic-function-name generic-function)))
1424   (lambda (&rest args)
1425     (let* ((types (types-from-args generic-function args 'eql))
1426            (smethods (sort-applicable-methods generic-function
1427                                               methods
1428                                               types))
1429            (emf (get-effective-method-function generic-function smethods)))
1430       (invoke-emf emf args))))
1431 \f
1432 ;;; The value returned by compute-discriminating-function is a function
1433 ;;; object. It is called a discriminating function because it is called
1434 ;;; when the generic function is called and its role is to discriminate
1435 ;;; on the arguments to the generic function and then call appropriate
1436 ;;; method functions.
1437 ;;;
1438 ;;; A discriminating function can only be called when it is installed as
1439 ;;; the funcallable instance function of the generic function for which
1440 ;;; it was computed.
1441 ;;;
1442 ;;; More precisely, if compute-discriminating-function is called with
1443 ;;; an argument <gf1>, and returns a result <df1>, that result must
1444 ;;; not be passed to apply or funcall directly. Rather, <df1> must be
1445 ;;; stored as the funcallable instance function of the same generic
1446 ;;; function <gf1> (using SET-FUNCALLABLE-INSTANCE-FUNCTION). Then the
1447 ;;; generic function can be passed to funcall or apply.
1448 ;;;
1449 ;;; An important exception is that methods on this generic function are
1450 ;;; permitted to return a function which itself ends up calling the value
1451 ;;; returned by a more specific method. This kind of `encapsulation' of
1452 ;;; discriminating function is critical to many uses of the MOP.
1453 ;;;
1454 ;;; As an example, the following canonical case is legal:
1455 ;;;
1456 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1457 ;;;     (let ((std (call-next-method)))
1458 ;;;       (lambda (arg)
1459 ;;;         (print (list 'call-to-gf gf arg))
1460 ;;;         (funcall std arg))))
1461 ;;;
1462 ;;; Because many discriminating functions would like to use a dynamic
1463 ;;; strategy in which the precise discriminating function changes with
1464 ;;; time it is important to specify how a discriminating function is
1465 ;;; permitted itself to change the funcallable instance function of the
1466 ;;; generic function.
1467 ;;;
1468 ;;; Discriminating functions may set the funcallable instance function
1469 ;;; of the generic function, but the new value must be generated by making
1470 ;;; a call to COMPUTE-DISCRIMINATING-FUNCTION. This is to ensure that any
1471 ;;; more specific methods which may have encapsulated the discriminating
1472 ;;; function will get a chance to encapsulate the new, inner discriminating
1473 ;;; function.
1474 ;;;
1475 ;;; This implies that if a discriminating function wants to modify itself
1476 ;;; it should first store some information in the generic function proper,
1477 ;;; and then call compute-discriminating-function. The appropriate method
1478 ;;; on compute-discriminating-function will see the information stored in
1479 ;;; the generic function and generate a discriminating function accordingly.
1480 ;;;
1481 ;;; The following is an example of a discriminating function which modifies
1482 ;;; itself in accordance with this protocol:
1483 ;;;
1484 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1485 ;;;     (lambda (arg)
1486 ;;;      (cond (<some condition>
1487 ;;;             <store some info in the generic function>
1488 ;;;             (set-funcallable-instance-function
1489 ;;;               gf
1490 ;;;               (compute-discriminating-function gf))
1491 ;;;             (funcall gf arg))
1492 ;;;            (t
1493 ;;;             <call-a-method-of-gf>))))
1494 ;;;
1495 ;;; Whereas this code would not be legal:
1496 ;;;
1497 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1498 ;;;     (lambda (arg)
1499 ;;;      (cond (<some condition>
1500 ;;;             (set-funcallable-instance-function
1501 ;;;               gf
1502 ;;;               (lambda (a) ..))
1503 ;;;             (funcall gf arg))
1504 ;;;            (t
1505 ;;;             <call-a-method-of-gf>))))
1506 ;;;
1507 ;;; NOTE:  All the examples above assume that all instances of the class
1508 ;;;     my-generic-function accept only one argument.
1509
1510 (defun slot-value-using-class-dfun (class object slotd)
1511   (declare (ignore class))
1512   (function-funcall (slot-definition-reader-function slotd) object))
1513
1514 (defun setf-slot-value-using-class-dfun (new-value class object slotd)
1515   (declare (ignore class))
1516   (function-funcall (slot-definition-writer-function slotd) new-value object))
1517
1518 (defun slot-boundp-using-class-dfun (class object slotd)
1519   (declare (ignore class))
1520   (function-funcall (slot-definition-boundp-function slotd) object))
1521
1522 (defmethod compute-discriminating-function ((gf standard-generic-function))
1523   (with-slots (dfun-state arg-info) gf
1524     (typecase dfun-state
1525       (null (let ((name (generic-function-name gf)))
1526               (when (eq name 'compute-applicable-methods)
1527                 (update-all-c-a-m-gf-info gf))
1528               (cond ((eq name 'slot-value-using-class)
1529                      (update-slot-value-gf-info gf 'reader)
1530                      #'slot-value-using-class-dfun)
1531                     ((equal name '(setf slot-value-using-class))
1532                      (update-slot-value-gf-info gf 'writer)
1533                      #'setf-slot-value-using-class-dfun)
1534                     ((eq name 'slot-boundp-using-class)
1535                      (update-slot-value-gf-info gf 'boundp)
1536                      #'slot-boundp-using-class-dfun)
1537                     ((gf-precompute-dfun-and-emf-p arg-info)
1538                      (make-final-dfun gf))
1539                     (t
1540                      (make-initial-dfun gf)))))
1541       (function dfun-state)
1542       (cons (car dfun-state)))))
1543
1544 (defmethod update-gf-dfun ((class std-class) gf)
1545   (let ((*new-class* class)
1546         #|| (name (generic-function-name gf)) ||#
1547         (arg-info (gf-arg-info gf)))
1548     (cond #||
1549           ((eq name 'slot-value-using-class)
1550            (update-slot-value-gf-info gf 'reader))
1551           ((equal name '(setf slot-value-using-class))
1552            (update-slot-value-gf-info gf 'writer))
1553           ((eq name 'slot-boundp-using-class)
1554            (update-slot-value-gf-info gf 'boundp))
1555           ||#
1556           ((gf-precompute-dfun-and-emf-p arg-info)
1557            (multiple-value-bind (dfun cache info)
1558                (make-final-dfun-internal gf)
1559              (set-dfun gf dfun cache info) ; lest the cache be freed twice
1560              (update-dfun gf dfun cache info))))))
1561 \f
1562 (defun (setf class-name) (new-value class)
1563   (let ((classoid (%wrapper-classoid (class-wrapper class))))
1564     (setf (classoid-name classoid) new-value))
1565   (reinitialize-instance class :name new-value))
1566
1567 (defun (setf generic-function-name) (new-value generic-function)
1568   (reinitialize-instance generic-function :name new-value))
1569 \f
1570 (defmethod function-keywords ((method standard-method))
1571   (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1572       (analyze-lambda-list (if (consp method)
1573                                (early-method-lambda-list method)
1574                                (method-lambda-list method)))
1575     (declare (ignore nreq nopt keysp restp))
1576     (values keywords allow-other-keys-p)))
1577
1578 (defun method-ll->generic-function-ll (ll)
1579   (multiple-value-bind
1580       (nreq nopt keysp restp allow-other-keys-p keywords keyword-parameters)
1581       (analyze-lambda-list ll)
1582     (declare (ignore nreq nopt keysp restp allow-other-keys-p keywords))
1583     (remove-if (lambda (s)
1584                  (or (memq s keyword-parameters)
1585                      (eq s '&allow-other-keys)))
1586                ll)))
1587 \f
1588 ;;; This is based on the rules of method lambda list congruency defined in
1589 ;;; the spec. The lambda list it constructs is the pretty union of the
1590 ;;; lambda lists of all the methods. It doesn't take method applicability
1591 ;;; into account at all yet.
1592 (defmethod generic-function-pretty-arglist
1593            ((generic-function standard-generic-function))
1594   (let ((methods (generic-function-methods generic-function)))
1595     (if methods
1596       (let ((arglist ()))
1597         ;; arglist is constructed from the GF's methods - maybe with
1598         ;; keys and rest stuff added
1599         (multiple-value-bind (required optional rest key allow-other-keys)
1600             (method-pretty-arglist (car methods))
1601           (dolist (m (cdr methods))
1602             (multiple-value-bind (method-key-keywords
1603                                   method-allow-other-keys
1604                                   method-key)
1605                 (function-keywords m)
1606               ;; we've modified function-keywords to return what we want as
1607               ;;  the third value, no other change here.
1608               (declare (ignore method-key-keywords))
1609               (setq key (union key method-key))
1610               (setq allow-other-keys (or allow-other-keys
1611                                          method-allow-other-keys))))
1612           (when allow-other-keys
1613             (setq arglist '(&allow-other-keys)))
1614           (when key
1615             (setq arglist (nconc (list '&key) key arglist)))
1616           (when rest
1617             (setq arglist (nconc (list '&rest rest) arglist)))
1618           (when optional
1619             (setq arglist (nconc (list '&optional) optional arglist)))
1620           (nconc required arglist)))
1621       ;; otherwise we take the lambda-list from the GF directly, with no
1622       ;; other 'keys' added ...
1623       (let ((lambda-list (generic-function-lambda-list generic-function)))
1624         lambda-list))))
1625
1626 (defmethod method-pretty-arglist ((method standard-method))
1627   (let ((required ())
1628         (optional ())
1629         (rest nil)
1630         (key ())
1631         (allow-other-keys nil)
1632         (state 'required)
1633         (arglist (method-lambda-list method)))
1634     (dolist (arg arglist)
1635       (cond ((eq arg '&optional)         (setq state 'optional))
1636             ((eq arg '&rest)             (setq state 'rest))
1637             ((eq arg '&key)              (setq state 'key))
1638             ((eq arg '&allow-other-keys) (setq allow-other-keys t))
1639             ((memq arg lambda-list-keywords))
1640             (t
1641              (ecase state
1642                (required (push arg required))
1643                (optional (push arg optional))
1644                (key      (push arg key))
1645                (rest     (setq rest arg))))))
1646     (values (nreverse required)
1647             (nreverse optional)
1648             rest
1649             (nreverse key)
1650             allow-other-keys)))
1651