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