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