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