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