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