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