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