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