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