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