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