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