0.pre7.61:
[sbcl.git] / src / pcl / boot.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
28 The CommonLoops evaluator is meta-circular.
29
30 Most of the code in PCL is methods on generic functions, including
31 most of the code that actually implements generic functions and method
32 lookup.
33
34 So, we have a classic bootstrapping problem. The solution to this is
35 to first get a cheap implementation of generic functions running,
36 these are called early generic functions. These early generic
37 functions and the corresponding early methods and early method lookup
38 are used to get enough of the system running that it is possible to
39 create real generic functions and methods and implement real method
40 lookup. At that point (done in the file FIXUP) the function
41 !FIX-EARLY-GENERIC-FUNCTIONS is called to convert all the early generic
42 functions to real generic functions.
43
44 The cheap generic functions are built using the same
45 FUNCALLABLE-INSTANCE objects that real generic functions are made out of.
46 This means that as PCL is being bootstrapped, the cheap generic
47 function objects which are being created are the same objects which
48 will later be real generic functions. This is good because:
49   - we don't cons garbage structure, and
50   - we can keep pointers to the cheap generic function objects
51     during booting because those pointers will still point to
52     the right object after the generic functions are all fixed up.
53
54 This file defines the DEFMETHOD macro and the mechanism used to expand
55 it. This includes the mechanism for processing the body of a method.
56 DEFMETHOD basically expands into a call to LOAD-DEFMETHOD, which
57 basically calls ADD-METHOD to add the method to the generic function.
58 These expansions can be loaded either during bootstrapping or when PCL
59 is fully up and running.
60
61 An important effect of this arrangement is it means we can compile
62 files with DEFMETHOD forms in them in a completely running PCL, but
63 then load those files back in during bootstrapping. This makes
64 development easier. It also means there is only one set of code for
65 processing DEFMETHOD. Bootstrapping works by being sure to have
66 LOAD-METHOD be careful to call only primitives which work during
67 bootstrapping.
68
69 |#
70
71 ;;; FIXME: As of sbcl-0.6.9.10, PCL still uses this nonstandard type
72 ;;; of declaration internally. It would be good to figure out how to
73 ;;; get rid of it, or failing that, (1) document why it's needed and
74 ;;; (2) use a private symbol with a forbidding name which suggests
75 ;;; it's not to be messed with by the user (e.g. SB-PCL:%CLASS)
76 ;;; instead of the too-inviting CLASS. (I tried just deleting the
77 ;;; declarations in MAKE-METHOD-LAMBDA-INTERNAL ca. sbcl-0.6.9.10, but
78 ;;; then things break.)
79 (declaim (declaration class))
80
81 ;;; FIXME: SB-KERNEL::PCL-CHECK-WRAPPER-VALIDITY-HOOK shouldn't be a
82 ;;; separate function. Instead, we should define a simple placeholder
83 ;;; version of SB-PCL:CHECK-WRAPPER-VALIDITY where
84 ;;; SB-KERNEL::PCL-CHECK-WRAPPER-VALIDITY is defined now, then just
85 ;;; let the later real PCL DEFUN of SB-PCL:CHECK-WRAPPER-VALIDITY
86 ;;; overwrite it.
87 (setf (symbol-function 'sb-kernel::pcl-check-wrapper-validity-hook)
88       #'check-wrapper-validity)
89
90 (declaim (notinline make-a-method
91                     add-named-method
92                     ensure-generic-function-using-class
93
94                     add-method
95                     remove-method))
96
97 (defvar *!early-functions*
98         '((make-a-method early-make-a-method
99                          real-make-a-method)
100           (add-named-method early-add-named-method
101                             real-add-named-method)
102           ))
103
104 ;;; For each of the early functions, arrange to have it point to its
105 ;;; early definition. Do this in a way that makes sure that if we
106 ;;; redefine one of the early definitions the redefinition will take
107 ;;; effect. This makes development easier.
108 (dolist (fns *!early-functions*)
109   (let ((name (car fns))
110         (early-name (cadr fns)))
111     (setf (gdefinition name)
112             (set-fun-name
113              (lambda (&rest args)
114                (apply (fdefinition early-name) args))
115              name))))
116
117 ;;; *!GENERIC-FUNCTION-FIXUPS* is used by !FIX-EARLY-GENERIC-FUNCTIONS
118 ;;; to convert the few functions in the bootstrap which are supposed
119 ;;; to be generic functions but can't be early on.
120 (defvar *!generic-function-fixups*
121   '((add-method
122      ((generic-function method)  ;lambda-list
123       (standard-generic-function method) ;specializers
124       real-add-method))          ;method-function
125     (remove-method
126      ((generic-function method)
127       (standard-generic-function method)
128       real-remove-method))
129     (get-method
130      ((generic-function qualifiers specializers &optional (errorp t))
131       (standard-generic-function t t)
132       real-get-method))
133     (ensure-generic-function-using-class
134      ((generic-function fun-name
135                         &key generic-function-class environment
136                         &allow-other-keys)
137       (generic-function t)
138       real-ensure-gf-using-class--generic-function)
139      ((generic-function fun-name
140                         &key generic-function-class environment
141                         &allow-other-keys)
142       (null t)
143       real-ensure-gf-using-class--null))
144     (make-method-lambda
145      ((proto-generic-function proto-method lambda-expression environment)
146       (standard-generic-function standard-method t t)
147       real-make-method-lambda))
148     (make-method-initargs-form
149      ((proto-generic-function proto-method
150                               lambda-expression
151                               lambda-list environment)
152       (standard-generic-function standard-method t t t)
153       real-make-method-initargs-form))
154     (compute-effective-method
155      ((generic-function combin applicable-methods)
156       (generic-function standard-method-combination t)
157       standard-compute-effective-method))))
158 \f
159 (defmacro defgeneric (fun-name lambda-list &body options)
160   (let ((initargs ())
161         (methods ()))
162     (flet ((duplicate-option (name)
163              (error 'simple-program-error
164                     :format-control "The option ~S appears more than once."
165                     :format-arguments (list name)))
166            (expand-method-definition (qab) ; QAB = qualifiers, arglist, body
167              (let* ((arglist-pos (position-if #'listp qab))
168                     (arglist (elt qab arglist-pos))
169                     (qualifiers (subseq qab 0 arglist-pos))
170                     (body (nthcdr (1+ arglist-pos) qab)))
171                `(defmethod ,fun-name ,@qualifiers ,arglist ,@body))))
172       (macrolet ((initarg (key) `(getf initargs ,key)))
173         (dolist (option options)
174           (let ((car-option (car option)))
175             (case car-option
176               (declare
177                (push (cdr option) (initarg :declarations)))
178               ((:argument-precedence-order :method-combination)
179                (if (initarg car-option)
180                    (duplicate-option car-option)
181                    (setf (initarg car-option)
182                          `',(cdr option))))
183               ((:documentation :generic-function-class :method-class)
184                (unless (proper-list-of-length-p option 2)
185                  (error "bad list length for ~S" option))
186                (if (initarg car-option)
187                    (duplicate-option car-option)
188                    (setf (initarg car-option) `',(cadr option))))
189               (:method
190                (push (cdr option) methods))
191               (t
192                ;; ANSI requires that unsupported things must get a
193                ;; PROGRAM-ERROR.
194                (error 'simple-program-error
195                       :format-control "unsupported option ~S"
196                       :format-arguments (list option))))))
197
198         (when (initarg :declarations)
199           (setf (initarg :declarations)
200                 `',(initarg :declarations))))
201       `(progn
202          (eval-when (:compile-toplevel :load-toplevel :execute)
203            (compile-or-load-defgeneric ',fun-name))
204          (load-defgeneric ',fun-name ',lambda-list ,@initargs)
205          ,@(mapcar #'expand-method-definition methods)
206          `,(function ,fun-name)))))
207
208 (defun compile-or-load-defgeneric (fun-name)
209   (sb-kernel:proclaim-as-fun-name fun-name)
210   (sb-kernel:note-name-defined fun-name :function)
211   (unless (eq (info :function :where-from fun-name) :declared)
212     (setf (info :function :where-from fun-name) :defined)
213     (setf (info :function :type fun-name)
214           (sb-kernel:specifier-type 'function))))
215
216 (defun load-defgeneric (fun-name lambda-list &rest initargs)
217   (when (fboundp fun-name)
218     (sb-kernel::style-warn "redefining ~S in DEFGENERIC" fun-name))
219   (apply #'ensure-generic-function
220          fun-name
221          :lambda-list lambda-list
222          :definition-source `((defgeneric ,fun-name) ,*load-truename*)
223          initargs))
224 \f
225 (defmacro defmethod (&rest args &environment env)
226   (multiple-value-bind (name qualifiers lambda-list body)
227       (parse-defmethod args)
228     (multiple-value-bind (proto-gf proto-method)
229         (prototypes-for-make-method-lambda name)
230       (expand-defmethod name
231                         proto-gf
232                         proto-method
233                         qualifiers
234                         lambda-list
235                         body
236                         env))))
237
238 (defun prototypes-for-make-method-lambda (name)
239   (if (not (eq *boot-state* 'complete))
240       (values nil nil)
241       (let ((gf? (and (gboundp name)
242                       (gdefinition name))))
243         (if (or (null gf?)
244                 (not (generic-function-p gf?)))
245             (values (class-prototype (find-class 'standard-generic-function))
246                     (class-prototype (find-class 'standard-method)))
247             (values gf?
248                     (class-prototype (or (generic-function-method-class gf?)
249                                          (find-class 'standard-method))))))))
250
251 ;;; Take a name which is either a generic function name or a list specifying
252 ;;; a SETF generic function (like: (SETF <generic-function-name>)). Return
253 ;;; the prototype instance of the method-class for that generic function.
254 ;;;
255 ;;; If there is no generic function by that name, this returns the
256 ;;; default value, the prototype instance of the class
257 ;;; STANDARD-METHOD. This default value is also returned if the spec
258 ;;; names an ordinary function or even a macro. In effect, this leaves
259 ;;; the signalling of the appropriate error until load time.
260 ;;;
261 ;;; Note: During bootstrapping, this function is allowed to return NIL.
262 (defun method-prototype-for-gf (name)
263   (let ((gf? (and (gboundp name)
264                   (gdefinition name))))
265     (cond ((neq *boot-state* 'complete) nil)
266           ((or (null gf?)
267                (not (generic-function-p gf?)))          ; Someone else MIGHT
268                                                         ; error at load time.
269            (class-prototype (find-class 'standard-method)))
270           (t
271             (class-prototype (or (generic-function-method-class gf?)
272                                  (find-class 'standard-method)))))))
273 \f
274 (defvar *optimize-asv-funcall-p* nil)
275 (defvar *asv-readers*)
276 (defvar *asv-writers*)
277 (defvar *asv-boundps*)
278
279 (defun expand-defmethod (name
280                          proto-gf
281                          proto-method
282                          qualifiers
283                          lambda-list
284                          body
285                          env)
286   (let ((*make-instance-function-keys* nil)
287         (*optimize-asv-funcall-p* t)
288         (*asv-readers* nil) (*asv-writers* nil) (*asv-boundps* nil))
289     (declare (special *make-instance-function-keys*))
290     (multiple-value-bind (method-lambda unspecialized-lambda-list specializers)
291         (add-method-declarations name qualifiers lambda-list body env)
292       (multiple-value-bind (method-function-lambda initargs)
293           (make-method-lambda proto-gf proto-method method-lambda env)
294         (let ((initargs-form (make-method-initargs-form proto-gf
295                                                         proto-method
296                                                         method-function-lambda
297                                                         initargs
298                                                         env)))
299           `(progn
300              ;; Note: We could DECLAIM the ftype of the generic
301              ;; function here, since ANSI specifies that we create it
302              ;; if it does not exist. However, I chose not to, because
303              ;; I think it's more useful to support a style of
304              ;; programming where every generic function has an
305              ;; explicit DEFGENERIC and any typos in DEFMETHODs are
306              ;; warned about. Otherwise
307              ;;   (DEFGENERIC FOO-BAR-BLETCH ((X T)))
308              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X HASH-TABLE)) ..)
309              ;;   (DEFMETHOD FOO-BRA-BLETCH ((X SIMPLE-VECTOR)) ..)
310              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X VECTOR)) ..)
311              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X ARRAY)) ..)
312              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X LIST)) ..)
313              ;; compiles without raising an error and runs without
314              ;; raising an error (since SIMPLE-VECTOR cases fall
315              ;; through to VECTOR) but still doesn't do what was
316              ;; intended. I hate that kind of bug (code which silently
317              ;; gives the wrong answer), so we don't do a DECLAIM
318              ;; here. -- WHN 20000229
319              ,@(when *make-instance-function-keys*
320                  `((get-make-instance-functions
321                     ',*make-instance-function-keys*)))
322              ,@(when (or *asv-readers* *asv-writers* *asv-boundps*)
323                  `((initialize-internal-slot-gfs*
324                     ',*asv-readers* ',*asv-writers* ',*asv-boundps*)))
325              ,(make-defmethod-form name qualifiers specializers
326                                    unspecialized-lambda-list
327                                    (if proto-method
328                                        (class-name (class-of proto-method))
329                                        'standard-method)
330                                    initargs-form
331                                    (getf (getf initargs ':plist)
332                                          ':pv-table-symbol))))))))
333
334 (defun interned-symbol-p (x)
335   (and (symbolp x) (symbol-package x)))
336
337 (defun make-defmethod-form (name qualifiers specializers
338                                  unspecialized-lambda-list method-class-name
339                                  initargs-form &optional pv-table-symbol)
340   (let (fn
341         fn-lambda)
342     (if (and (interned-symbol-p (fun-name-block-name name))
343              (every #'interned-symbol-p qualifiers)
344              (every #'(lambda (s)
345                         (if (consp s)
346                             (and (eq (car s) 'eql)
347                                  (constantp (cadr s))
348                                  (let ((sv (eval (cadr s))))
349                                    (or (interned-symbol-p sv)
350                                        (integerp sv)
351                                        (and (characterp sv)
352                                             (standard-char-p sv)))))
353                             (interned-symbol-p s)))
354                     specializers)
355              (consp initargs-form)
356              (eq (car initargs-form) 'list*)
357              (memq (cadr initargs-form) '(:function :fast-function))
358              (consp (setq fn (caddr initargs-form)))
359              (eq (car fn) 'function)
360              (consp (setq fn-lambda (cadr fn)))
361              (eq (car fn-lambda) 'lambda))
362         (let* ((specls (mapcar (lambda (specl)
363                                  (if (consp specl)
364                                      `(,(car specl) ,(eval (cadr specl)))
365                                    specl))
366                                specializers))
367                (mname `(,(if (eq (cadr initargs-form) ':function)
368                              'method 'fast-method)
369                         ,name ,@qualifiers ,specls))
370                (mname-sym (intern (let ((*print-pretty* nil)
371                                         ;; (We bind *PACKAGE* to
372                                         ;; KEYWORD here as a way to
373                                         ;; force symbols to be printed
374                                         ;; with explicit package
375                                         ;; prefixes.)
376                                         (*package* *keyword-package*))
377                                     (format nil "~S" mname)))))
378           `(progn
379              (defun ,mname-sym ,(cadr fn-lambda)
380                ,@(cddr fn-lambda))
381              ,(make-defmethod-form-internal
382                name qualifiers `',specls
383                unspecialized-lambda-list method-class-name
384                `(list* ,(cadr initargs-form)
385                        #',mname-sym
386                        ,@(cdddr initargs-form))
387                pv-table-symbol)))
388         (make-defmethod-form-internal
389          name qualifiers
390          `(list ,@(mapcar #'(lambda (specializer)
391                               (if (consp specializer)
392                                   ``(,',(car specializer)
393                                      ,,(cadr specializer))
394                                   `',specializer))
395                           specializers))
396          unspecialized-lambda-list method-class-name
397          initargs-form
398          pv-table-symbol))))
399
400 (defun make-defmethod-form-internal
401     (name qualifiers specializers-form unspecialized-lambda-list
402      method-class-name initargs-form &optional pv-table-symbol)
403   `(load-defmethod
404     ',method-class-name
405     ',name
406     ',qualifiers
407     ,specializers-form
408     ',unspecialized-lambda-list
409     ,initargs-form
410     ;; Paper over a bug in KCL by passing the cache-symbol here in
411     ;; addition to in the list. FIXME: We should no longer need to do
412     ;; this, since the CLOS code is now SBCL-specific, and doesn't
413     ;; need to be ported to every buggy compiler in existence.
414     ',pv-table-symbol))
415
416 (defmacro make-method-function (method-lambda &environment env)
417   (make-method-function-internal method-lambda env))
418
419 (defun make-method-function-internal (method-lambda &optional env)
420   (multiple-value-bind (proto-gf proto-method)
421       (prototypes-for-make-method-lambda nil)
422     (multiple-value-bind (method-function-lambda initargs)
423         (make-method-lambda proto-gf proto-method method-lambda env)
424       (make-method-initargs-form proto-gf
425                                  proto-method
426                                  method-function-lambda
427                                  initargs
428                                  env))))
429
430 (defun add-method-declarations (name qualifiers lambda-list body env)
431   (multiple-value-bind (parameters unspecialized-lambda-list specializers)
432       (parse-specialized-lambda-list lambda-list)
433     (declare (ignore parameters))
434     (multiple-value-bind (documentation declarations real-body)
435         (extract-declarations body env)
436       (values `(lambda ,unspecialized-lambda-list
437                  ,@(when documentation `(,documentation))
438                  (declare (%method-name ,(list name qualifiers specializers)))
439                  (declare (%method-lambda-list ,@lambda-list))
440                  ,@declarations
441                  ,@real-body)
442               unspecialized-lambda-list specializers))))
443
444 (defun real-make-method-initargs-form (proto-gf proto-method
445                                        method-lambda initargs env)
446   (declare (ignore proto-gf proto-method))
447   (unless (and (consp method-lambda) (eq (car method-lambda) 'lambda))
448     (error "The METHOD-LAMBDA argument to MAKE-METHOD-FUNCTION, ~S, ~
449             is not a lambda form."
450            method-lambda))
451   (make-method-initargs-form-internal method-lambda initargs env))
452
453 (unless (fboundp 'make-method-initargs-form)
454   (setf (gdefinition 'make-method-initargs-form)
455         (symbol-function 'real-make-method-initargs-form)))
456
457 (defun real-make-method-lambda (proto-gf proto-method method-lambda env)
458   (declare (ignore proto-gf proto-method))
459   (make-method-lambda-internal method-lambda env))
460
461 ;;; a helper function for creating Python-friendly type declarations
462 ;;; in DEFMETHOD forms
463 (defun parameter-specializer-declaration-in-defmethod (parameter specializer)
464   (cond ((and (consp specializer)
465               (eq (car specializer) 'eql))
466          ;; KLUDGE: ANSI, in its wisdom, says that
467          ;; EQL-SPECIALIZER-FORMs in EQL specializers are evaluated at
468          ;; DEFMETHOD expansion time. Thus, although one might think
469          ;; that in
470          ;;   (DEFMETHOD FOO ((X PACKAGE)
471          ;;                   (Y (EQL 12))
472          ;;      ..))
473          ;; the PACKAGE and (EQL 12) forms are both parallel type
474          ;; names, they're not, as is made clear when you do
475          ;;   (DEFMETHOD FOO ((X PACKAGE)
476          ;;                   (Y (EQL 'BAR)))
477          ;;     ..)
478          ;; where Y needs to be a symbol named "BAR", not some cons
479          ;; made by (CONS 'QUOTE 'BAR). I.e. when the
480          ;; EQL-SPECIALIZER-FORM is (EQL 'X), it requires an argument
481          ;; to be of type (EQL X). It'd be easy to transform one to
482          ;; the other, but it'd be somewhat messier to do so while
483          ;; ensuring that the EQL-SPECIALIZER-FORM is only EVAL'd
484          ;; once. (The new code wouldn't be messy, but it'd require a
485          ;; big transformation of the old code.) So instead we punt.
486          ;; -- WHN 20000610
487          '(ignorable))
488         ((member specializer
489                  ;; KLUDGE: For some low-level implementation
490                  ;; classes, perhaps because of some problems related
491                  ;; to the incomplete integration of PCL into SBCL's
492                  ;; type system, some specializer classes can't be
493                  ;; declared as argument types. E.g.
494                  ;;   (DEFMETHOD FOO ((X SLOT-OBJECT))
495                  ;;     (DECLARE (TYPE SLOT-OBJECT X))
496                  ;;     ..)
497                  ;; loses when
498                  ;;   (DEFSTRUCT BAR A B)
499                  ;;   (FOO (MAKE-BAR))
500                  ;; perhaps because of the way that STRUCTURE-OBJECT
501                  ;; inherits both from SLOT-OBJECT and from
502                  ;; SB-KERNEL:INSTANCE. In an effort to sweep such
503                  ;; problems under the rug, we exclude these problem
504                  ;; cases by blacklisting them here. -- WHN 2001-01-19
505                  '(slot-object))
506          '(ignorable))
507         ((not (eq *boot-state* 'complete))
508          ;; KLUDGE: PCL, in its wisdom, sometimes calls methods with
509          ;; types which don't match their specializers. (Specifically,
510          ;; it calls ENSURE-CLASS-USING-CLASS (T NULL) with a non-NULL
511          ;; second argument.) Hopefully it only does this kind of
512          ;; weirdness when bootstrapping.. -- WHN 20000610
513          '(ignorable))
514         (t
515          ;; Otherwise, we can make Python very happy.
516          `(type ,specializer ,parameter))))
517
518 (defun make-method-lambda-internal (method-lambda &optional env)
519   (unless (and (consp method-lambda) (eq (car method-lambda) 'lambda))
520     (error "The METHOD-LAMBDA argument to MAKE-METHOD-LAMBDA, ~S, ~
521             is not a lambda form."
522            method-lambda))
523   (multiple-value-bind (documentation declarations real-body)
524       (extract-declarations (cddr method-lambda) env)
525     (let* ((name-decl (get-declaration '%method-name declarations))
526            (sll-decl (get-declaration '%method-lambda-list declarations))
527            (method-name (when (consp name-decl) (car name-decl)))
528            (generic-function-name (when method-name (car method-name)))
529            (specialized-lambda-list (or sll-decl (cadr method-lambda))))
530       (multiple-value-bind (parameters lambda-list specializers)
531           (parse-specialized-lambda-list specialized-lambda-list)
532         (let* ((required-parameters
533                 (mapcar (lambda (r s) (declare (ignore s)) r)
534                         parameters
535                         specializers))
536                (slots (mapcar #'list required-parameters))
537                (calls (list nil))
538                (class-declarations
539                 `(declare
540                   ;; These declarations seem to be used by PCL to pass
541                   ;; information to itself; when I tried to delete 'em
542                   ;; ca. 0.6.10 it didn't work. I'm not sure how
543                   ;; they work, but note the (VARIABLE-DECLARATION '%CLASS ..)
544                   ;; expression in CAN-OPTIMIZE-ACCESS1. -- WHN 2000-12-30
545                   ,@(remove nil
546                             (mapcar (lambda (a s) (and (symbolp s)
547                                                        (neq s t)
548                                                        `(%class ,a ,s)))
549                                     parameters
550                                     specializers))
551                   ;; These TYPE declarations weren't in the original
552                   ;; PCL code, but the Python compiler likes them a
553                   ;; lot. (We're telling the compiler about our
554                   ;; knowledge of specialized argument types so that
555                   ;; it can avoid run-time type dispatch overhead,
556                   ;; which can be a huge win for Python.)
557                   ;;
558                   ;; FIXME: Perhaps these belong in
559                   ;; ADD-METHOD-DECLARATIONS instead of here?
560                   ,@(mapcar #'parameter-specializer-declaration-in-defmethod
561                             parameters
562                             specializers)))
563                (method-lambda
564                 ;; Remove the documentation string and insert the
565                 ;; appropriate class declarations. The documentation
566                 ;; string is removed to make it easy for us to insert
567                 ;; new declarations later, they will just go after the
568                 ;; CADR of the method lambda. The class declarations
569                 ;; are inserted to communicate the class of the method's
570                 ;; arguments to the code walk.
571                 `(lambda ,lambda-list
572                    ;; The default ignorability of method parameters
573                    ;; doesn't seem to be specified by ANSI. PCL had
574                    ;; them basically ignorable but was a little
575                    ;; inconsistent. E.g. even though the two
576                    ;; method definitions 
577                    ;;   (DEFMETHOD FOO ((X T) (Y T)) "Z")
578                    ;;   (DEFMETHOD FOO ((X T) Y) "Z")
579                    ;; are otherwise equivalent, PCL treated Y as
580                    ;; ignorable in the first definition but not in the
581                    ;; second definition. We make all required
582                    ;; parameters ignorable as a way of systematizing
583                    ;; the old PCL behavior. -- WHN 2000-11-24
584                    (declare (ignorable ,@required-parameters))
585                    ,class-declarations
586                    ,@declarations
587                    (block ,(fun-name-block-name generic-function-name)
588                      ,@real-body)))
589                (constant-value-p (and (null (cdr real-body))
590                                       (constantp (car real-body))))
591                (constant-value (and constant-value-p
592                                     (eval (car real-body))))
593                (plist (and constant-value-p
594                            (or (typep constant-value
595                                       '(or number character))
596                                (and (symbolp constant-value)
597                                     (symbol-package constant-value)))
598                            (list :constant-value constant-value)))
599                (applyp (dolist (p lambda-list nil)
600                          (cond ((memq p '(&optional &rest &key))
601                                 (return t))
602                                ((eq p '&aux)
603                                 (return nil))))))
604           (multiple-value-bind
605               (walked-lambda call-next-method-p closurep next-method-p-p)
606               (walk-method-lambda method-lambda
607                                   required-parameters
608                                   env
609                                   slots
610                                   calls)
611             (multiple-value-bind
612                 (ignore walked-declarations walked-lambda-body)
613                 (extract-declarations (cddr walked-lambda))
614               (declare (ignore ignore))
615               (when (or next-method-p-p call-next-method-p)
616                 (setq plist (list* :needs-next-methods-p t plist)))
617               (when (some #'cdr slots)
618                 (multiple-value-bind (slot-name-lists call-list)
619                     (slot-name-lists-from-slots slots calls)
620                   (let ((pv-table-symbol (make-symbol "pv-table")))
621                     (setq plist
622                           `(,@(when slot-name-lists
623                                 `(:slot-name-lists ,slot-name-lists))
624                               ,@(when call-list
625                                   `(:call-list ,call-list))
626                               :pv-table-symbol ,pv-table-symbol
627                               ,@plist))
628                     (setq walked-lambda-body
629                           `((pv-binding (,required-parameters
630                                          ,slot-name-lists
631                                          ,pv-table-symbol)
632                                         ,@walked-lambda-body))))))
633               (when (and (memq '&key lambda-list)
634                          (not (memq '&allow-other-keys lambda-list)))
635                 (let ((aux (memq '&aux lambda-list)))
636                 (setq lambda-list (nconc (ldiff lambda-list aux)
637                                          (list '&allow-other-keys)
638                                          aux))))
639               (values `(lambda (.method-args. .next-methods.)
640                          (simple-lexical-method-functions
641                           (,lambda-list .method-args. .next-methods.
642                                         :call-next-method-p
643                                         ,call-next-method-p
644                                         :next-method-p-p ,next-method-p-p
645                                         :closurep ,closurep
646                                         :applyp ,applyp)
647                           ,@walked-declarations
648                           ,@walked-lambda-body))
649                       `(,@(when plist
650                       `(:plist ,plist))
651                           ,@(when documentation
652                           `(:documentation ,documentation)))))))))))
653
654 (unless (fboundp 'make-method-lambda)
655   (setf (gdefinition 'make-method-lambda)
656         (symbol-function 'real-make-method-lambda)))
657
658 (defmacro simple-lexical-method-functions ((lambda-list
659                                             method-args
660                                             next-methods
661                                             &rest lmf-options)
662                                            &body body)
663   `(progn
664      ,method-args ,next-methods
665      (bind-simple-lexical-method-macros (,method-args ,next-methods)
666        (bind-lexical-method-functions (,@lmf-options)
667          (bind-args (,lambda-list ,method-args)
668            ,@body)))))
669
670 (defmacro fast-lexical-method-functions ((lambda-list
671                                           next-method-call
672                                           args
673                                           rest-arg
674                                           &rest lmf-options)
675                                          &body body)
676  `(bind-fast-lexical-method-macros (,args ,rest-arg ,next-method-call)
677     (bind-lexical-method-functions (,@lmf-options)
678       (bind-args (,(nthcdr (length args) lambda-list) ,rest-arg)
679         ,@body))))
680
681 (defmacro bind-simple-lexical-method-macros ((method-args next-methods)
682                                              &body body)
683   `(macrolet ((call-next-method-bind (&body body)
684                 `(let ((.next-method. (car ,',next-methods))
685                        (,',next-methods (cdr ,',next-methods)))
686                    .next-method. ,',next-methods
687                    ,@body))
688               (call-next-method-body (cnm-args)
689                 `(if .next-method.
690                      (funcall (if (std-instance-p .next-method.)
691                                   (method-function .next-method.)
692                                   .next-method.) ; for early methods
693                               (or ,cnm-args ,',method-args)
694                               ,',next-methods)
695                      (error "no next method")))
696               (next-method-p-body ()
697                 `(not (null .next-method.))))
698      ,@body))
699
700 (defstruct (method-call (:copier nil))
701   (function #'identity :type function)
702   call-method-args)
703
704 #-sb-fluid (declaim (sb-ext:freeze-type method-call))
705
706 (defmacro invoke-method-call1 (function args cm-args)
707   `(let ((.function. ,function)
708          (.args. ,args)
709          (.cm-args. ,cm-args))
710      (if (and .cm-args. (null (cdr .cm-args.)))
711          (funcall .function. .args. (car .cm-args.))
712          (apply .function. .args. .cm-args.))))
713
714 (defmacro invoke-method-call (method-call restp &rest required-args+rest-arg)
715   `(invoke-method-call1 (method-call-function ,method-call)
716                         ,(if restp
717                              `(list* ,@required-args+rest-arg)
718                              `(list ,@required-args+rest-arg))
719                         (method-call-call-method-args ,method-call)))
720
721 (defstruct (fast-method-call (:copier nil))
722   (function #'identity :type function)
723   pv-cell
724   next-method-call
725   arg-info)
726
727 #-sb-fluid (declaim (sb-ext:freeze-type fast-method-call))
728
729 (defmacro fmc-funcall (fn pv-cell next-method-call &rest args)
730   `(funcall ,fn ,pv-cell ,next-method-call ,@args))
731
732 (defmacro invoke-fast-method-call (method-call &rest required-args+rest-arg)
733   `(fmc-funcall (fast-method-call-function ,method-call)
734                 (fast-method-call-pv-cell ,method-call)
735                 (fast-method-call-next-method-call ,method-call)
736                 ,@required-args+rest-arg))
737
738 (defstruct (fast-instance-boundp (:copier nil))
739   (index 0 :type fixnum))
740
741 #-sb-fluid (declaim (sb-ext:freeze-type fast-instance-boundp))
742
743 (eval-when (:compile-toplevel :load-toplevel :execute)
744
745 (defvar *allow-emf-call-tracing-p* nil)
746 (defvar *enable-emf-call-tracing-p* #-testing nil #+testing t)
747
748 ) ; EVAL-WHEN
749 \f
750 ;;;; effective method functions
751
752 (defvar *emf-call-trace-size* 200)
753 (defvar *emf-call-trace* nil)
754 (defvar *emf-call-trace-index* 0)
755
756 ;;; This function was in the CMU CL version of PCL (ca Debian 2.4.8)
757 ;;; without explanation. It appears to be intended for debugging, so
758 ;;; it might be useful someday, so I haven't deleted it.
759 ;;; But it isn't documented and isn't used for anything now, so
760 ;;; I've conditionalized it out of the base system. -- WHN 19991213
761 #+sb-show
762 (defun show-emf-call-trace ()
763   (when *emf-call-trace*
764     (let ((j *emf-call-trace-index*)
765           (*enable-emf-call-tracing-p* nil))
766       (format t "~&(The oldest entries are printed first)~%")
767       (dotimes-fixnum (i *emf-call-trace-size*)
768         (let ((ct (aref *emf-call-trace* j)))
769           (when ct (print ct)))
770         (incf j)
771         (when (= j *emf-call-trace-size*)
772           (setq j 0))))))
773
774 (defun trace-emf-call-internal (emf format args)
775   (unless *emf-call-trace*
776     (setq *emf-call-trace* (make-array *emf-call-trace-size*)))
777   (setf (aref *emf-call-trace* *emf-call-trace-index*)
778         (list* emf format args))
779   (incf *emf-call-trace-index*)
780   (when (= *emf-call-trace-index* *emf-call-trace-size*)
781     (setq *emf-call-trace-index* 0)))
782
783 (defmacro trace-emf-call (emf format args)
784   (when *allow-emf-call-tracing-p*
785     `(when *enable-emf-call-tracing-p*
786        (trace-emf-call-internal ,emf ,format ,args))))
787
788 (defmacro invoke-effective-method-function-fast
789     (emf restp &rest required-args+rest-arg)
790   `(progn
791      (trace-emf-call ,emf ,restp (list ,@required-args+rest-arg))
792      (invoke-fast-method-call ,emf ,@required-args+rest-arg)))
793
794 (defmacro invoke-effective-method-function (emf restp
795                                                 &rest required-args+rest-arg)
796   (unless (constantp restp)
797     (error "The RESTP argument is not constant."))
798   (setq restp (eval restp))
799   `(locally
800
801      ;; In sbcl-0.6.11.43, the compiler would issue bogus warnings
802      ;; about type mismatches in unreachable code when we
803      ;; macroexpanded the GET-SLOTS-OR-NIL expressions here and
804      ;; byte-compiled the code. GET-SLOTS-OR-NIL is now an inline
805      ;; function instead of a macro, which seems sufficient to solve
806      ;; the problem all by itself (probably because of some quirk in
807      ;; the relative order of expansion and type inference) but we
808      ;; also use overkill by NOTINLINEing GET-SLOTS-OR-NIL, because it
809      ;; looks as though (1) inlining isn't that much of a win anyway,
810      ;; and (2a) once you miss the FAST-METHOD-CALL clause you're
811      ;; going to be slow anyway, but (2b) code bloat still hurts even
812      ;; when it's off the critical path.
813      (declare (notinline get-slots-or-nil))
814
815      (trace-emf-call ,emf ,restp (list ,@required-args+rest-arg))
816      (cond ((typep ,emf 'fast-method-call)
817              (invoke-fast-method-call ,emf ,@required-args+rest-arg))
818            ,@(when (and (null restp) (= 1 (length required-args+rest-arg)))
819                `(((typep ,emf 'fixnum)
820                   (let* ((.slots. (get-slots-or-nil
821                                    ,(car required-args+rest-arg)))
822                          (value (when .slots. (clos-slots-ref .slots. ,emf))))
823                     (if (eq value +slot-unbound+)
824                         (slot-unbound-internal ,(car required-args+rest-arg)
825                                                ,emf)
826                         value)))))
827            ,@(when (and (null restp) (= 2 (length required-args+rest-arg)))
828                `(((typep ,emf 'fixnum)
829                   (let ((.new-value. ,(car required-args+rest-arg))
830                         (.slots. (get-slots-or-nil
831                                   ,(car required-args+rest-arg))))
832                     (when .slots.
833                          (setf (clos-slots-ref .slots. ,emf) .new-value.))))))
834            #||
835            ,@(when (and (null restp) (= 1 (length required-args+rest-arg)))
836                `(((typep ,emf 'fast-instance-boundp)
837                   (let ((.slots. (get-slots-or-nil
838                                   ,(car required-args+rest-arg))))
839                     (and .slots.
840                          (not (eq (clos-slots-ref
841                                    .slots. (fast-instance-boundp-index ,emf))
842                                   +slot-unbound+)))))))
843            ||#
844            (t
845             (etypecase ,emf
846               (method-call
847                (invoke-method-call ,emf ,restp ,@required-args+rest-arg))
848               (function
849                ,(if restp
850                     `(apply (the function ,emf) ,@required-args+rest-arg)
851                     `(funcall (the function ,emf)
852                               ,@required-args+rest-arg))))))))
853
854 (defun invoke-emf (emf args)
855   (trace-emf-call emf t args)
856   (etypecase emf
857     (fast-method-call
858      (let* ((arg-info (fast-method-call-arg-info emf))
859             (restp (cdr arg-info))
860             (nreq (car arg-info)))
861        (if restp
862            (let* ((rest-args (nthcdr nreq args))
863                   (req-args (ldiff args rest-args)))
864              (apply (fast-method-call-function emf)
865                     (fast-method-call-pv-cell emf)
866                     (fast-method-call-next-method-call emf)
867                     (nconc req-args (list rest-args))))
868            (cond ((null args)
869                   (if (eql nreq 0)
870                       (invoke-fast-method-call emf)
871                       (error "wrong number of args")))
872                  ((null (cdr args))
873                   (if (eql nreq 1)
874                       (invoke-fast-method-call emf (car args))
875                       (error "wrong number of args")))
876                  ((null (cddr args))
877                   (if (eql nreq 2)
878                       (invoke-fast-method-call emf (car args) (cadr args))
879                       (error "wrong number of args")))
880                  (t
881                   (apply (fast-method-call-function emf)
882                          (fast-method-call-pv-cell emf)
883                          (fast-method-call-next-method-call emf)
884                          args))))))
885     (method-call
886      (apply (method-call-function emf)
887             args
888             (method-call-call-method-args emf)))
889     (fixnum
890      (cond ((null args) (error "1 or 2 args were expected."))
891            ((null (cdr args))
892             (let* ((slots (get-slots (car args)))
893                    (value (clos-slots-ref slots emf)))
894               (if (eq value +slot-unbound+)
895                   (slot-unbound-internal (car args) emf)
896                   value)))
897            ((null (cddr args))
898              (setf (clos-slots-ref (get-slots (cadr args)) emf)
899                    (car args)))
900            (t (error "1 or 2 args were expected."))))
901     (fast-instance-boundp
902      (if (or (null args) (cdr args))
903          (error "1 arg was expected.")
904        (let ((slots (get-slots (car args))))
905          (not (eq (clos-slots-ref slots
906                                   (fast-instance-boundp-index emf))
907                   +slot-unbound+)))))
908     (function
909      (apply emf args))))
910
911 ;; KLUDGE: A comment from the original PCL said "This can be improved alot."
912 (defun gf-make-function-from-emf (gf emf)
913   (etypecase emf
914     (fast-method-call (let* ((arg-info (gf-arg-info gf))
915                              (nreq (arg-info-number-required arg-info))
916                              (restp (arg-info-applyp arg-info)))
917                         #'(lambda (&rest args)
918                             (trace-emf-call emf t args)
919                             (apply (fast-method-call-function emf)
920                                    (fast-method-call-pv-cell emf)
921                                    (fast-method-call-next-method-call emf)
922                                    (if restp
923                                        (let* ((rest-args (nthcdr nreq args))
924                                               (req-args (ldiff args
925                                                                rest-args)))
926                                          (nconc req-args rest-args))
927                                        args)))))
928     (method-call #'(lambda (&rest args)
929                      (trace-emf-call emf t args)
930                      (apply (method-call-function emf)
931                             args
932                             (method-call-call-method-args emf))))
933     (function emf)))
934 \f
935 (defmacro bind-fast-lexical-method-macros ((args rest-arg next-method-call)
936                                            &body body)
937   `(macrolet ((call-next-method-bind (&body body)
938                 `(let () ,@body))
939               (call-next-method-body (cnm-args)
940                 `(if ,',next-method-call
941                      ,(if (and (null ',rest-arg)
942                                (consp cnm-args)
943                                (eq (car cnm-args) 'list))
944                           `(invoke-effective-method-function
945                             ,',next-method-call nil
946                             ,@(cdr cnm-args))
947                           (let ((call `(invoke-effective-method-function
948                                         ,',next-method-call
949                                         ,',(not (null rest-arg))
950                                         ,@',args
951                                         ,@',(when rest-arg `(,rest-arg)))))
952                             `(if ,cnm-args
953                                  (bind-args ((,@',args
954                                               ,@',(when rest-arg
955                                                     `(&rest ,rest-arg)))
956                                              ,cnm-args)
957                                             ,call)
958                                  ,call)))
959                      (error "no next method")))
960               (next-method-p-body ()
961                 `(not (null ,',next-method-call))))
962      ,@body))
963
964 (defmacro bind-lexical-method-functions
965     ((&key call-next-method-p next-method-p-p closurep applyp)
966      &body body)
967   (cond ((and (null call-next-method-p) (null next-method-p-p)
968               (null closurep)
969               (null applyp))
970          `(let () ,@body))
971         ((and (null closurep)
972               (null applyp))
973          ;; OK to use MACROLET, and all args are mandatory
974          ;; (else APPLYP would be true).
975          `(call-next-method-bind
976             (macrolet ((call-next-method (&rest cnm-args)
977                          `(call-next-method-body ,(when cnm-args
978                                                     `(list ,@cnm-args))))
979                        (next-method-p ()
980                          `(next-method-p-body)))
981                ,@body)))
982         (t
983          `(call-next-method-bind
984             (flet (,@(and call-next-method-p
985                           '((call-next-method (&rest cnm-args)
986                               (call-next-method-body cnm-args))))
987                    ,@(and next-method-p-p
988                           '((next-method-p ()
989                               (next-method-p-body)))))
990               ,@body)))))
991
992 (defmacro bind-args ((lambda-list args) &body body)
993   (let ((args-tail '.args-tail.)
994         (key '.key.)
995         (state 'required))
996     (flet ((process-var (var)
997              (if (memq var lambda-list-keywords)
998                  (progn
999                    (case var
1000                      (&optional       (setq state 'optional))
1001                      (&key            (setq state 'key))
1002                      (&allow-other-keys)
1003                      (&rest           (setq state 'rest))
1004                      (&aux            (setq state 'aux))
1005                      (otherwise
1006                       (error
1007                        "encountered the non-standard lambda list keyword ~S"
1008                        var)))
1009                    nil)
1010                  (case state
1011                    (required `((,var (pop ,args-tail))))
1012                    (optional (cond ((not (consp var))
1013                                     `((,var (when ,args-tail
1014                                               (pop ,args-tail)))))
1015                                    ((null (cddr var))
1016                                     `((,(car var) (if ,args-tail
1017                                                       (pop ,args-tail)
1018                                                       ,(cadr var)))))
1019                                    (t
1020                                     `((,(caddr var) ,args-tail)
1021                                       (,(car var) (if ,args-tail
1022                                                       (pop ,args-tail)
1023                                                       ,(cadr var)))))))
1024                    (rest `((,var ,args-tail)))
1025                    (key (cond ((not (consp var))
1026                                `((,var (get-key-arg ,(keywordicate var)
1027                                                     ,args-tail))))
1028                               ((null (cddr var))
1029                                (multiple-value-bind (keyword variable)
1030                                    (if (consp (car var))
1031                                        (values (caar var)
1032                                                (cadar var))
1033                                        (values (keywordicate (car var))
1034                                                (car var)))
1035                                  `((,key (get-key-arg1 ',keyword ,args-tail))
1036                                    (,variable (if (consp ,key)
1037                                                   (car ,key)
1038                                                   ,(cadr var))))))
1039                               (t
1040                                (multiple-value-bind (keyword variable)
1041                                    (if (consp (car var))
1042                                        (values (caar var)
1043                                                (cadar var))
1044                                        (values (keywordicate (car var))
1045                                                (car var)))
1046                                  `((,key (get-key-arg1 ',keyword ,args-tail))
1047                                    (,(caddr var) ,key)
1048                                    (,variable (if (consp ,key)
1049                                                   (car ,key)
1050                                                   ,(cadr var))))))))
1051                    (aux `(,var))))))
1052       (let ((bindings (mapcan #'process-var lambda-list)))
1053         `(let* ((,args-tail ,args)
1054                 ,@bindings)
1055            (declare (ignorable ,args-tail))
1056            ,@body)))))
1057
1058 (defun get-key-arg (keyword list)
1059   (loop (when (atom list) (return nil))
1060         (when (eq (car list) keyword) (return (cadr list)))
1061         (setq list (cddr list))))
1062
1063 (defun get-key-arg1 (keyword list)
1064   (loop (when (atom list) (return nil))
1065         (when (eq (car list) keyword) (return (cdr list)))
1066         (setq list (cddr list))))
1067
1068 (defun walk-method-lambda (method-lambda required-parameters env slots calls)
1069   (let ((call-next-method-p nil)   ; flag indicating that CALL-NEXT-METHOD
1070                                    ; should be in the method definition
1071         (closurep nil)             ; flag indicating that #'CALL-NEXT-METHOD
1072                                    ; was seen in the body of a method
1073         (next-method-p-p nil))     ; flag indicating that NEXT-METHOD-P
1074                                    ; should be in the method definition
1075     (flet ((walk-function (form context env)
1076              (cond ((not (eq context ':eval)) form)
1077                    ;; FIXME: Jumping to a conclusion from the way it's used
1078                    ;; above, perhaps CONTEXT should be called SITUATION
1079                    ;; (after the term used in the ANSI specification of
1080                    ;; EVAL-WHEN) and given modern ANSI keyword values
1081                    ;; like :LOAD-TOPLEVEL.
1082                    ((not (listp form)) form)
1083                    ((eq (car form) 'call-next-method)
1084                     (setq call-next-method-p t)
1085                     form)
1086                    ((eq (car form) 'next-method-p)
1087                     (setq next-method-p-p t)
1088                     form)
1089                    ((and (eq (car form) 'function)
1090                          (cond ((eq (cadr form) 'call-next-method)
1091                                 (setq call-next-method-p t)
1092                                 (setq closurep t)
1093                                 form)
1094                                ((eq (cadr form) 'next-method-p)
1095                                 (setq next-method-p-p t)
1096                                 (setq closurep t)
1097                                 form)
1098                                (t nil))))
1099                    ((and (memq (car form)
1100                                '(slot-value set-slot-value slot-boundp))
1101                          (constantp (caddr form)))
1102                      (let ((parameter (can-optimize-access form
1103                                                            required-parameters
1104                                                            env)))
1105                       (let ((fun (ecase (car form)
1106                                    (slot-value #'optimize-slot-value)
1107                                    (set-slot-value #'optimize-set-slot-value)
1108                                    (slot-boundp #'optimize-slot-boundp))))
1109                         (funcall fun slots parameter form))))
1110                    ((and (eq (car form) 'apply)
1111                          (consp (cadr form))
1112                          (eq (car (cadr form)) 'function)
1113                          (generic-function-name-p (cadr (cadr form))))
1114                     (optimize-generic-function-call
1115                      form required-parameters env slots calls))
1116                    ((generic-function-name-p (car form))
1117                     (optimize-generic-function-call
1118                      form required-parameters env slots calls))
1119                    ((and (eq (car form) 'asv-funcall)
1120                          *optimize-asv-funcall-p*)
1121                     (case (fourth form)
1122                       (reader (push (third form) *asv-readers*))
1123                       (writer (push (third form) *asv-writers*))
1124                       (boundp (push (third form) *asv-boundps*)))
1125                     `(,(second form) ,@(cddddr form)))
1126                    (t form))))
1127
1128       (let ((walked-lambda (walk-form method-lambda env #'walk-function)))
1129         (values walked-lambda
1130                 call-next-method-p
1131                 closurep
1132                 next-method-p-p)))))
1133
1134 (defun generic-function-name-p (name)
1135   (and (legal-fun-name-p name)
1136        (gboundp name)
1137        (if (eq *boot-state* 'complete)
1138            (standard-generic-function-p (gdefinition name))
1139            (funcallable-instance-p (gdefinition name)))))
1140 \f
1141 (defvar *method-function-plist* (make-hash-table :test 'eq))
1142 (defvar *mf1* nil)
1143 (defvar *mf1p* nil)
1144 (defvar *mf1cp* nil)
1145 (defvar *mf2* nil)
1146 (defvar *mf2p* nil)
1147 (defvar *mf2cp* nil)
1148
1149 (defun method-function-plist (method-function)
1150   (unless (eq method-function *mf1*)
1151     (rotatef *mf1* *mf2*)
1152     (rotatef *mf1p* *mf2p*)
1153     (rotatef *mf1cp* *mf2cp*))
1154   (unless (or (eq method-function *mf1*) (null *mf1cp*))
1155     (setf (gethash *mf1* *method-function-plist*) *mf1p*))
1156   (unless (eq method-function *mf1*)
1157     (setf *mf1* method-function
1158           *mf1cp* nil
1159           *mf1p* (gethash method-function *method-function-plist*)))
1160   *mf1p*)
1161
1162 (defun (setf method-function-plist)
1163     (val method-function)
1164   (unless (eq method-function *mf1*)
1165     (rotatef *mf1* *mf2*)
1166     (rotatef *mf1cp* *mf2cp*)
1167     (rotatef *mf1p* *mf2p*))
1168   (unless (or (eq method-function *mf1*) (null *mf1cp*))
1169     (setf (gethash *mf1* *method-function-plist*) *mf1p*))
1170   (setf *mf1* method-function
1171         *mf1cp* t
1172         *mf1p* val))
1173
1174 (defun method-function-get (method-function key &optional default)
1175   (getf (method-function-plist method-function) key default))
1176
1177 (defun (setf method-function-get)
1178     (val method-function key)
1179   (setf (getf (method-function-plist method-function) key) val))
1180
1181 (defun method-function-pv-table (method-function)
1182   (method-function-get method-function :pv-table))
1183
1184 (defun method-function-method (method-function)
1185   (method-function-get method-function :method))
1186
1187 (defun method-function-needs-next-methods-p (method-function)
1188   (method-function-get method-function :needs-next-methods-p t))
1189 \f
1190 (defmacro method-function-closure-generator (method-function)
1191   `(method-function-get ,method-function 'closure-generator))
1192
1193 (defun load-defmethod
1194     (class name quals specls ll initargs &optional pv-table-symbol)
1195   (setq initargs (copy-tree initargs))
1196   (let ((method-spec (or (getf initargs ':method-spec)
1197                          (make-method-spec name quals specls))))
1198     (setf (getf initargs ':method-spec) method-spec)
1199     (load-defmethod-internal class name quals specls
1200                              ll initargs pv-table-symbol)))
1201
1202 (defun load-defmethod-internal
1203     (method-class gf-spec qualifiers specializers lambda-list
1204                   initargs pv-table-symbol)
1205   (when pv-table-symbol
1206     (setf (getf (getf initargs ':plist) :pv-table-symbol)
1207           pv-table-symbol))
1208   (when (and (eq *boot-state* 'complete)
1209              (fboundp gf-spec))
1210     (let* ((gf (fdefinition gf-spec))
1211            (method (and (generic-function-p gf)
1212                         (find-method gf
1213                                      qualifiers
1214                                      (parse-specializers specializers)
1215                                      nil))))
1216       (when method
1217         (sb-kernel::style-warn "redefining ~S~{ ~S~} ~S in DEFMETHOD"
1218                                gf-spec qualifiers specializers))))
1219   (let ((method (apply #'add-named-method
1220                        gf-spec qualifiers specializers lambda-list
1221                        :definition-source `((defmethod ,gf-spec
1222                                                 ,@qualifiers
1223                                               ,specializers)
1224                                             ,*load-truename*)
1225                        initargs)))
1226     (unless (or (eq method-class 'standard-method)
1227                 (eq (find-class method-class nil) (class-of method)))
1228       ;; FIXME: should be STYLE-WARNING?
1229       (format *error-output*
1230               "~&At the time the method with qualifiers ~:S and~%~
1231                specializers ~:S on the generic function ~S~%~
1232                was compiled, the method-class for that generic function was~%~
1233                ~S. But, the method class is now ~S, this~%~
1234                may mean that this method was compiled improperly.~%"
1235               qualifiers specializers gf-spec
1236               method-class (class-name (class-of method))))
1237     method))
1238
1239 (defun make-method-spec (gf-spec qualifiers unparsed-specializers)
1240   `(method ,gf-spec ,@qualifiers ,unparsed-specializers))
1241
1242 (defun initialize-method-function (initargs &optional return-function-p method)
1243   (let* ((mf (getf initargs ':function))
1244          (method-spec (getf initargs ':method-spec))
1245          (plist (getf initargs ':plist))
1246          (pv-table-symbol (getf plist ':pv-table-symbol))
1247          (pv-table nil)
1248          (mff (getf initargs ':fast-function)))
1249     (flet ((set-mf-property (p v)
1250              (when mf
1251                (setf (method-function-get mf p) v))
1252              (when mff
1253                (setf (method-function-get mff p) v))))
1254       (when method-spec
1255         (when mf
1256           (setq mf (set-fun-name mf method-spec)))
1257         (when mff
1258           (let ((name `(,(or (get (car method-spec) 'fast-sym)
1259                              (setf (get (car method-spec) 'fast-sym)
1260                                    ;; KLUDGE: If we're going to be
1261                                    ;; interning private symbols in our
1262                                    ;; a this way, it would be cleanest
1263                                    ;; to use a separate package
1264                                    ;; %PCL-PRIVATE or something, and
1265                                    ;; failing that, to use a special
1266                                    ;; symbol prefix denoting privateness.
1267                                    ;; -- WHN 19991201
1268                                    (intern (format nil "FAST-~A"
1269                                                    (car method-spec))
1270                                            *pcl-package*)))
1271                          ,@(cdr method-spec))))
1272             (set-fun-name mff name)
1273             (unless mf
1274               (set-mf-property :name name)))))
1275       (when plist
1276         (let ((snl (getf plist :slot-name-lists))
1277               (cl (getf plist :call-list)))
1278           (when (or snl cl)
1279             (setq pv-table (intern-pv-table :slot-name-lists snl
1280                                             :call-list cl))
1281             (when pv-table (set pv-table-symbol pv-table))
1282             (set-mf-property :pv-table pv-table)))
1283         (loop (when (null plist) (return nil))
1284               (set-mf-property (pop plist) (pop plist)))
1285         (when method
1286           (set-mf-property :method method))
1287         (when return-function-p
1288           (or mf (method-function-from-fast-function mff)))))))
1289 \f
1290 (defun analyze-lambda-list (lambda-list)
1291   (flet (;; FIXME: Is this redundant with SB-C::MAKE-KEYWORD-FOR-ARG?
1292          (parse-key-argument (arg)
1293            (if (listp arg)
1294                (if (listp (car arg))
1295                    (caar arg)
1296                    (keywordicate (car arg)))
1297                (keywordicate arg))))
1298     (let ((nrequired 0)
1299           (noptional 0)
1300           (keysp nil)
1301           (restp nil)
1302           (allow-other-keys-p nil)
1303           (keywords ())
1304           (keyword-parameters ())
1305           (state 'required))
1306       (dolist (x lambda-list)
1307         (if (memq x lambda-list-keywords)
1308             (case x
1309               (&optional         (setq state 'optional))
1310               (&key              (setq keysp t
1311                                        state 'key))
1312               (&allow-other-keys (setq allow-other-keys-p t))
1313               (&rest             (setq restp t
1314                                        state 'rest))
1315               (&aux           (return t))
1316               (otherwise
1317                 (error "encountered the non-standard lambda list keyword ~S"
1318                        x)))
1319             (ecase state
1320               (required  (incf nrequired))
1321               (optional  (incf noptional))
1322               (key       (push (parse-key-argument x) keywords)
1323                          (push x keyword-parameters))
1324               (rest      ()))))
1325       (values nrequired noptional keysp restp allow-other-keys-p
1326               (reverse keywords)
1327               (reverse keyword-parameters)))))
1328
1329 (defun keyword-spec-name (x)
1330   (let ((key (if (atom x) x (car x))))
1331     (if (atom key)
1332         (keywordicate key)
1333         (car key))))
1334
1335 (defun ftype-declaration-from-lambda-list (lambda-list name)
1336   (multiple-value-bind (nrequired noptional keysp restp allow-other-keys-p
1337                                   keywords keyword-parameters)
1338       (analyze-lambda-list lambda-list)
1339     (declare (ignore keyword-parameters))
1340     (let* ((old (info :function :type name)) ;FIXME:FDOCUMENTATION instead?
1341            (old-ftype (if (sb-kernel:fun-type-p old) old nil))
1342            (old-restp (and old-ftype (sb-kernel:fun-type-rest old-ftype)))
1343            (old-keys (and old-ftype
1344                           (mapcar #'sb-kernel:key-info-name
1345                                   (sb-kernel:fun-type-keywords
1346                                    old-ftype))))
1347            (old-keysp (and old-ftype (sb-kernel:fun-type-keyp old-ftype)))
1348            (old-allowp (and old-ftype
1349                             (sb-kernel:fun-type-allowp old-ftype)))
1350            (keywords (union old-keys (mapcar #'keyword-spec-name keywords))))
1351       `(function ,(append (make-list nrequired :initial-element t)
1352                           (when (plusp noptional)
1353                             (append '(&optional)
1354                                     (make-list noptional :initial-element t)))
1355                           (when (or restp old-restp)
1356                             '(&rest t))
1357                           (when (or keysp old-keysp)
1358                             (append '(&key)
1359                                     (mapcar #'(lambda (key)
1360                                                 `(,key t))
1361                                             keywords)
1362                                     (when (or allow-other-keys-p old-allowp)
1363                                       '(&allow-other-keys)))))
1364                  *))))
1365
1366 (defun defgeneric-declaration (spec lambda-list)
1367   (when (consp spec)
1368     (setq spec (get-setf-fun-name (cadr spec))))
1369   `(ftype ,(ftype-declaration-from-lambda-list lambda-list spec) ,spec))
1370 \f
1371 ;;;; early generic function support
1372
1373 (defvar *!early-generic-functions* ())
1374
1375 (defun ensure-generic-function (fun-name
1376                                 &rest all-keys
1377                                 &key environment
1378                                 &allow-other-keys)
1379   (declare (ignore environment))
1380   (let ((existing (and (gboundp fun-name)
1381                        (gdefinition fun-name))))
1382     (if (and existing
1383              (eq *boot-state* 'complete)
1384              (null (generic-function-p existing)))
1385         (generic-clobbers-function fun-name)
1386         (apply #'ensure-generic-function-using-class
1387                existing fun-name all-keys))))
1388
1389 (defun generic-clobbers-function (fun-name)
1390   (error 'simple-program-error
1391          :format-control "~S already names an ordinary function or a macro."
1392          :format-arguments (list fun-name)))
1393
1394 (defvar *sgf-wrapper*
1395   (boot-make-wrapper (early-class-size 'standard-generic-function)
1396                      'standard-generic-function))
1397
1398 (defvar *sgf-slots-init*
1399   (mapcar #'(lambda (canonical-slot)
1400               (if (memq (getf canonical-slot :name) '(arg-info source))
1401                   +slot-unbound+
1402                   (let ((initfunction (getf canonical-slot :initfunction)))
1403                     (if initfunction
1404                         (funcall initfunction)
1405                         +slot-unbound+))))
1406           (early-collect-inheritance 'standard-generic-function)))
1407
1408 (defvar *sgf-method-class-index*
1409   (!bootstrap-slot-index 'standard-generic-function 'method-class))
1410
1411 (defun early-gf-p (x)
1412   (and (fsc-instance-p x)
1413        (eq (clos-slots-ref (get-slots x) *sgf-method-class-index*)
1414            +slot-unbound+)))
1415
1416 (defvar *sgf-methods-index*
1417   (!bootstrap-slot-index 'standard-generic-function 'methods))
1418
1419 (defmacro early-gf-methods (gf)
1420   `(clos-slots-ref (get-slots ,gf) *sgf-methods-index*))
1421
1422 (defvar *sgf-arg-info-index*
1423   (!bootstrap-slot-index 'standard-generic-function 'arg-info))
1424
1425 (defmacro early-gf-arg-info (gf)
1426   `(clos-slots-ref (get-slots ,gf) *sgf-arg-info-index*))
1427
1428 (defvar *sgf-dfun-state-index*
1429   (!bootstrap-slot-index 'standard-generic-function 'dfun-state))
1430
1431 (defstruct (arg-info
1432             (:conc-name nil)
1433             (:constructor make-arg-info ())
1434             (:copier nil))
1435   (arg-info-lambda-list :no-lambda-list)
1436   arg-info-precedence
1437   arg-info-metatypes
1438   arg-info-number-optional
1439   arg-info-key/rest-p
1440   arg-info-keys   ;nil        no &KEY or &REST allowed
1441                   ;(k1 k2 ..) Each method must accept these &KEY arguments.
1442                   ;T          must have &KEY or &REST
1443
1444   gf-info-simple-accessor-type ; nil, reader, writer, boundp
1445   (gf-precompute-dfun-and-emf-p nil) ; set by set-arg-info
1446
1447   gf-info-static-c-a-m-emf
1448   (gf-info-c-a-m-emf-std-p t)
1449   gf-info-fast-mf-p)
1450
1451 #-sb-fluid (declaim (sb-ext:freeze-type arg-info))
1452
1453 (defun arg-info-valid-p (arg-info)
1454   (not (null (arg-info-number-optional arg-info))))
1455
1456 (defun arg-info-applyp (arg-info)
1457   (or (plusp (arg-info-number-optional arg-info))
1458       (arg-info-key/rest-p arg-info)))
1459
1460 (defun arg-info-number-required (arg-info)
1461   (length (arg-info-metatypes arg-info)))
1462
1463 (defun arg-info-nkeys (arg-info)
1464   (count-if #'(lambda (x) (neq x t)) (arg-info-metatypes arg-info)))
1465
1466 ;;; Keep pages clean by not setting if the value is already the same.
1467 (defmacro esetf (pos val)
1468   (let ((valsym (gensym "value")))
1469     `(let ((,valsym ,val))
1470        (unless (equal ,pos ,valsym)
1471          (setf ,pos ,valsym)))))
1472
1473 (defun set-arg-info (gf &key new-method (lambda-list nil lambda-list-p)
1474                         argument-precedence-order)
1475   (let* ((arg-info (if (eq *boot-state* 'complete)
1476                        (gf-arg-info gf)
1477                        (early-gf-arg-info gf)))
1478          (methods (if (eq *boot-state* 'complete)
1479                       (generic-function-methods gf)
1480                       (early-gf-methods gf)))
1481          (was-valid-p (integerp (arg-info-number-optional arg-info)))
1482          (first-p (and new-method (null (cdr methods)))))
1483     (when (and (not lambda-list-p) methods)
1484       (setq lambda-list (gf-lambda-list gf)))
1485     (when (or lambda-list-p
1486               (and first-p
1487                    (eq (arg-info-lambda-list arg-info) ':no-lambda-list)))
1488       (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1489           (analyze-lambda-list lambda-list)
1490         (when (and methods (not first-p))
1491           (let ((gf-nreq (arg-info-number-required arg-info))
1492                 (gf-nopt (arg-info-number-optional arg-info))
1493                 (gf-key/rest-p (arg-info-key/rest-p arg-info)))
1494             (unless (and (= nreq gf-nreq)
1495                          (= nopt gf-nopt)
1496                          (eq (or keysp restp) gf-key/rest-p))
1497               (error "The lambda-list ~S is incompatible with ~
1498                      existing methods of ~S."
1499                      lambda-list gf))))
1500         (when lambda-list-p
1501           (esetf (arg-info-lambda-list arg-info) lambda-list))
1502         (when (or lambda-list-p argument-precedence-order
1503                   (null (arg-info-precedence arg-info)))
1504           (esetf (arg-info-precedence arg-info)
1505                  (compute-precedence lambda-list nreq
1506                                      argument-precedence-order)))
1507         (esetf (arg-info-metatypes arg-info) (make-list nreq))
1508         (esetf (arg-info-number-optional arg-info) nopt)
1509         (esetf (arg-info-key/rest-p arg-info) (not (null (or keysp restp))))
1510         (esetf (arg-info-keys arg-info)
1511                (if lambda-list-p
1512                    (if allow-other-keys-p t keywords)
1513                    (arg-info-key/rest-p arg-info)))))
1514     (when new-method
1515       (check-method-arg-info gf arg-info new-method))
1516     (set-arg-info1 gf arg-info new-method methods was-valid-p first-p)
1517     arg-info))
1518
1519 (defun check-method-arg-info (gf arg-info method)
1520   (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1521       (analyze-lambda-list (if (consp method)
1522                                (early-method-lambda-list method)
1523                                (method-lambda-list method)))
1524     (flet ((lose (string &rest args)
1525              (error
1526               "attempt to add the method ~S to the generic function ~S.~%~
1527                But ~A"
1528               method
1529               gf
1530               (apply #'format nil string args)))
1531            (comparison-description (x y)
1532              (if (> x y) "more" "fewer")))
1533       (let ((gf-nreq (arg-info-number-required arg-info))
1534             (gf-nopt (arg-info-number-optional arg-info))
1535             (gf-key/rest-p (arg-info-key/rest-p arg-info))
1536             (gf-keywords (arg-info-keys arg-info)))
1537         (unless (= nreq gf-nreq)
1538           (lose
1539            "the method has ~A required arguments than the generic function."
1540            (comparison-description nreq gf-nreq)))
1541         (unless (= nopt gf-nopt)
1542           (lose
1543            "the method has ~A optional arguments than the generic function."
1544            (comparison-description nopt gf-nopt)))
1545         (unless (eq (or keysp restp) gf-key/rest-p)
1546           (error
1547            "The method and generic function differ in whether they accept~%~
1548             &REST or &KEY arguments."))
1549         (when (consp gf-keywords)
1550           (unless (or (and restp (not keysp))
1551                       allow-other-keys-p
1552                       (every #'(lambda (k) (memq k keywords)) gf-keywords))
1553             (lose "the method does not accept each of the &KEY arguments~%~
1554                    ~S."
1555                   gf-keywords)))))))
1556
1557 (defun set-arg-info1 (gf arg-info new-method methods was-valid-p first-p)
1558   (let* ((existing-p (and methods (cdr methods) new-method))
1559          (nreq (length (arg-info-metatypes arg-info)))
1560          (metatypes (if existing-p
1561                         (arg-info-metatypes arg-info)
1562                         (make-list nreq)))
1563          (type (if existing-p
1564                    (gf-info-simple-accessor-type arg-info)
1565                    nil)))
1566     (when (arg-info-valid-p arg-info)
1567       (dolist (method (if new-method (list new-method) methods))
1568         (let* ((specializers (if (or (eq *boot-state* 'complete)
1569                                      (not (consp method)))
1570                                  (method-specializers method)
1571                                  (early-method-specializers method t)))
1572                (class (if (or (eq *boot-state* 'complete) (not (consp method)))
1573                           (class-of method)
1574                           (early-method-class method)))
1575                (new-type (when (and class
1576                                     (or (not (eq *boot-state* 'complete))
1577                                         (eq (generic-function-method-combination gf)
1578                                             *standard-method-combination*)))
1579                            (cond ((eq class *the-class-standard-reader-method*)
1580                                   'reader)
1581                                  ((eq class *the-class-standard-writer-method*)
1582                                   'writer)
1583                                  ((eq class *the-class-standard-boundp-method*)
1584                                   'boundp)))))
1585           (setq metatypes (mapcar #'raise-metatype metatypes specializers))
1586           (setq type (cond ((null type) new-type)
1587                            ((eq type new-type) type)
1588                            (t nil)))))
1589       (esetf (arg-info-metatypes arg-info) metatypes)
1590       (esetf (gf-info-simple-accessor-type arg-info) type)))
1591   (when (or (not was-valid-p) first-p)
1592     (multiple-value-bind (c-a-m-emf std-p)
1593         (if (early-gf-p gf)
1594             (values t t)
1595             (compute-applicable-methods-emf gf))
1596       (esetf (gf-info-static-c-a-m-emf arg-info) c-a-m-emf)
1597       (esetf (gf-info-c-a-m-emf-std-p arg-info) std-p)
1598       (unless (gf-info-c-a-m-emf-std-p arg-info)
1599         (esetf (gf-info-simple-accessor-type arg-info) t))))
1600   (unless was-valid-p
1601     (let ((name (if (eq *boot-state* 'complete)
1602                     (generic-function-name gf)
1603                     (!early-gf-name gf))))
1604       (esetf (gf-precompute-dfun-and-emf-p arg-info)
1605              (let* ((sym (if (atom name) name (cadr name)))
1606                     (pkg-list (cons *pcl-package*
1607                                     (package-use-list *pcl-package*))))
1608                (and sym (symbolp sym)
1609                     (not (null (memq (symbol-package sym) pkg-list)))
1610                     (not (find #\space (symbol-name sym))))))))
1611   (esetf (gf-info-fast-mf-p arg-info)
1612          (or (not (eq *boot-state* 'complete))
1613              (let* ((method-class (generic-function-method-class gf))
1614                     (methods (compute-applicable-methods
1615                               #'make-method-lambda
1616                               (list gf (class-prototype method-class)
1617                                     '(lambda) nil))))
1618                (and methods (null (cdr methods))
1619                     (let ((specls (method-specializers (car methods))))
1620                       (and (classp (car specls))
1621                            (eq 'standard-generic-function
1622                                (class-name (car specls)))
1623                            (classp (cadr specls))
1624                            (eq 'standard-method
1625                                (class-name (cadr specls)))))))))
1626   arg-info)
1627
1628 ;;; This is the early definition of ENSURE-GENERIC-FUNCTION-USING-CLASS.
1629 ;;;
1630 ;;; The STATIC-SLOTS field of the funcallable instances used as early
1631 ;;; generic functions is used to store the early methods and early
1632 ;;; discriminator code for the early generic function. The static
1633 ;;; slots field of the fins contains a list whose:
1634 ;;;    CAR    -   a list of the early methods on this early gf
1635 ;;;    CADR   -   the early discriminator code for this method
1636 (defun ensure-generic-function-using-class (existing spec &rest keys
1637                                             &key (lambda-list nil
1638                                                               lambda-list-p)
1639                                             &allow-other-keys)
1640   (declare (ignore keys))
1641   (cond ((and existing (early-gf-p existing))
1642          existing)
1643         ((assoc spec *!generic-function-fixups* :test #'equal)
1644          (if existing
1645              (make-early-gf spec lambda-list lambda-list-p existing)
1646              (error "The function ~S is not already defined." spec)))
1647         (existing
1648          (error "~S should be on the list ~S."
1649                 spec
1650                 '*!generic-function-fixups*))
1651         (t
1652          (pushnew spec *!early-generic-functions* :test #'equal)
1653          (make-early-gf spec lambda-list lambda-list-p))))
1654
1655 (defun make-early-gf (spec &optional lambda-list lambda-list-p function)
1656   (let ((fin (allocate-funcallable-instance *sgf-wrapper* *sgf-slots-init*)))
1657     (set-funcallable-instance-fun
1658      fin
1659      (or function
1660          (if (eq spec 'print-object)
1661              #'(sb-kernel:instance-lambda (instance stream)
1662                  (print-unreadable-object (instance stream :identity t)
1663                    (format stream "std-instance")))
1664              #'(sb-kernel:instance-lambda (&rest args)
1665                  (declare (ignore args))
1666                  (error "The function of the funcallable-instance ~S~
1667                          has not been set." fin)))))
1668     (setf (gdefinition spec) fin)
1669     (!bootstrap-set-slot 'standard-generic-function fin 'name spec)
1670     (!bootstrap-set-slot 'standard-generic-function
1671                          fin
1672                          'source
1673                          *load-truename*)
1674     (set-fun-name fin spec)
1675     (let ((arg-info (make-arg-info)))
1676       (setf (early-gf-arg-info fin) arg-info)
1677       (when lambda-list-p
1678         (proclaim (defgeneric-declaration spec lambda-list))
1679         (set-arg-info fin :lambda-list lambda-list)))
1680     fin))
1681
1682 (defun set-dfun (gf &optional dfun cache info)
1683   (when cache
1684     (setf (cache-owner cache) gf))
1685   (let ((new-state (if (and dfun (or cache info))
1686                        (list* dfun cache info)
1687                        dfun)))
1688     (if (eq *boot-state* 'complete)
1689         (setf (gf-dfun-state gf) new-state)
1690         (setf (clos-slots-ref (get-slots gf) *sgf-dfun-state-index*)
1691               new-state)))
1692   dfun)
1693
1694 (defun gf-dfun-cache (gf)
1695   (let ((state (if (eq *boot-state* 'complete)
1696                    (gf-dfun-state gf)
1697                    (clos-slots-ref (get-slots gf) *sgf-dfun-state-index*))))
1698     (typecase state
1699       (function nil)
1700       (cons (cadr state)))))
1701
1702 (defun gf-dfun-info (gf)
1703   (let ((state (if (eq *boot-state* 'complete)
1704                    (gf-dfun-state gf)
1705                    (clos-slots-ref (get-slots gf) *sgf-dfun-state-index*))))
1706     (typecase state
1707       (function nil)
1708       (cons (cddr state)))))
1709
1710 (defvar *sgf-name-index*
1711   (!bootstrap-slot-index 'standard-generic-function 'name))
1712
1713 (defun !early-gf-name (gf)
1714   (clos-slots-ref (get-slots gf) *sgf-name-index*))
1715
1716 (defun gf-lambda-list (gf)
1717   (let ((arg-info (if (eq *boot-state* 'complete)
1718                       (gf-arg-info gf)
1719                       (early-gf-arg-info gf))))
1720     (if (eq ':no-lambda-list (arg-info-lambda-list arg-info))
1721         (let ((methods (if (eq *boot-state* 'complete)
1722                            (generic-function-methods gf)
1723                            (early-gf-methods gf))))
1724           (if (null methods)
1725               (progn
1726                 (warn "no way to determine the lambda list for ~S" gf)
1727                 nil)
1728               (let* ((method (car (last methods)))
1729                      (ll (if (consp method)
1730                              (early-method-lambda-list method)
1731                              (method-lambda-list method)))
1732                      (k (member '&key ll)))
1733                 (if k
1734                     (append (ldiff ll (cdr k)) '(&allow-other-keys))
1735                     ll))))
1736         (arg-info-lambda-list arg-info))))
1737
1738 (defmacro real-ensure-gf-internal (gf-class all-keys env)
1739   `(progn
1740      (cond ((symbolp ,gf-class)
1741             (setq ,gf-class (find-class ,gf-class t ,env)))
1742            ((classp ,gf-class))
1743            (t
1744             (error "The :GENERIC-FUNCTION-CLASS argument (~S) was neither a~%~
1745                     class nor a symbol that names a class."
1746                    ,gf-class)))
1747      (remf ,all-keys :generic-function-class)
1748      (remf ,all-keys :environment)
1749      (let ((combin (getf ,all-keys :method-combination '.shes-not-there.)))
1750        (unless (eq combin '.shes-not-there.)
1751          (setf (getf ,all-keys :method-combination)
1752                (find-method-combination (class-prototype ,gf-class)
1753                                         (car combin)
1754                                         (cdr combin)))))
1755     (let ((method-class (getf ,all-keys :method-class '.shes-not-there.)))
1756       (unless (eq method-class '.shes-not-there.)
1757         (setf (getf ,all-keys :method-class)
1758                 (find-class method-class t ,env))))))
1759
1760 (defun real-ensure-gf-using-class--generic-function
1761        (existing
1762         fun-name
1763         &rest all-keys
1764         &key environment (lambda-list nil lambda-list-p)
1765              (generic-function-class 'standard-generic-function gf-class-p)
1766         &allow-other-keys)
1767   (real-ensure-gf-internal generic-function-class all-keys environment)
1768   (unless (or (null gf-class-p)
1769               (eq (class-of existing) generic-function-class))
1770     (change-class existing generic-function-class))
1771   (prog1
1772       (apply #'reinitialize-instance existing all-keys)
1773     (when lambda-list-p
1774       (proclaim (defgeneric-declaration fun-name lambda-list)))))
1775
1776 (defun real-ensure-gf-using-class--null
1777        (existing
1778         fun-name
1779         &rest all-keys
1780         &key environment (lambda-list nil lambda-list-p)
1781              (generic-function-class 'standard-generic-function)
1782         &allow-other-keys)
1783   (declare (ignore existing))
1784   (real-ensure-gf-internal generic-function-class all-keys environment)
1785   (prog1
1786       (setf (gdefinition fun-name)
1787             (apply #'make-instance generic-function-class
1788                    :name fun-name all-keys))
1789     (when lambda-list-p
1790       (proclaim (defgeneric-declaration fun-name lambda-list)))))
1791 \f
1792 (defun get-generic-function-info (gf)
1793   ;; values   nreq applyp metatypes nkeys arg-info
1794   (multiple-value-bind (applyp metatypes arg-info)
1795       (let* ((arg-info (if (early-gf-p gf)
1796                            (early-gf-arg-info gf)
1797                            (gf-arg-info gf)))
1798              (metatypes (arg-info-metatypes arg-info)))
1799         (values (arg-info-applyp arg-info)
1800                 metatypes
1801                 arg-info))
1802     (values (length metatypes) applyp metatypes
1803             (count-if #'(lambda (x) (neq x t)) metatypes)
1804             arg-info)))
1805
1806 (defun early-make-a-method (class qualifiers arglist specializers initargs doc
1807                             &optional slot-name)
1808   (initialize-method-function initargs)
1809   (let ((parsed ())
1810         (unparsed ()))
1811     ;; Figure out whether we got class objects or class names as the
1812     ;; specializers and set parsed and unparsed appropriately. If we
1813     ;; got class objects, then we can compute unparsed, but if we got
1814     ;; class names we don't try to compute parsed.
1815     ;;
1816     ;; Note that the use of not symbolp in this call to every should be
1817     ;; read as 'classp' we can't use classp itself because it doesn't
1818     ;; exist yet.
1819     (if (every #'(lambda (s) (not (symbolp s))) specializers)
1820         (setq parsed specializers
1821               unparsed (mapcar #'(lambda (s)
1822                                    (if (eq s t) t (class-name s)))
1823                                specializers))
1824         (setq unparsed specializers
1825               parsed ()))
1826     (list :early-method           ;This is an early method dammit!
1827
1828           (getf initargs ':function)
1829           (getf initargs ':fast-function)
1830
1831           parsed                  ;The parsed specializers. This is used
1832                                   ;by early-method-specializers to cache
1833                                   ;the parse. Note that this only comes
1834                                   ;into play when there is more than one
1835                                   ;early method on an early gf.
1836
1837           (list class        ;A list to which real-make-a-method
1838                 qualifiers      ;can be applied to make a real method
1839                 arglist    ;corresponding to this early one.
1840                 unparsed
1841                 initargs
1842                 doc
1843                 slot-name))))
1844
1845 (defun real-make-a-method
1846        (class qualifiers lambda-list specializers initargs doc
1847         &optional slot-name)
1848   (setq specializers (parse-specializers specializers))
1849   (apply #'make-instance class
1850          :qualifiers qualifiers
1851          :lambda-list lambda-list
1852          :specializers specializers
1853          :documentation doc
1854          :slot-name slot-name
1855          :allow-other-keys t
1856          initargs))
1857
1858 (defun early-method-function (early-method)
1859   (values (cadr early-method) (caddr early-method)))
1860
1861 (defun early-method-class (early-method)
1862   (find-class (car (fifth early-method))))
1863
1864 (defun early-method-standard-accessor-p (early-method)
1865   (let ((class (first (fifth early-method))))
1866     (or (eq class 'standard-reader-method)
1867         (eq class 'standard-writer-method)
1868         (eq class 'standard-boundp-method))))
1869
1870 (defun early-method-standard-accessor-slot-name (early-method)
1871   (seventh (fifth early-method)))
1872
1873 ;;; Fetch the specializers of an early method. This is basically just
1874 ;;; a simple accessor except that when the second argument is t, this
1875 ;;; converts the specializers from symbols into class objects. The
1876 ;;; class objects are cached in the early method, this makes
1877 ;;; bootstrapping faster because the class objects only have to be
1878 ;;; computed once.
1879 ;;;
1880 ;;; NOTE:
1881 ;;;  The second argument should only be passed as T by
1882 ;;;  early-lookup-method. This is to implement the rule that only when
1883 ;;;  there is more than one early method on a generic function is the
1884 ;;;  conversion from class names to class objects done. This
1885 ;;;  corresponds to the fact that we are only allowed to have one
1886 ;;;  method on any generic function up until the time classes exist.
1887 (defun early-method-specializers (early-method &optional objectsp)
1888   (if (and (listp early-method)
1889            (eq (car early-method) :early-method))
1890       (cond ((eq objectsp t)
1891              (or (fourth early-method)
1892                  (setf (fourth early-method)
1893                        (mapcar #'find-class (cadddr (fifth early-method))))))
1894             (t
1895              (cadddr (fifth early-method))))
1896       (error "~S is not an early-method." early-method)))
1897
1898 (defun early-method-qualifiers (early-method)
1899   (cadr (fifth early-method)))
1900
1901 (defun early-method-lambda-list (early-method)
1902   (caddr (fifth early-method)))
1903
1904 (defun early-add-named-method (generic-function-name
1905                                qualifiers
1906                                specializers
1907                                arglist
1908                                &rest initargs)
1909   (let* ((gf (ensure-generic-function generic-function-name))
1910          (existing
1911            (dolist (m (early-gf-methods gf))
1912              (when (and (equal (early-method-specializers m) specializers)
1913                         (equal (early-method-qualifiers m) qualifiers))
1914                (return m))))
1915          (new (make-a-method 'standard-method
1916                              qualifiers
1917                              arglist
1918                              specializers
1919                              initargs
1920                              ())))
1921     (when existing (remove-method gf existing))
1922     (add-method gf new)))
1923
1924 ;;; This is the early version of ADD-METHOD. Later this will become a
1925 ;;; generic function. See !FIX-EARLY-GENERIC-FUNCTIONS which has
1926 ;;; special knowledge about ADD-METHOD.
1927 (defun add-method (generic-function method)
1928   (when (not (fsc-instance-p generic-function))
1929     (error "Early ADD-METHOD didn't get a funcallable instance."))
1930   (when (not (and (listp method) (eq (car method) :early-method)))
1931     (error "Early ADD-METHOD didn't get an early method."))
1932   (push method (early-gf-methods generic-function))
1933   (set-arg-info generic-function :new-method method)
1934   (unless (assoc (!early-gf-name generic-function)
1935                  *!generic-function-fixups*
1936                  :test #'equal)
1937     (update-dfun generic-function)))
1938
1939 ;;; This is the early version of REMOVE-METHOD. See comments on
1940 ;;; the early version of ADD-METHOD.
1941 (defun remove-method (generic-function method)
1942   (when (not (fsc-instance-p generic-function))
1943     (error "An early remove-method didn't get a funcallable instance."))
1944   (when (not (and (listp method) (eq (car method) :early-method)))
1945     (error "An early remove-method didn't get an early method."))
1946   (setf (early-gf-methods generic-function)
1947         (remove method (early-gf-methods generic-function)))
1948   (set-arg-info generic-function)
1949   (unless (assoc (!early-gf-name generic-function)
1950                  *!generic-function-fixups*
1951                  :test #'equal)
1952     (update-dfun generic-function)))
1953
1954 ;;; This is the early version of GET-METHOD. See comments on the early
1955 ;;; version of ADD-METHOD.
1956 (defun get-method (generic-function qualifiers specializers
1957                                     &optional (errorp t))
1958   (if (early-gf-p generic-function)
1959       (or (dolist (m (early-gf-methods generic-function))
1960             (when (and (or (equal (early-method-specializers m nil)
1961                                   specializers)
1962                            (equal (early-method-specializers m t)
1963                                   specializers))
1964                        (equal (early-method-qualifiers m) qualifiers))
1965               (return m)))
1966           (if errorp
1967               (error "can't get early method")
1968               nil))
1969       (real-get-method generic-function qualifiers specializers errorp)))
1970
1971 (defun !fix-early-generic-functions ()
1972   (let ((accessors nil))
1973     ;; Rearrange *!EARLY-GENERIC-FUNCTIONS* to speed up
1974     ;; FIX-EARLY-GENERIC-FUNCTIONS.
1975     (dolist (early-gf-spec *!early-generic-functions*)
1976       (when (every #'early-method-standard-accessor-p
1977                    (early-gf-methods (gdefinition early-gf-spec)))
1978         (push early-gf-spec accessors)))
1979     (dolist (spec (nconc accessors
1980                          '(accessor-method-slot-name
1981                            generic-function-methods
1982                            method-specializers
1983                            specializerp
1984                            specializer-type
1985                            specializer-class
1986                            slot-definition-location
1987                            slot-definition-name
1988                            class-slots
1989                            gf-arg-info
1990                            class-precedence-list
1991                            slot-boundp-using-class
1992                            (setf slot-value-using-class)
1993                            slot-value-using-class
1994                            structure-class-p
1995                            standard-class-p
1996                            funcallable-standard-class-p
1997                            specializerp)))
1998       (/show spec)
1999       (setq *!early-generic-functions*
2000             (cons spec
2001                   (delete spec *!early-generic-functions* :test #'equal))))
2002
2003     (dolist (early-gf-spec *!early-generic-functions*)
2004       (/show early-gf-spec)
2005       (let* ((gf (gdefinition early-gf-spec))
2006              (methods (mapcar #'(lambda (early-method)
2007                                   (let ((args (copy-list (fifth
2008                                                           early-method))))
2009                                     (setf (fourth args)
2010                                           (early-method-specializers
2011                                            early-method t))
2012                                     (apply #'real-make-a-method args)))
2013                               (early-gf-methods gf))))
2014         (setf (generic-function-method-class gf) *the-class-standard-method*)
2015         (setf (generic-function-method-combination gf)
2016               *standard-method-combination*)
2017         (set-methods gf methods)))
2018
2019     (dolist (fn *!early-functions*)
2020       (/show fn)
2021       (setf (gdefinition (car fn)) (fdefinition (caddr fn))))
2022
2023     (dolist (fixup *!generic-function-fixups*)
2024       (/show fixup)
2025       (let* ((fspec (car fixup))
2026              (gf (gdefinition fspec))
2027              (methods (mapcar #'(lambda (method)
2028                                   (let* ((lambda-list (first method))
2029                                          (specializers (second method))
2030                                          (method-fn-name (third method))
2031                                          (fn-name (or method-fn-name fspec))
2032                                          (fn (fdefinition fn-name))
2033                                          (initargs
2034                                           (list :function
2035                                                 (set-fun-name
2036                                                  #'(lambda (args next-methods)
2037                                                      (declare (ignore
2038                                                                next-methods))
2039                                                      (apply fn args))
2040                                                  `(call ,fn-name)))))
2041                                     (declare (type function fn))
2042                                     (make-a-method 'standard-method
2043                                                    ()
2044                                                    lambda-list
2045                                                    specializers
2046                                                    initargs
2047                                                    nil)))
2048                               (cdr fixup))))
2049         (setf (generic-function-method-class gf) *the-class-standard-method*)
2050         (setf (generic-function-method-combination gf)
2051               *standard-method-combination*)
2052         (set-methods gf methods))))
2053   (/show "leaving !FIX-EARLY-GENERIC-FUNCTIONS"))
2054 \f
2055 ;;; PARSE-DEFMETHOD is used by DEFMETHOD to parse the &REST argument
2056 ;;; into the 'real' arguments. This is where the syntax of DEFMETHOD
2057 ;;; is really implemented.
2058 (defun parse-defmethod (cdr-of-form)
2059   (declare (list cdr-of-form))
2060   (let ((name (pop cdr-of-form))
2061         (qualifiers ())
2062         (spec-ll ()))
2063     (loop (if (and (car cdr-of-form) (atom (car cdr-of-form)))
2064               (push (pop cdr-of-form) qualifiers)
2065               (return (setq qualifiers (nreverse qualifiers)))))
2066     (setq spec-ll (pop cdr-of-form))
2067     (values name qualifiers spec-ll cdr-of-form)))
2068
2069 (defun parse-specializers (specializers)
2070   (declare (list specializers))
2071   (flet ((parse (spec)
2072            (let ((result (specializer-from-type spec)))
2073              (if (specializerp result)
2074                  result
2075                  (if (symbolp spec)
2076                      (error "~S was used as a specializer,~%~
2077                              but is not the name of a class."
2078                             spec)
2079                      (error "~S is not a legal specializer." spec))))))
2080     (mapcar #'parse specializers)))
2081
2082 (defun unparse-specializers (specializers-or-method)
2083   (if (listp specializers-or-method)
2084       (flet ((unparse (spec)
2085                (if (specializerp spec)
2086                    (let ((type (specializer-type spec)))
2087                      (if (and (consp type)
2088                               (eq (car type) 'class))
2089                          (let* ((class (cadr type))
2090                                 (class-name (class-name class)))
2091                            (if (eq class (find-class class-name nil))
2092                                class-name
2093                                type))
2094                          type))
2095                    (error "~S is not a legal specializer." spec))))
2096         (mapcar #'unparse specializers-or-method))
2097       (unparse-specializers (method-specializers specializers-or-method))))
2098
2099 (defun parse-method-or-spec (spec &optional (errorp t))
2100   (let (gf method name temp)
2101     (if (method-p spec) 
2102         (setq method spec
2103               gf (method-generic-function method)
2104               temp (and gf (generic-function-name gf))
2105               name (if temp
2106                        (intern-fun-name
2107                          (make-method-spec temp
2108                                            (method-qualifiers method)
2109                                            (unparse-specializers
2110                                              (method-specializers method))))
2111                        (make-symbol (format nil "~S" method))))
2112         (multiple-value-bind (gf-spec quals specls)
2113             (parse-defmethod spec)
2114           (and (setq gf (and (or errorp (gboundp gf-spec))
2115                              (gdefinition gf-spec)))
2116                (let ((nreq (compute-discriminating-function-arglist-info gf)))
2117                  (setq specls (append (parse-specializers specls)
2118                                       (make-list (- nreq (length specls))
2119                                                  :initial-element
2120                                                  *the-class-t*)))
2121                  (and
2122                    (setq method (get-method gf quals specls errorp))
2123                    (setq name
2124                          (intern-fun-name (make-method-spec gf-spec
2125                                                             quals
2126                                                             specls))))))))
2127     (values gf method name)))
2128 \f
2129 (defun extract-parameters (specialized-lambda-list)
2130   (multiple-value-bind (parameters ignore1 ignore2)
2131       (parse-specialized-lambda-list specialized-lambda-list)
2132     (declare (ignore ignore1 ignore2))
2133     parameters))
2134
2135 (defun extract-lambda-list (specialized-lambda-list)
2136   (multiple-value-bind (ignore1 lambda-list ignore2)
2137       (parse-specialized-lambda-list specialized-lambda-list)
2138     (declare (ignore ignore1 ignore2))
2139     lambda-list))
2140
2141 (defun extract-specializer-names (specialized-lambda-list)
2142   (multiple-value-bind (ignore1 ignore2 specializers)
2143       (parse-specialized-lambda-list specialized-lambda-list)
2144     (declare (ignore ignore1 ignore2))
2145     specializers))
2146
2147 (defun extract-required-parameters (specialized-lambda-list)
2148   (multiple-value-bind (ignore1 ignore2 ignore3 required-parameters)
2149       (parse-specialized-lambda-list specialized-lambda-list)
2150     (declare (ignore ignore1 ignore2 ignore3))
2151     required-parameters))
2152
2153 (defun parse-specialized-lambda-list (arglist &optional post-keyword)
2154   ;;(declare (values parameters lambda-list specializers required-parameters))
2155   (let ((arg (car arglist)))
2156     (cond ((null arglist) (values nil nil nil nil))
2157           ((eq arg '&aux)
2158            (values nil arglist nil))
2159           ((memq arg lambda-list-keywords)
2160            (unless (memq arg '(&optional &rest &key &allow-other-keys &aux))
2161              ;; Warn about non-standard lambda-list-keywords, but then
2162              ;; go on to treat them like a standard lambda-list-keyword
2163              ;; what with the warning its probably ok.
2164              ;;
2165              ;; FIXME: This shouldn't happen now that this is maintained
2166              ;; as part of SBCL, should it? Perhaps this is now
2167              ;; "internal error: unrecognized lambda-list keyword ~S"?
2168              (warn "Unrecognized lambda-list keyword ~S in arglist.~%~
2169                     Assuming that the symbols following it are parameters,~%~
2170                     and not allowing any parameter specializers to follow it."
2171                    arg))
2172            ;; When we are at a lambda-list keyword, the parameters
2173            ;; don't include the lambda-list keyword; the lambda-list
2174            ;; does include the lambda-list keyword; and no
2175            ;; specializers are allowed to follow the lambda-list
2176            ;; keywords (at least for now).
2177            (multiple-value-bind (parameters lambda-list)
2178                (parse-specialized-lambda-list (cdr arglist) t)
2179              (values parameters
2180                      (cons arg lambda-list)
2181                      ()
2182                      ())))
2183           (post-keyword
2184            ;; After a lambda-list keyword there can be no specializers.
2185            (multiple-value-bind (parameters lambda-list)
2186                (parse-specialized-lambda-list (cdr arglist) t)
2187              (values (cons (if (listp arg) (car arg) arg) parameters)
2188                      (cons arg lambda-list)
2189                      ()
2190                      ())))
2191           (t
2192            (multiple-value-bind (parameters lambda-list specializers required)
2193                (parse-specialized-lambda-list (cdr arglist))
2194              (values (cons (if (listp arg) (car arg) arg) parameters)
2195                      (cons (if (listp arg) (car arg) arg) lambda-list)
2196                      (cons (if (listp arg) (cadr arg) t) specializers)
2197                      (cons (if (listp arg) (car arg) arg) required)))))))
2198 \f
2199 (setq *boot-state* 'early)
2200 \f
2201 ;;; FIXME: In here there was a #-CMU definition of SYMBOL-MACROLET
2202 ;;; which used %WALKER stuff. That suggests to me that maybe the code
2203 ;;; walker stuff was only used for implementing stuff like that; maybe
2204 ;;; it's not needed any more? Hunt down what it was used for and see.
2205
2206 (defmacro with-slots (slots instance &body body)
2207   (let ((in (gensym)))
2208     `(let ((,in ,instance))
2209        (declare (ignorable ,in))
2210        ,@(let ((instance (if (and (consp instance) (eq (car instance) 'the))
2211                              (third instance)
2212                              instance)))
2213            (and (symbolp instance)
2214                 `((declare (%variable-rebinding ,in ,instance)))))
2215        ,in
2216        (symbol-macrolet ,(mapcar #'(lambda (slot-entry)
2217                                      (let ((variable-name
2218                                             (if (symbolp slot-entry)
2219                                                 slot-entry
2220                                                 (car slot-entry)))
2221                                            (slot-name
2222                                             (if (symbolp slot-entry)
2223                                                 slot-entry
2224                                                 (cadr slot-entry))))
2225                                        `(,variable-name
2226                                           (slot-value ,in ',slot-name))))
2227                                  slots)
2228                         ,@body))))
2229
2230 (defmacro with-accessors (slots instance &body body)
2231   (let ((in (gensym)))
2232     `(let ((,in ,instance))
2233        (declare (ignorable ,in))
2234        ,@(let ((instance (if (and (consp instance) (eq (car instance) 'the))
2235                              (third instance)
2236                              instance)))
2237            (and (symbolp instance)
2238                 `((declare (%variable-rebinding ,in ,instance)))))
2239        ,in
2240        (symbol-macrolet ,(mapcar #'(lambda (slot-entry)
2241                                    (let ((variable-name (car slot-entry))
2242                                          (accessor-name (cadr slot-entry)))
2243                                      `(,variable-name
2244                                         (,accessor-name ,in))))
2245                                slots)
2246           ,@body))))