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