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