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