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