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