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