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