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