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