1.0.48.23: faster with-arguments CALL-NEXT-METHOD
[sbcl.git] / src / pcl / boot.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 #|
27
28 The CommonLoops evaluator is meta-circular.
29
30 Most of the code in PCL is methods on generic functions, including
31 most of the code that actually implements generic functions and method
32 lookup.
33
34 So, we have a classic bootstrapping problem. The solution to this is
35 to first get a cheap implementation of generic functions running,
36 these are called early generic functions. These early generic
37 functions and the corresponding early methods and early method lookup
38 are used to get enough of the system running that it is possible to
39 create real generic functions and methods and implement real method
40 lookup. At that point (done in the file FIXUP) the function
41 !FIX-EARLY-GENERIC-FUNCTIONS is called to convert all the early generic
42 functions to real generic functions.
43
44 The cheap generic functions are built using the same
45 FUNCALLABLE-INSTANCE objects that real generic functions are made out of.
46 This means that as PCL is being bootstrapped, the cheap generic
47 function objects which are being created are the same objects which
48 will later be real generic functions. This is good because:
49   - we don't cons garbage structure, and
50   - we can keep pointers to the cheap generic function objects
51     during booting because those pointers will still point to
52     the right object after the generic functions are all fixed up.
53
54 This file defines the DEFMETHOD macro and the mechanism used to expand
55 it. This includes the mechanism for processing the body of a method.
56 DEFMETHOD basically expands into a call to LOAD-DEFMETHOD, which
57 basically calls ADD-METHOD to add the method to the generic function.
58 These expansions can be loaded either during bootstrapping or when PCL
59 is fully up and running.
60
61 An important effect of this arrangement is it means we can compile
62 files with DEFMETHOD forms in them in a completely running PCL, but
63 then load those files back in during bootstrapping. This makes
64 development easier. It also means there is only one set of code for
65 processing DEFMETHOD. Bootstrapping works by being sure to have
66 LOAD-METHOD be careful to call only primitives which work during
67 bootstrapping.
68
69 |#
70
71 (declaim (notinline make-a-method add-named-method
72                     ensure-generic-function-using-class
73                     add-method remove-method))
74
75 (defvar *!early-functions*
76   '((make-a-method early-make-a-method real-make-a-method)
77     (add-named-method early-add-named-method real-add-named-method)))
78
79 ;;; For each of the early functions, arrange to have it point to its
80 ;;; early definition. Do this in a way that makes sure that if we
81 ;;; redefine one of the early definitions the redefinition will take
82 ;;; effect. This makes development easier.
83 (dolist (fns *!early-functions*)
84   (let ((name (car fns))
85         (early-name (cadr fns)))
86     (setf (gdefinition name)
87             (set-fun-name
88              (lambda (&rest args)
89                (apply (fdefinition early-name) args))
90              name))))
91
92 ;;; *!GENERIC-FUNCTION-FIXUPS* is used by !FIX-EARLY-GENERIC-FUNCTIONS
93 ;;; to convert the few functions in the bootstrap which are supposed
94 ;;; to be generic functions but can't be early on.
95 ;;;
96 ;;; each entry is a list of name and lambda-list, class names as
97 ;;; specializers, and method body function name.
98 (defvar *!generic-function-fixups*
99   '((add-method
100      ((generic-function method)
101       (standard-generic-function method)
102       real-add-method))
103     (remove-method
104      ((generic-function method)
105       (standard-generic-function method)
106       real-remove-method))
107     (get-method
108      ((generic-function qualifiers specializers &optional (errorp t))
109       (standard-generic-function t t)
110       real-get-method))
111     (ensure-generic-function-using-class
112      ((generic-function fun-name
113                         &key generic-function-class environment
114                         &allow-other-keys)
115       (generic-function t)
116       real-ensure-gf-using-class--generic-function)
117      ((generic-function fun-name
118                         &key generic-function-class environment
119                         &allow-other-keys)
120       (null t)
121       real-ensure-gf-using-class--null))
122     (make-method-lambda
123      ((proto-generic-function proto-method lambda-expression environment)
124       (standard-generic-function standard-method t t)
125       real-make-method-lambda))
126     (make-method-specializers-form
127      ((proto-generic-function proto-method specializer-names environment)
128       (standard-generic-function standard-method t t)
129       real-make-method-specializers-form))
130     (parse-specializer-using-class
131      ((generic-function specializer)
132       (standard-generic-function t)
133       real-parse-specializer-using-class))
134     (unparse-specializer-using-class
135      ((generic-function specializer)
136       (standard-generic-function t)
137       real-unparse-specializer-using-class))
138     (make-method-initargs-form
139      ((proto-generic-function proto-method
140                               lambda-expression
141                               lambda-list environment)
142       (standard-generic-function standard-method t t t)
143       real-make-method-initargs-form))
144     (compute-effective-method
145      ((generic-function combin applicable-methods)
146       (generic-function standard-method-combination t)
147       standard-compute-effective-method))))
148 \f
149 (defmacro defgeneric (fun-name lambda-list &body options)
150   (declare (type list lambda-list))
151   (unless (legal-fun-name-p fun-name)
152     (error 'simple-program-error
153            :format-control "illegal generic function name ~S"
154            :format-arguments (list fun-name)))
155   (check-gf-lambda-list lambda-list)
156   (let ((initargs ())
157         (methods ()))
158     (flet ((duplicate-option (name)
159              (error 'simple-program-error
160                     :format-control "The option ~S appears more than once."
161                     :format-arguments (list name)))
162            (expand-method-definition (qab) ; QAB = qualifiers, arglist, body
163              (let* ((arglist-pos (position-if #'listp qab))
164                     (arglist (elt qab arglist-pos))
165                     (qualifiers (subseq qab 0 arglist-pos))
166                     (body (nthcdr (1+ arglist-pos) qab)))
167                `(push (defmethod ,fun-name ,@qualifiers ,arglist ,@body)
168                       (generic-function-initial-methods (fdefinition ',fun-name))))))
169       (macrolet ((initarg (key) `(getf initargs ,key)))
170         (dolist (option options)
171           (let ((car-option (car option)))
172             (case car-option
173               (declare
174                (when (and
175                       (consp (cadr option))
176                       (member (first (cadr option))
177                               ;; FIXME: this list is slightly weird.
178                               ;; ANSI (on the DEFGENERIC page) in one
179                               ;; place allows only OPTIMIZE; in
180                               ;; another place gives this list of
181                               ;; disallowed declaration specifiers.
182                               ;; This seems to be the only place where
183                               ;; the FUNCTION declaration is
184                               ;; mentioned; TYPE seems to be missing.
185                               ;; Very strange.  -- CSR, 2002-10-21
186                               '(declaration ftype function
187                                 inline notinline special)))
188                  (error 'simple-program-error
189                         :format-control "The declaration specifier ~S ~
190                                          is not allowed inside DEFGENERIC."
191                         :format-arguments (list (cadr option))))
192                (push (cadr option) (initarg :declarations)))
193               (:method-combination
194                (when (initarg car-option)
195                  (duplicate-option car-option))
196                (unless (symbolp (cadr option))
197                  (error 'simple-program-error
198                         :format-control "METHOD-COMBINATION name not a ~
199                                          symbol: ~S"
200                         :format-arguments (list (cadr option))))
201                (setf (initarg car-option)
202                      `',(cdr option)))
203               (:argument-precedence-order
204                (let* ((required (parse-lambda-list lambda-list))
205                       (supplied (cdr option)))
206                  (unless (= (length required) (length supplied))
207                    (error 'simple-program-error
208                           :format-control "argument count discrepancy in ~
209                                            :ARGUMENT-PRECEDENCE-ORDER clause."
210                           :format-arguments nil))
211                  (when (set-difference required supplied)
212                    (error 'simple-program-error
213                           :format-control "unequal sets for ~
214                                            :ARGUMENT-PRECEDENCE-ORDER clause: ~
215                                            ~S and ~S"
216                           :format-arguments (list required supplied)))
217                  (setf (initarg car-option)
218                        `',(cdr option))))
219               ((:documentation :generic-function-class :method-class)
220                (unless (proper-list-of-length-p option 2)
221                  (error "bad list length for ~S" option))
222                (if (initarg car-option)
223                    (duplicate-option car-option)
224                    (setf (initarg car-option) `',(cadr option))))
225               (:method
226                (push (cdr option) methods))
227               (t
228                ;; ANSI requires that unsupported things must get a
229                ;; PROGRAM-ERROR.
230                (error 'simple-program-error
231                       :format-control "unsupported option ~S"
232                       :format-arguments (list option))))))
233
234         (when (initarg :declarations)
235           (setf (initarg :declarations)
236                 `',(initarg :declarations))))
237       `(progn
238          (eval-when (:compile-toplevel :load-toplevel :execute)
239            (compile-or-load-defgeneric ',fun-name))
240          (load-defgeneric ',fun-name ',lambda-list
241                           (sb-c:source-location) ,@initargs)
242         ,@(mapcar #'expand-method-definition methods)
243         (fdefinition ',fun-name)))))
244
245 (defun compile-or-load-defgeneric (fun-name)
246   (proclaim-as-fun-name fun-name)
247   (note-name-defined fun-name :function)
248   (unless (eq (info :function :where-from fun-name) :declared)
249     (setf (info :function :where-from fun-name) :defined)
250     (setf (info :function :type fun-name)
251           (specifier-type 'function))))
252
253 (defun load-defgeneric (fun-name lambda-list source-location &rest initargs)
254   (when (fboundp fun-name)
255     (warn 'sb-kernel:redefinition-with-defgeneric
256           :name fun-name
257           :new-location source-location)
258     (let ((fun (fdefinition fun-name)))
259       (when (generic-function-p fun)
260         (loop for method in (generic-function-initial-methods fun)
261               do (remove-method fun method))
262         (setf (generic-function-initial-methods fun) '()))))
263   (apply #'ensure-generic-function
264          fun-name
265          :lambda-list lambda-list
266          :definition-source source-location
267          initargs))
268
269 (define-condition generic-function-lambda-list-error
270     (reference-condition simple-program-error)
271   ()
272   (:default-initargs :references (list '(:ansi-cl :section (3 4 2)))))
273
274 (defun check-gf-lambda-list (lambda-list)
275   (flet ((ensure (arg ok)
276            (unless ok
277              (error 'generic-function-lambda-list-error
278                     :format-control
279                     "~@<invalid ~S ~_in the generic function lambda list ~S~:>"
280                     :format-arguments (list arg lambda-list)))))
281     (multiple-value-bind (required optional restp rest keyp keys allowp
282                           auxp aux morep more-context more-count)
283         (parse-lambda-list lambda-list)
284       (declare (ignore required)) ; since they're no different in a gf ll
285       (declare (ignore restp rest)) ; since they're no different in a gf ll
286       (declare (ignore allowp)) ; since &ALLOW-OTHER-KEYS is fine either way
287       (declare (ignore aux)) ; since we require AUXP=NIL
288       (declare (ignore more-context more-count)) ; safely ignored unless MOREP
289       ;; no defaults allowed for &OPTIONAL arguments
290       (dolist (i optional)
291         (ensure i (or (symbolp i)
292                       (and (consp i) (symbolp (car i)) (null (cdr i))))))
293       ;; no defaults allowed for &KEY arguments
294       (when keyp
295         (dolist (i keys)
296           (ensure i (or (symbolp i)
297                         (and (consp i)
298                              (or (symbolp (car i))
299                                  (and (consp (car i))
300                                       (symbolp (caar i))
301                                       (symbolp (cadar i))
302                                       (null (cddar i))))
303                              (null (cdr i)))))))
304       ;; no &AUX allowed
305       (when auxp
306         (error "&AUX is not allowed in a generic function lambda list: ~S"
307                lambda-list))
308       ;; Oh, *puhlease*... not specifically as per section 3.4.2 of
309       ;; the ANSI spec, but the CMU CL &MORE extension does not
310       ;; belong here!
311       (aver (not morep)))))
312 \f
313 (defmacro defmethod (&rest args)
314   (multiple-value-bind (name qualifiers lambda-list body)
315       (parse-defmethod args)
316     `(progn
317       ;; KLUDGE: this double expansion is quite a monumental
318       ;; workaround: it comes about because of a fantastic interaction
319       ;; between the processing rules of CLHS 3.2.3.1 and the
320       ;; bizarreness of MAKE-METHOD-LAMBDA.
321       ;;
322       ;; MAKE-METHOD-LAMBDA can be called by the user, and if the
323       ;; lambda itself doesn't refer to outside bindings the return
324       ;; value must be compileable in the null lexical environment.
325       ;; However, the function must also refer somehow to the
326       ;; associated method object, so that it can call NO-NEXT-METHOD
327       ;; with the appropriate arguments if there is no next method --
328       ;; but when the function is generated, the method object doesn't
329       ;; exist yet.
330       ;;
331       ;; In order to resolve this issue, we insert a literal cons cell
332       ;; into the body of the method lambda, return the same cons cell
333       ;; as part of the second (initargs) return value of
334       ;; MAKE-METHOD-LAMBDA, and a method on INITIALIZE-INSTANCE fills
335       ;; in the cell when the method is created.  However, this
336       ;; strategy depends on having a fresh cons cell for every method
337       ;; lambda, which (without the workaround below) is skewered by
338       ;; the processing in CLHS 3.2.3.1, which permits implementations
339       ;; to macroexpand the bodies of EVAL-WHEN forms with both
340       ;; :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL only once.  The
341       ;; expansion below forces the double expansion in those cases,
342       ;; while expanding only once in the common case.
343       (eval-when (:load-toplevel)
344         (%defmethod-expander ,name ,qualifiers ,lambda-list ,body))
345       (eval-when (:execute)
346         (%defmethod-expander ,name ,qualifiers ,lambda-list ,body)))))
347
348 (defmacro %defmethod-expander
349     (name qualifiers lambda-list body &environment env)
350   (multiple-value-bind (proto-gf proto-method)
351       (prototypes-for-make-method-lambda name)
352     (expand-defmethod name proto-gf proto-method qualifiers
353                       lambda-list body env)))
354
355
356 (defun prototypes-for-make-method-lambda (name)
357   (if (not (eq **boot-state** 'complete))
358       (values nil nil)
359       (let ((gf? (and (fboundp name)
360                       (gdefinition name))))
361         (if (or (null gf?)
362                 (not (generic-function-p gf?)))
363             (values (class-prototype (find-class 'standard-generic-function))
364                     (class-prototype (find-class 'standard-method)))
365             (values gf?
366                     (class-prototype (or (generic-function-method-class gf?)
367                                          (find-class 'standard-method))))))))
368
369 ;;; Take a name which is either a generic function name or a list specifying
370 ;;; a SETF generic function (like: (SETF <generic-function-name>)). Return
371 ;;; the prototype instance of the method-class for that generic function.
372 ;;;
373 ;;; If there is no generic function by that name, this returns the
374 ;;; default value, the prototype instance of the class
375 ;;; STANDARD-METHOD. This default value is also returned if the spec
376 ;;; names an ordinary function or even a macro. In effect, this leaves
377 ;;; the signalling of the appropriate error until load time.
378 ;;;
379 ;;; Note: During bootstrapping, this function is allowed to return NIL.
380 (defun method-prototype-for-gf (name)
381   (let ((gf? (and (fboundp name)
382                   (gdefinition name))))
383     (cond ((neq **boot-state** 'complete) nil)
384           ((or (null gf?)
385                (not (generic-function-p gf?)))          ; Someone else MIGHT
386                                                         ; error at load time.
387            (class-prototype (find-class 'standard-method)))
388           (t
389             (class-prototype (or (generic-function-method-class gf?)
390                                  (find-class 'standard-method)))))))
391 \f
392 ;;; These are used to communicate the method name and lambda-list to
393 ;;; MAKE-METHOD-LAMBDA-INTERNAL.
394 (defvar *method-name* nil)
395 (defvar *method-lambda-list* nil)
396
397 (defun expand-defmethod (name
398                          proto-gf
399                          proto-method
400                          qualifiers
401                          lambda-list
402                          body
403                          env)
404   (multiple-value-bind (parameters unspecialized-lambda-list specializers)
405       (parse-specialized-lambda-list lambda-list)
406     (declare (ignore parameters))
407     (let ((method-lambda `(lambda ,unspecialized-lambda-list ,@body))
408           (*method-name* `(,name ,@qualifiers ,specializers))
409           (*method-lambda-list* lambda-list))
410       (multiple-value-bind (method-function-lambda initargs)
411           (make-method-lambda proto-gf proto-method method-lambda env)
412         (let ((initargs-form (make-method-initargs-form
413                               proto-gf proto-method method-function-lambda
414                               initargs env))
415               (specializers-form (make-method-specializers-form
416                                   proto-gf proto-method specializers env)))
417           `(progn
418              ;; Note: We could DECLAIM the ftype of the generic function
419              ;; here, since ANSI specifies that we create it if it does
420              ;; not exist. However, I chose not to, because I think it's
421              ;; more useful to support a style of programming where every
422              ;; generic function has an explicit DEFGENERIC and any typos
423              ;; in DEFMETHODs are warned about. Otherwise
424              ;;
425              ;;   (DEFGENERIC FOO-BAR-BLETCH (X))
426              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X HASH-TABLE)) ..)
427              ;;   (DEFMETHOD FOO-BRA-BLETCH ((X SIMPLE-VECTOR)) ..)
428              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X VECTOR)) ..)
429              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X ARRAY)) ..)
430              ;;   (DEFMETHOD FOO-BAR-BLETCH ((X LIST)) ..)
431              ;;
432              ;; compiles without raising an error and runs without
433              ;; raising an error (since SIMPLE-VECTOR cases fall through
434              ;; to VECTOR) but still doesn't do what was intended. I hate
435              ;; that kind of bug (code which silently gives the wrong
436              ;; answer), so we don't do a DECLAIM here. -- WHN 20000229
437              ,(make-defmethod-form name qualifiers specializers-form
438                                    unspecialized-lambda-list
439                                    (if proto-method
440                                        (class-name (class-of proto-method))
441                                        'standard-method)
442                                    initargs-form)))))))
443
444 (defun interned-symbol-p (x)
445   (and (symbolp x) (symbol-package x)))
446
447 (defun make-defmethod-form
448     (name qualifiers specializers unspecialized-lambda-list
449      method-class-name initargs-form)
450   (let (fn
451         fn-lambda)
452     (if (and (interned-symbol-p (fun-name-block-name name))
453              (every #'interned-symbol-p qualifiers)
454              (every (lambda (s)
455                       (if (consp s)
456                           (and (eq (car s) 'eql)
457                                (constantp (cadr s))
458                                (let ((sv (constant-form-value (cadr s))))
459                                  (or (interned-symbol-p sv)
460                                      (integerp sv)
461                                      (and (characterp sv)
462                                           (standard-char-p sv)))))
463                           (interned-symbol-p s)))
464                     specializers)
465              (consp initargs-form)
466              (eq (car initargs-form) 'list*)
467              (memq (cadr initargs-form) '(:function))
468              (consp (setq fn (caddr initargs-form)))
469              (eq (car fn) 'function)
470              (consp (setq fn-lambda (cadr fn)))
471              (eq (car fn-lambda) 'lambda)
472              (bug "Really got here"))
473         (let* ((specls (mapcar (lambda (specl)
474                                  (if (consp specl)
475                                      ;; CONSTANT-FORM-VALUE?  What I
476                                      ;; kind of want to know, though,
477                                      ;; is what happens if we don't do
478                                      ;; this for some slow-method
479                                      ;; function because of a hairy
480                                      ;; lexenv -- is the only bad
481                                      ;; effect that the method
482                                      ;; function ends up unnamed?  If
483                                      ;; so, couldn't we arrange to
484                                      ;; name it later?
485                                      `(,(car specl) ,(eval (cadr specl)))
486                                    specl))
487                                specializers))
488                (mname `(,(if (eq (cadr initargs-form) :function)
489                              'slow-method 'fast-method)
490                         ,name ,@qualifiers ,specls)))
491           `(progn
492              (defun ,mname ,(cadr fn-lambda)
493                ,@(cddr fn-lambda))
494              ,(make-defmethod-form-internal
495                name qualifiers `',specls
496                unspecialized-lambda-list method-class-name
497                `(list* ,(cadr initargs-form)
498                        #',mname
499                        ,@(cdddr initargs-form)))))
500         (make-defmethod-form-internal
501          name qualifiers
502          specializers
503          #+nil
504          `(list ,@(mapcar (lambda (specializer)
505                             (if (consp specializer)
506                                 ``(,',(car specializer)
507                                       ,,(cadr specializer))
508                                 `',specializer))
509                           specializers))
510          unspecialized-lambda-list
511          method-class-name
512          initargs-form))))
513
514 (defun make-defmethod-form-internal
515     (name qualifiers specializers-form unspecialized-lambda-list
516      method-class-name initargs-form)
517   `(load-defmethod
518     ',method-class-name
519     ',name
520     ',qualifiers
521     ,specializers-form
522     ',unspecialized-lambda-list
523     ,initargs-form
524     (sb-c:source-location)))
525
526 (defmacro make-method-function (method-lambda &environment env)
527   (multiple-value-bind (proto-gf proto-method)
528       (prototypes-for-make-method-lambda nil)
529     (multiple-value-bind (method-function-lambda initargs)
530         (make-method-lambda proto-gf proto-method method-lambda env)
531       (make-method-initargs-form proto-gf
532                                  proto-method
533                                  method-function-lambda
534                                  initargs
535                                  env))))
536
537 (defun real-make-method-initargs-form (proto-gf proto-method
538                                        method-lambda initargs env)
539   (declare (ignore proto-gf proto-method))
540   (unless (and (consp method-lambda)
541                (eq (car method-lambda) 'lambda))
542     (error "The METHOD-LAMBDA argument to MAKE-METHOD-FUNCTION, ~S, ~
543             is not a lambda form."
544            method-lambda))
545   (make-method-initargs-form-internal method-lambda initargs env))
546
547 (unless (fboundp 'make-method-initargs-form)
548   (setf (gdefinition 'make-method-initargs-form)
549         (symbol-function 'real-make-method-initargs-form)))
550
551 ;;; When bootstrapping PCL MAKE-METHOD-LAMBDA starts out as a regular
552 ;;; functions: REAL-MAKE-METHOD-LAMBDA set to the fdefinition of
553 ;;; MAKE-METHOD-LAMBDA. Once generic functions are born, the
554 ;;; REAL-MAKE-METHOD lambda is used as the body of the default method.
555 ;;; MAKE-METHOD-LAMBDA-INTERNAL is split out into a separate function
556 ;;; so that changing it in a live image is easy, and changes actually
557 ;;; take effect.
558 (defun real-make-method-lambda (proto-gf proto-method method-lambda env)
559   (make-method-lambda-internal proto-gf proto-method method-lambda env))
560
561 (unless (fboundp 'make-method-lambda)
562   (setf (gdefinition 'make-method-lambda)
563         (symbol-function 'real-make-method-lambda)))
564
565 (defun declared-specials (declarations)
566   (loop for (declare . specifiers) in declarations
567         append (loop for specifier in specifiers
568                      when (eq 'special (car specifier))
569                      append (cdr specifier))))
570
571 (defun make-method-lambda-internal (proto-gf proto-method method-lambda env)
572   (declare (ignore proto-gf proto-method))
573   (unless (and (consp method-lambda) (eq (car method-lambda) 'lambda))
574     (error "The METHOD-LAMBDA argument to MAKE-METHOD-LAMBDA, ~S, ~
575             is not a lambda form."
576            method-lambda))
577   (multiple-value-bind (real-body declarations documentation)
578       (parse-body (cddr method-lambda))
579     ;; We have the %METHOD-NAME declaration in the place where we expect it only
580     ;; if there is are no non-standard prior MAKE-METHOD-LAMBDA methods -- or
581     ;; unless they're fantastically unintrusive.
582     (let* ((method-name *method-name*)
583            (generic-function-name (when method-name (car method-name)))
584            (specialized-lambda-list (or *method-lambda-list*
585                                         (ecase (car method-lambda)
586                                           (lambda (second method-lambda))
587                                           (named-lambda (third method-lambda)))))
588            ;; the method-cell is a way of communicating what method a
589            ;; method-function implements, for the purpose of
590            ;; NO-NEXT-METHOD.  We need something that can be shared
591            ;; between function and initargs, but not something that
592            ;; will be coalesced as a constant (because we are naughty,
593            ;; oh yes) with the expansion of any other methods in the
594            ;; same file.  -- CSR, 2007-05-30
595            (method-cell (list (make-symbol "METHOD-CELL"))))
596       (multiple-value-bind (parameters lambda-list specializers)
597           (parse-specialized-lambda-list specialized-lambda-list)
598         (let* ((required-parameters
599                 (mapcar (lambda (r s) (declare (ignore s)) r)
600                         parameters
601                         specializers))
602                (slots (mapcar #'list required-parameters))
603                (class-declarations
604                 `(declare
605                   ;; These declarations seem to be used by PCL to pass
606                   ;; information to itself; when I tried to delete 'em
607                   ;; ca. 0.6.10 it didn't work. I'm not sure how
608                   ;; they work, but note the (VAR-DECLARATION '%CLASS ..)
609                   ;; expression in CAN-OPTIMIZE-ACCESS1. -- WHN 2000-12-30
610                   ,@(remove nil
611                             (mapcar (lambda (a s) (and (symbolp s)
612                                                        (neq s t)
613                                                        `(%class ,a ,s)))
614                                     parameters
615                                     specializers))
616                   ;; These TYPE declarations weren't in the original
617                   ;; PCL code, but the Python compiler likes them a
618                   ;; lot. (We're telling the compiler about our
619                   ;; knowledge of specialized argument types so that
620                   ;; it can avoid run-time type dispatch overhead,
621                   ;; which can be a huge win for Python.)
622                   ;;
623                   ;; KLUDGE: when I tried moving these to
624                   ;; ADD-METHOD-DECLARATIONS, things broke.  No idea
625                   ;; why.  -- CSR, 2004-06-16
626                   ,@(let ((specials (declared-specials declarations)))
627                       (mapcar (lambda (par spec)
628                                 (parameter-specializer-declaration-in-defmethod
629                                  par spec specials env))
630                               parameters
631                               specializers))))
632                (method-lambda
633                 ;; Remove the documentation string and insert the
634                 ;; appropriate class declarations. The documentation
635                 ;; string is removed to make it easy for us to insert
636                 ;; new declarations later, they will just go after the
637                 ;; CADR of the method lambda. The class declarations
638                 ;; are inserted to communicate the class of the method's
639                 ;; arguments to the code walk.
640                 `(lambda ,lambda-list
641                    ;; The default ignorability of method parameters
642                    ;; doesn't seem to be specified by ANSI. PCL had
643                    ;; them basically ignorable but was a little
644                    ;; inconsistent. E.g. even though the two
645                    ;; method definitions
646                    ;;   (DEFMETHOD FOO ((X T) (Y T)) "Z")
647                    ;;   (DEFMETHOD FOO ((X T) Y) "Z")
648                    ;; are otherwise equivalent, PCL treated Y as
649                    ;; ignorable in the first definition but not in the
650                    ;; second definition. We make all required
651                    ;; parameters ignorable as a way of systematizing
652                    ;; the old PCL behavior. -- WHN 2000-11-24
653                    (declare (ignorable ,@required-parameters))
654                    ,class-declarations
655                    ,@declarations
656                    (block ,(fun-name-block-name generic-function-name)
657                      ,@real-body)))
658                (constant-value-p (and (null (cdr real-body))
659                                       (constantp (car real-body))))
660                (constant-value (and constant-value-p
661                                     (constant-form-value (car real-body))))
662                (plist (and constant-value-p
663                            (or (typep constant-value
664                                       '(or number character))
665                                (and (symbolp constant-value)
666                                     (symbol-package constant-value)))
667                            (list :constant-value constant-value)))
668                (applyp (dolist (p lambda-list nil)
669                          (cond ((memq p '(&optional &rest &key))
670                                 (return t))
671                                ((eq p '&aux)
672                                 (return nil))))))
673           (multiple-value-bind
674                 (walked-lambda call-next-method-p closurep
675                                next-method-p-p setq-p
676                                parameters-setqd)
677               (walk-method-lambda method-lambda
678                                   required-parameters
679                                   env
680                                   slots)
681             (multiple-value-bind (walked-lambda-body
682                                   walked-declarations
683                                   walked-documentation)
684                 (parse-body (cddr walked-lambda))
685               (declare (ignore walked-documentation))
686               (when (some #'cdr slots)
687                 (let ((slot-name-lists (slot-name-lists-from-slots slots)))
688                   (setq plist
689                         `(,@(when slot-name-lists
690                                   `(:slot-name-lists ,slot-name-lists))
691                             ,@plist))
692                   (setq walked-lambda-body
693                         `((pv-binding (,required-parameters
694                                        ,slot-name-lists
695                                        (load-time-value
696                                         (intern-pv-table
697                                          :slot-name-lists ',slot-name-lists)))
698                             ,@walked-lambda-body)))))
699               (when (and (memq '&key lambda-list)
700                          (not (memq '&allow-other-keys lambda-list)))
701                 (let ((aux (memq '&aux lambda-list)))
702                   (setq lambda-list (nconc (ldiff lambda-list aux)
703                                            (list '&allow-other-keys)
704                                            aux))))
705               (values `(lambda (.method-args. .next-methods.)
706                          (simple-lexical-method-functions
707                              (,lambda-list .method-args. .next-methods.
708                                            :call-next-method-p
709                                            ,(when call-next-method-p t)
710                                            :next-method-p-p ,next-method-p-p
711                                            :setq-p ,setq-p
712                                            :parameters-setqd ,parameters-setqd
713                                            :method-cell ,method-cell
714                                            :closurep ,closurep
715                                            :applyp ,applyp)
716                            ,@walked-declarations
717                            (locally
718                                (declare (disable-package-locks
719                                          %parameter-binding-modified))
720                              (symbol-macrolet ((%parameter-binding-modified
721                                                 ',@parameters-setqd))
722                                (declare (enable-package-locks
723                                          %parameter-binding-modified))
724                                ,@walked-lambda-body))))
725                       `(,@(when call-next-method-p `(method-cell ,method-cell))
726                           ,@(when (member call-next-method-p '(:simple nil))
727                                   '(simple-next-method-call t))
728                           ,@(when plist `(plist ,plist))
729                           ,@(when documentation `(:documentation ,documentation)))))))))))
730
731 (defun real-make-method-specializers-form
732     (proto-gf proto-method specializer-names env)
733   (declare (ignore env proto-gf proto-method))
734   (flet ((parse (name)
735            (cond
736              ((and (eq **boot-state** 'complete)
737                    (specializerp name))
738               name)
739              ((symbolp name) `(find-class ',name))
740              ((consp name) (ecase (car name)
741                              ((eql) `(intern-eql-specializer ,(cadr name)))
742                              ((class-eq) `(class-eq-specializer (find-class ',(cadr name))))))
743              (t
744               ;; FIXME: Document CLASS-EQ specializers.
745               (error 'simple-reference-error
746                      :format-control
747                      "~@<~S is not a valid parameter specializer name.~@:>"
748                      :format-arguments (list name)
749                      :references (list '(:ansi-cl :macro defmethod)
750                                        '(:ansi-cl :glossary "parameter specializer name")))))))
751     `(list ,@(mapcar #'parse specializer-names))))
752
753 (unless (fboundp 'make-method-specializers-form)
754   (setf (gdefinition 'make-method-specializers-form)
755         (symbol-function 'real-make-method-specializers-form)))
756
757 (defun real-parse-specializer-using-class (generic-function specializer)
758   (let ((result (specializer-from-type specializer)))
759     (if (specializerp result)
760         result
761         (error "~@<~S cannot be parsed as a specializer for ~S.~@:>"
762                specializer generic-function))))
763
764 (unless (fboundp 'parse-specializer-using-class)
765   (setf (gdefinition 'parse-specializer-using-class)
766         (symbol-function 'real-parse-specializer-using-class)))
767
768 (defun real-unparse-specializer-using-class (generic-function specializer)
769   (if (specializerp specializer)
770       ;; FIXME: this HANDLER-CASE is a bit of a hammer to crack a nut:
771       ;; the idea is that we want to unparse permissively, so that the
772       ;; lazy (or rather the "portable") specializer extender (who
773       ;; does not define methods on these new SBCL-specific MOP
774       ;; functions) can still subclass specializer and define methods
775       ;; without everything going wrong.  Making it cleaner and
776       ;; clearer that that is what we are defending against would be
777       ;; nice.  -- CSR, 2007-06-01
778       (handler-case
779           (let ((type (specializer-type specializer)))
780             (if (and (consp type) (eq (car type) 'class))
781                 (let* ((class (cadr type))
782                        (class-name (class-name class)))
783                   (if (eq class (find-class class-name nil))
784                       class-name
785                       type))
786                 type))
787         (error () specializer))
788       (error "~@<~S is not a legal specializer for ~S.~@:>"
789              specializer generic-function)))
790
791 (unless (fboundp 'unparse-specializer-using-class)
792   (setf (gdefinition 'unparse-specializer-using-class)
793         (symbol-function 'real-unparse-specializer-using-class)))
794
795 ;;; a helper function for creating Python-friendly type declarations
796 ;;; in DEFMETHOD forms.
797 ;;;
798 ;;; We're too lazy to cons up a new environment for this, so we just pass in
799 ;;; the list of locally declared specials in addition to the old environment.
800 (defun parameter-specializer-declaration-in-defmethod
801     (parameter specializer specials env)
802   (cond ((and (consp specializer)
803               (eq (car specializer) 'eql))
804          ;; KLUDGE: ANSI, in its wisdom, says that
805          ;; EQL-SPECIALIZER-FORMs in EQL specializers are evaluated at
806          ;; DEFMETHOD expansion time. Thus, although one might think
807          ;; that in
808          ;;   (DEFMETHOD FOO ((X PACKAGE)
809          ;;                   (Y (EQL 12))
810          ;;      ..))
811          ;; the PACKAGE and (EQL 12) forms are both parallel type
812          ;; names, they're not, as is made clear when you do
813          ;;   (DEFMETHOD FOO ((X PACKAGE)
814          ;;                   (Y (EQL 'BAR)))
815          ;;     ..)
816          ;; where Y needs to be a symbol named "BAR", not some cons
817          ;; made by (CONS 'QUOTE 'BAR). I.e. when the
818          ;; EQL-SPECIALIZER-FORM is (EQL 'X), it requires an argument
819          ;; to be of type (EQL X). It'd be easy to transform one to
820          ;; the other, but it'd be somewhat messier to do so while
821          ;; ensuring that the EQL-SPECIALIZER-FORM is only EVAL'd
822          ;; once. (The new code wouldn't be messy, but it'd require a
823          ;; big transformation of the old code.) So instead we punt.
824          ;; -- WHN 20000610
825          '(ignorable))
826         ((member specializer
827                  ;; KLUDGE: For some low-level implementation
828                  ;; classes, perhaps because of some problems related
829                  ;; to the incomplete integration of PCL into SBCL's
830                  ;; type system, some specializer classes can't be
831                  ;; declared as argument types. E.g.
832                  ;;   (DEFMETHOD FOO ((X SLOT-OBJECT))
833                  ;;     (DECLARE (TYPE SLOT-OBJECT X))
834                  ;;     ..)
835                  ;; loses when
836                  ;;   (DEFSTRUCT BAR A B)
837                  ;;   (FOO (MAKE-BAR))
838                  ;; perhaps because of the way that STRUCTURE-OBJECT
839                  ;; inherits both from SLOT-OBJECT and from
840                  ;; SB-KERNEL:INSTANCE. In an effort to sweep such
841                  ;; problems under the rug, we exclude these problem
842                  ;; cases by blacklisting them here. -- WHN 2001-01-19
843                  (list 'slot-object #+nil (find-class 'slot-object)))
844          '(ignorable))
845         ((not (eq **boot-state** 'complete))
846          ;; KLUDGE: PCL, in its wisdom, sometimes calls methods with
847          ;; types which don't match their specializers. (Specifically,
848          ;; it calls ENSURE-CLASS-USING-CLASS (T NULL) with a non-NULL
849          ;; second argument.) Hopefully it only does this kind of
850          ;; weirdness when bootstrapping.. -- WHN 20000610
851          '(ignorable))
852         ((typep specializer 'eql-specializer)
853          `(type (eql ,(eql-specializer-object specializer)) ,parameter))
854         ((or (var-special-p parameter env) (member parameter specials))
855          ;; Don't declare types for special variables -- our rebinding magic
856          ;; for SETQ cases don't work right there as SET, (SETF SYMBOL-VALUE),
857          ;; etc. make things undecidable.
858          '(ignorable))
859         (t
860          ;; Otherwise, we can usually make Python very happy.
861          ;;
862          ;; KLUDGE: Since INFO doesn't work right for class objects here,
863          ;; and they are valid specializers, see if the specializer is
864          ;; a named class, and use the name in that case -- otherwise
865          ;; the class instance is ok, since info will just return NIL, NIL.
866          ;;
867          ;; We still need to deal with the class case too, but at
868          ;; least #.(find-class 'integer) and integer as equivalent
869          ;; specializers with this.
870          (let* ((specializer-nameoid
871                  (if (and (typep specializer 'class)
872                           (let ((name (class-name specializer)))
873                             (and name (symbolp name)
874                                  (eq specializer (find-class name nil)))))
875                      (class-name specializer)
876                      specializer))
877                 (kind (info :type :kind specializer-nameoid)))
878
879            (flet ((specializer-nameoid-class ()
880                     (typecase specializer-nameoid
881                       (symbol (find-class specializer-nameoid nil))
882                       (class specializer-nameoid)
883                       (class-eq-specializer
884                        (specializer-class specializer-nameoid))
885                       (t nil))))
886              (ecase kind
887                ((:primitive) `(type ,specializer-nameoid ,parameter))
888                ((:defined)
889                 (let ((class (specializer-nameoid-class)))
890                   ;; CLASS can be null here if the user has
891                   ;; erroneously tried to use a defined type as a
892                   ;; specializer; it can be a non-BUILT-IN-CLASS if
893                   ;; the user defines a type and calls (SETF
894                   ;; FIND-CLASS) in a consistent way.
895                  (when (and class (typep class 'built-in-class))
896                    `(type ,(class-name class) ,parameter))))
897               ((:instance nil)
898                (let ((class (specializer-nameoid-class)))
899                  (cond
900                    (class
901                     (if (typep class '(or built-in-class structure-class))
902                         `(type ,class ,parameter)
903                         ;; don't declare CLOS classes as parameters;
904                         ;; it's too expensive.
905                         '(ignorable)))
906                    (t
907                     ;; we can get here, and still not have a failure
908                     ;; case, by doing MOP programming like (PROGN
909                     ;; (ENSURE-CLASS 'FOO) (DEFMETHOD BAR ((X FOO))
910                     ;; ...)).  Best to let the user know we haven't
911                     ;; been able to extract enough information:
912                     (style-warn
913                      "~@<can't find type for specializer ~S in ~S.~@:>"
914                      specializer-nameoid
915                      'parameter-specializer-declaration-in-defmethod)
916                     '(ignorable)))))
917               ((:forthcoming-defclass-type)
918                '(ignorable))))))))
919
920 ;;; For passing a list (groveled by the walker) of the required
921 ;;; parameters whose bindings are modified in the method body to the
922 ;;; optimized-slot-value* macros.
923 (define-symbol-macro %parameter-binding-modified ())
924
925 (defmacro simple-lexical-method-functions ((lambda-list
926                                             method-args
927                                             next-methods
928                                             &rest lmf-options)
929                                            &body body)
930   `(progn
931      ,method-args ,next-methods
932      (bind-simple-lexical-method-functions (,method-args ,next-methods
933                                                          ,lmf-options)
934          (bind-args (,lambda-list ,method-args)
935            ,@body))))
936
937 (defmacro fast-lexical-method-functions ((lambda-list
938                                           next-method-call
939                                           args
940                                           rest-arg
941                                           &rest lmf-options)
942                                          &body body)
943   `(bind-fast-lexical-method-functions (,args ,rest-arg ,next-method-call ,lmf-options)
944      (bind-args (,(nthcdr (length args) lambda-list) ,rest-arg)
945        ,@body)))
946
947 (defmacro bind-simple-lexical-method-functions
948     ((method-args next-methods (&key call-next-method-p next-method-p-p setq-p
949                                      parameters-setqd closurep applyp method-cell))
950      &body body
951      &environment env)
952   (if (not (or call-next-method-p setq-p closurep next-method-p-p applyp))
953       `(locally
954            ,@body)
955       `(let ((.next-method. (car ,next-methods))
956              (,next-methods (cdr ,next-methods)))
957          (declare (ignorable .next-method. ,next-methods))
958          (flet (,@(and call-next-method-p
959                     `((call-next-method (&rest cnm-args)
960                        (declare (dynamic-extent cnm-args))
961                        ,@(if (safe-code-p env)
962                              `((%check-cnm-args cnm-args
963                                                 ,method-args
964                                                 ',method-cell))
965                              nil)
966                        (if .next-method.
967                            (funcall (if (std-instance-p .next-method.)
968                                         (method-function .next-method.)
969                                         .next-method.) ; for early methods
970                                     (or cnm-args ,method-args)
971                                     ,next-methods)
972                            (apply #'call-no-next-method
973                                   ',method-cell
974                                   (or cnm-args ,method-args))))))
975                 ,@(and next-method-p-p
976                     '((next-method-p ()
977                        (not (null .next-method.))))))
978            ,@body))))
979
980 (defun call-no-next-method (method-cell &rest args)
981   (let ((method (car method-cell)))
982     (aver method)
983     ;; Can't easily provide a RETRY restart here, as the return value here is
984     ;; for the method, not the generic function.
985     (apply #'no-next-method (method-generic-function method)
986            method args)))
987
988 (defun call-no-applicable-method (gf args)
989   (restart-case
990           (apply #'no-applicable-method gf args)
991     (retry ()
992       :report "Retry calling the generic function."
993       (apply gf args))))
994
995 (defun call-no-primary-method (gf args)
996   (restart-case
997       (apply #'no-primary-method gf args)
998     (retry ()
999       :report "Retry calling the generic function."
1000       (apply gf args))))
1001
1002 (defstruct (method-call (:copier nil))
1003   (function #'identity :type function)
1004   call-method-args)
1005 (defstruct (constant-method-call (:copier nil) (:include method-call))
1006   value)
1007
1008 #-sb-fluid (declaim (sb-ext:freeze-type method-call))
1009
1010 (defmacro invoke-method-call1 (function args cm-args)
1011   `(let ((.function. ,function)
1012          (.args. ,args)
1013          (.cm-args. ,cm-args))
1014      (if (and .cm-args. (null (cdr .cm-args.)))
1015          (funcall .function. .args. (car .cm-args.))
1016          (apply .function. .args. .cm-args.))))
1017
1018 (defmacro invoke-method-call (method-call restp &rest required-args+rest-arg)
1019   `(invoke-method-call1 (method-call-function ,method-call)
1020                         ,(if restp
1021                              `(list* ,@required-args+rest-arg)
1022                              `(list ,@required-args+rest-arg))
1023                         (method-call-call-method-args ,method-call)))
1024
1025 (defstruct (fast-method-call (:copier nil))
1026   (function #'identity :type function)
1027   pv
1028   next-method-call
1029   arg-info)
1030 (defstruct (constant-fast-method-call
1031              (:copier nil) (:include fast-method-call))
1032   value)
1033
1034 #-sb-fluid (declaim (sb-ext:freeze-type fast-method-call))
1035
1036 ;; The two variants of INVOKE-FAST-METHOD-CALL differ in how REST-ARGs
1037 ;; are handled. The first one will get REST-ARG as a single list (as
1038 ;; the last argument), and will thus need to use APPLY. The second one
1039 ;; will get them as a &MORE argument, so we can pass the arguments
1040 ;; directly with MULTIPLE-VALUE-CALL and %MORE-ARG-VALUES.
1041
1042 (defmacro invoke-fast-method-call (method-call restp &rest required-args+rest-arg)
1043   `(,(if restp 'apply 'funcall) (fast-method-call-function ,method-call)
1044                                 (fast-method-call-pv ,method-call)
1045                                 (fast-method-call-next-method-call ,method-call)
1046                                 ,@required-args+rest-arg))
1047
1048 (defmacro invoke-fast-method-call/more (method-call
1049                                         more-context
1050                                         more-count
1051                                         &rest required-args)
1052   (macrolet ((generate-call (n)
1053                ``(funcall (fast-method-call-function ,method-call)
1054                           (fast-method-call-pv ,method-call)
1055                           (fast-method-call-next-method-call ,method-call)
1056                           ,@required-args
1057                           ,@(loop for x below ,n
1058                                   collect `(sb-c::%more-arg ,more-context ,x)))))
1059     ;; The cases with only small amounts of required arguments passed
1060     ;; are probably very common, and special-casing speeds them up by
1061     ;; a factor of 2 with very little effect on the other
1062     ;; cases. Though it'd be nice to have the generic case be equally
1063     ;; fast.
1064     `(case ,more-count
1065        (0 ,(generate-call 0))
1066        (1 ,(generate-call 1))
1067        (t (multiple-value-call (fast-method-call-function ,method-call)
1068             (values (fast-method-call-pv ,method-call))
1069             (values (fast-method-call-next-method-call ,method-call))
1070             ,@required-args
1071             (sb-c::%more-arg-values ,more-context 0 ,more-count))))))
1072
1073 (defstruct (fast-instance-boundp (:copier nil))
1074   (index 0 :type fixnum))
1075
1076 #-sb-fluid (declaim (sb-ext:freeze-type fast-instance-boundp))
1077
1078 (eval-when (:compile-toplevel :load-toplevel :execute)
1079   (defvar *allow-emf-call-tracing-p* nil)
1080   (defvar *enable-emf-call-tracing-p* #-sb-show nil #+sb-show t))
1081 \f
1082 ;;;; effective method functions
1083
1084 (defvar *emf-call-trace-size* 200)
1085 (defvar *emf-call-trace* nil)
1086 (defvar *emf-call-trace-index* 0)
1087
1088 ;;; This function was in the CMU CL version of PCL (ca Debian 2.4.8)
1089 ;;; without explanation. It appears to be intended for debugging, so
1090 ;;; it might be useful someday, so I haven't deleted it.
1091 ;;; But it isn't documented and isn't used for anything now, so
1092 ;;; I've conditionalized it out of the base system. -- WHN 19991213
1093 #+sb-show
1094 (defun show-emf-call-trace ()
1095   (when *emf-call-trace*
1096     (let ((j *emf-call-trace-index*)
1097           (*enable-emf-call-tracing-p* nil))
1098       (format t "~&(The oldest entries are printed first)~%")
1099       (dotimes-fixnum (i *emf-call-trace-size*)
1100         (let ((ct (aref *emf-call-trace* j)))
1101           (when ct (print ct)))
1102         (incf j)
1103         (when (= j *emf-call-trace-size*)
1104           (setq j 0))))))
1105
1106 (defun trace-emf-call-internal (emf format args)
1107   (unless *emf-call-trace*
1108     (setq *emf-call-trace* (make-array *emf-call-trace-size*)))
1109   (setf (aref *emf-call-trace* *emf-call-trace-index*)
1110         (list* emf format args))
1111   (incf *emf-call-trace-index*)
1112   (when (= *emf-call-trace-index* *emf-call-trace-size*)
1113     (setq *emf-call-trace-index* 0)))
1114
1115 (defmacro trace-emf-call (emf format args)
1116   (when *allow-emf-call-tracing-p*
1117     `(when *enable-emf-call-tracing-p*
1118        (trace-emf-call-internal ,emf ,format ,args))))
1119
1120 (defmacro invoke-effective-method-function-fast
1121     (emf restp &key required-args rest-arg more-arg)
1122   `(progn
1123      (trace-emf-call ,emf ,restp (list ,@required-args rest-arg))
1124      ,(if more-arg
1125           `(invoke-fast-method-call/more ,emf
1126                                          ,@more-arg
1127                                          ,@required-args)
1128           `(invoke-fast-method-call ,emf
1129                                     ,restp
1130                                     ,@required-args
1131                                     ,@rest-arg))))
1132
1133 (defun effective-method-optimized-slot-access-clause
1134     (emf restp required-args)
1135   ;; "What," you may wonder, "do these next two clauses do?" In that
1136   ;; case, you are not a PCL implementor, for they considered this to
1137   ;; be self-documenting.:-| Or CSR, for that matter, since he can
1138   ;; also figure it out by looking at it without breaking stride. For
1139   ;; the rest of us, though: From what the code is doing with .SLOTS.
1140   ;; and whatnot, evidently it's implementing SLOT-VALUEish and
1141   ;; GET-SLOT-VALUEish things. Then we can reason backwards and
1142   ;; conclude that setting EMF to a FIXNUM is an optimized way to
1143   ;; represent these slot access operations.
1144   (when (not restp)
1145     (let ((length (length required-args)))
1146       (cond ((= 1 length)
1147              `((fixnum
1148                 (let* ((.slots. (get-slots-or-nil
1149                                  ,(car required-args)))
1150                        (value (when .slots. (clos-slots-ref .slots. ,emf))))
1151                   (if (eq value +slot-unbound+)
1152                       (slot-unbound-internal ,(car required-args)
1153                                              ,emf)
1154                       value)))))
1155             ((= 2 length)
1156              `((fixnum
1157                 (let ((.new-value. ,(car required-args))
1158                       (.slots. (get-slots-or-nil
1159                                 ,(cadr required-args))))
1160                   (when .slots.
1161                     (setf (clos-slots-ref .slots. ,emf) .new-value.)))))))
1162       ;; (In cmucl-2.4.8 there was a commented-out third ,@(WHEN
1163       ;; ...) clause here to handle SLOT-BOUNDish stuff. Since
1164       ;; there was no explanation and presumably the code is 10+
1165       ;; years stale, I simply deleted it. -- WHN)
1166       )))
1167
1168 ;;; Before SBCL 0.9.16.7 instead of
1169 ;;; INVOKE-NARROW-EFFECTIVE-METHOD-FUNCTION we passed a (THE (OR
1170 ;;; FUNCTION METHOD-CALL FAST-METHOD-CALL) EMF) form as the EMF. Now,
1171 ;;; to make less work for the compiler we take a path that doesn't
1172 ;;; involve the slot-accessor clause (where EMF is a FIXNUM) at all.
1173 (macrolet ((def (name &optional narrow)
1174              `(defmacro ,name (emf restp &key required-args rest-arg more-arg)
1175                 (unless (constantp restp)
1176                   (error "The RESTP argument is not constant."))
1177                 (setq restp (constant-form-value restp))
1178                 (with-unique-names (emf-n)
1179                   `(locally
1180                        (declare (optimize (sb-c:insert-step-conditions 0)))
1181                      (let ((,emf-n ,emf))
1182                        (trace-emf-call ,emf-n ,restp (list ,@required-args ,@rest-arg))
1183                        (etypecase ,emf-n
1184                          (fast-method-call
1185                           ,(if more-arg
1186                                `(invoke-fast-method-call/more ,emf-n
1187                                                               ,@more-arg
1188                                                               ,@required-args)
1189                                `(invoke-fast-method-call ,emf-n
1190                                                          ,restp
1191                                                          ,@required-args
1192                                                          ,@rest-arg)))
1193                          ,@,(unless narrow
1194                               `(effective-method-optimized-slot-access-clause
1195                                 emf-n restp required-args))
1196                          (method-call
1197                           (invoke-method-call ,emf-n ,restp ,@required-args
1198                                               ,@rest-arg))
1199                          (function
1200                           ,(if restp
1201                                `(apply ,emf-n ,@required-args ,@rest-arg)
1202                                `(funcall ,emf-n ,@required-args
1203                                          ,@rest-arg))))))))))
1204   (def invoke-effective-method-function nil)
1205   (def invoke-narrow-effective-method-function t))
1206
1207 (defun invoke-emf (emf args)
1208   (trace-emf-call emf t args)
1209   (etypecase emf
1210     (fast-method-call
1211      (let* ((arg-info (fast-method-call-arg-info emf))
1212             (restp (cdr arg-info))
1213             (nreq (car arg-info)))
1214        (if restp
1215            (apply (fast-method-call-function emf)
1216                   (fast-method-call-pv emf)
1217                   (fast-method-call-next-method-call emf)
1218                   args)
1219            (cond ((null args)
1220                   (if (eql nreq 0)
1221                       (invoke-fast-method-call emf nil)
1222                       (error 'simple-program-error
1223                              :format-control "invalid number of arguments: 0"
1224                              :format-arguments nil)))
1225                  ((null (cdr args))
1226                   (if (eql nreq 1)
1227                       (invoke-fast-method-call emf nil (car args))
1228                       (error 'simple-program-error
1229                              :format-control "invalid number of arguments: 1"
1230                              :format-arguments nil)))
1231                  ((null (cddr args))
1232                   (if (eql nreq 2)
1233                       (invoke-fast-method-call emf nil (car args) (cadr args))
1234                       (error 'simple-program-error
1235                              :format-control "invalid number of arguments: 2"
1236                              :format-arguments nil)))
1237                  (t
1238                   (apply (fast-method-call-function emf)
1239                          (fast-method-call-pv emf)
1240                          (fast-method-call-next-method-call emf)
1241                          args))))))
1242     (method-call
1243      (apply (method-call-function emf)
1244             args
1245             (method-call-call-method-args emf)))
1246     (fixnum
1247      (cond ((null args)
1248             (error 'simple-program-error
1249                    :format-control "invalid number of arguments: 0"
1250                    :format-arguments nil))
1251            ((null (cdr args))
1252             (let* ((slots (get-slots (car args)))
1253                    (value (clos-slots-ref slots emf)))
1254               (if (eq value +slot-unbound+)
1255                   (slot-unbound-internal (car args) emf)
1256                   value)))
1257            ((null (cddr args))
1258             (setf (clos-slots-ref (get-slots (cadr args)) emf)
1259                   (car args)))
1260            (t (error 'simple-program-error
1261                      :format-control "invalid number of arguments"
1262                      :format-arguments nil))))
1263     (fast-instance-boundp
1264      (if (or (null args) (cdr args))
1265          (error 'simple-program-error
1266                 :format-control "invalid number of arguments"
1267                 :format-arguments nil)
1268          (let ((slots (get-slots (car args))))
1269            (not (eq (clos-slots-ref slots (fast-instance-boundp-index emf))
1270                     +slot-unbound+)))))
1271     (function
1272      (apply emf args))))
1273 \f
1274
1275 (defmacro fast-call-next-method-body ((args next-method-call rest-arg)
1276                                       method-cell
1277                                       cnm-args)
1278   `(if ,next-method-call
1279        ,(let ((call `(invoke-narrow-effective-method-function
1280                       ,next-method-call
1281                       ,(not (null rest-arg))
1282                       :required-args ,args
1283                       :rest-arg ,(when rest-arg (list rest-arg)))))
1284              `(if ,cnm-args
1285                   (bind-args ((,@args
1286                                ,@(when rest-arg
1287                                        `(&rest ,rest-arg)))
1288                               ,cnm-args)
1289                     ,call)
1290                   ,call))
1291        (call-no-next-method ',method-cell
1292                             ,@args
1293                             ,@(when rest-arg
1294                                     `(,rest-arg)))))
1295
1296 (defmacro bind-fast-lexical-method-functions
1297     ((args rest-arg next-method-call (&key
1298                                       call-next-method-p
1299                                       setq-p
1300                                       parameters-setqd
1301                                       method-cell
1302                                       next-method-p-p
1303                                       closurep
1304                                       applyp))
1305      &body body
1306      &environment env)
1307   (let* ((all-params (append args (when rest-arg (list rest-arg))))
1308          (rebindings (when (or setq-p call-next-method-p)
1309                        (mapcar (lambda (x) (list x x)) all-params))))
1310     (if (not (or call-next-method-p setq-p closurep next-method-p-p applyp))
1311         `(locally
1312              ,@body)
1313         `(flet (,@(when call-next-method-p
1314                     `((call-next-method (&rest cnm-args)
1315                         (declare (dynamic-extent cnm-args)
1316                                  (muffle-conditions code-deletion-note)
1317                                  (optimize (sb-c:insert-step-conditions 0)))
1318                         ,@(if (safe-code-p env)
1319                               `((%check-cnm-args cnm-args (list ,@args)
1320                                                  ',method-cell))
1321                               nil)
1322                         (fast-call-next-method-body (,args
1323                                                      ,next-method-call
1324                                                      ,rest-arg)
1325                             ,method-cell
1326                             cnm-args))))
1327                   ,@(when next-method-p-p
1328                       `((next-method-p ()
1329                          (declare (optimize (sb-c:insert-step-conditions 0)))
1330                          (not (null ,next-method-call))))))
1331            (let ,rebindings
1332              ,@(when rebindings `((declare (ignorable ,@all-params))))
1333              ,@body)))))
1334
1335 ;;; CMUCL comment (Gerd Moellmann):
1336 ;;;
1337 ;;; The standard says it's an error if CALL-NEXT-METHOD is called with
1338 ;;; arguments, and the set of methods applicable to those arguments is
1339 ;;; different from the set of methods applicable to the original
1340 ;;; method arguments.  (According to Barry Margolin, this rule was
1341 ;;; probably added to ensure that before and around methods are always
1342 ;;; run before primary methods.)
1343 ;;;
1344 ;;; This could be optimized for the case that the generic function
1345 ;;; doesn't have hairy methods, does have standard method combination,
1346 ;;; is a standard generic function, there are no methods defined on it
1347 ;;; for COMPUTE-APPLICABLE-METHODS and probably a lot more of such
1348 ;;; preconditions.  That looks hairy and is probably not worth it,
1349 ;;; because this check will never be fast.
1350 (defun %check-cnm-args (cnm-args orig-args method-cell)
1351   ;; 1. Check for no arguments.
1352   (when cnm-args
1353     (let* ((gf (method-generic-function (car method-cell)))
1354            (nreq (generic-function-nreq gf)))
1355       (declare (fixnum nreq))
1356       ;; 2. Requirement arguments pairwise: if all are EQL, the applicable
1357       ;; methods must be the same. This takes care of the relatively common
1358       ;; case of twiddling with &KEY arguments without being horribly
1359       ;; expensive.
1360       (unless (do ((orig orig-args (cdr orig))
1361                    (args cnm-args (cdr args))
1362                    (n nreq (1- nreq)))
1363                   ((zerop n) t)
1364                 (unless (and orig args (eql (car orig) (car args)))
1365                   (return nil)))
1366         ;; 3. Only then do the full check.
1367         (let ((omethods (compute-applicable-methods gf orig-args))
1368               (nmethods (compute-applicable-methods gf cnm-args)))
1369           (unless (equal omethods nmethods)
1370             (error "~@<The set of methods ~S applicable to argument~P ~
1371                     ~{~S~^, ~} to call-next-method is different from ~
1372                     the set of methods ~S applicable to the original ~
1373                     method argument~P ~{~S~^, ~}.~@:>"
1374                    nmethods (length cnm-args) cnm-args omethods
1375                    (length orig-args) orig-args)))))))
1376
1377 (defmacro bind-args ((lambda-list args) &body body)
1378   (let ((args-tail '.args-tail.)
1379         (key '.key.)
1380         (state 'required))
1381     (flet ((process-var (var)
1382              (if (memq var lambda-list-keywords)
1383                  (progn
1384                    (case var
1385                      (&optional       (setq state 'optional))
1386                      (&key            (setq state 'key))
1387                      (&allow-other-keys)
1388                      (&rest           (setq state 'rest))
1389                      (&aux            (setq state 'aux))
1390                      (otherwise
1391                       (error
1392                        "encountered the non-standard lambda list keyword ~S"
1393                        var)))
1394                    nil)
1395                  (case state
1396                    (required `((,var (pop ,args-tail))))
1397                    (optional (cond ((not (consp var))
1398                                     `((,var (when ,args-tail
1399                                               (pop ,args-tail)))))
1400                                    ((null (cddr var))
1401                                     `((,(car var) (if ,args-tail
1402                                                       (pop ,args-tail)
1403                                                       ,(cadr var)))))
1404                                    (t
1405                                     `((,(caddr var) (not (null ,args-tail)))
1406                                       (,(car var) (if ,args-tail
1407                                                       (pop ,args-tail)
1408                                                       ,(cadr var)))))))
1409                    (rest `((,var ,args-tail)))
1410                    (key (cond ((not (consp var))
1411                                `((,var (car
1412                                         (get-key-arg-tail ,(keywordicate var)
1413                                                           ,args-tail)))))
1414                               ((null (cddr var))
1415                                (multiple-value-bind (keyword variable)
1416                                    (if (consp (car var))
1417                                        (values (caar var)
1418                                                (cadar var))
1419                                        (values (keywordicate (car var))
1420                                                (car var)))
1421                                  `((,key (get-key-arg-tail ',keyword
1422                                                            ,args-tail))
1423                                    (,variable (if ,key
1424                                                   (car ,key)
1425                                                   ,(cadr var))))))
1426                               (t
1427                                (multiple-value-bind (keyword variable)
1428                                    (if (consp (car var))
1429                                        (values (caar var)
1430                                                (cadar var))
1431                                        (values (keywordicate (car var))
1432                                                (car var)))
1433                                  `((,key (get-key-arg-tail ',keyword
1434                                                            ,args-tail))
1435                                    (,(caddr var) (not (null,key)))
1436                                    (,variable (if ,key
1437                                                   (car ,key)
1438                                                   ,(cadr var))))))))
1439                    (aux `(,var))))))
1440       (let ((bindings (mapcan #'process-var lambda-list)))
1441         `(let* ((,args-tail ,args)
1442                 ,@bindings
1443                 (.dummy0.
1444                  ,@(when (eq state 'optional)
1445                      `((unless (null ,args-tail)
1446                          (error 'simple-program-error
1447                                 :format-control "surplus arguments: ~S"
1448                                 :format-arguments (list ,args-tail)))))))
1449            (declare (ignorable ,args-tail .dummy0.))
1450            ,@body)))))
1451
1452 (defun get-key-arg-tail (keyword list)
1453   (loop for (key . tail) on list by #'cddr
1454         when (null tail) do
1455           ;; FIXME: Do we want to export this symbol? Or maybe use an
1456           ;; (ERROR 'SIMPLE-PROGRAM-ERROR) form?
1457           (sb-c::%odd-key-args-error)
1458         when (eq key keyword)
1459           return tail))
1460
1461 (defun walk-method-lambda (method-lambda required-parameters env slots)
1462   (let (;; flag indicating that CALL-NEXT-METHOD should be in the
1463         ;; method definition
1464         (call-next-method-p nil)
1465         ;; flag indicating that #'CALL-NEXT-METHOD was seen in the
1466         ;; body of a method
1467         (closurep nil)
1468         ;; flag indicating that NEXT-METHOD-P should be in the method
1469         ;; definition
1470         (next-method-p-p nil)
1471         ;; a list of all required parameters whose bindings might be
1472         ;; modified in the method body.
1473         (parameters-setqd nil))
1474     (flet ((walk-function (form context env)
1475              (cond ((not (eq context :eval)) form)
1476                    ;; FIXME: Jumping to a conclusion from the way it's used
1477                    ;; above, perhaps CONTEXT should be called SITUATION
1478                    ;; (after the term used in the ANSI specification of
1479                    ;; EVAL-WHEN) and given modern ANSI keyword values
1480                    ;; like :LOAD-TOPLEVEL.
1481                    ((not (listp form)) form)
1482                    ((eq (car form) 'call-next-method)
1483                     (setq call-next-method-p (if (cdr form)
1484                                                  t
1485                                                  :simple))
1486                     form)
1487                    ((eq (car form) 'next-method-p)
1488                     (setq next-method-p-p t)
1489                     form)
1490                    ((memq (car form) '(setq multiple-value-setq))
1491                     ;; The walker will split (SETQ A 1 B 2) to
1492                     ;; separate (SETQ A 1) and (SETQ B 2) forms, so we
1493                     ;; only need to handle the simple case of SETQ
1494                     ;; here.
1495                     (let ((vars (if (eq (car form) 'setq)
1496                                     (list (second form))
1497                                     (second form))))
1498                       (dolist (var vars)
1499                         ;; Note that we don't need to check for
1500                         ;; %VARIABLE-REBINDING declarations like is
1501                         ;; done in CAN-OPTIMIZE-ACCESS1, since the
1502                         ;; bindings that will have that declation will
1503                         ;; never be SETQd.
1504                         (when (var-declaration '%class var env)
1505                           ;; If a parameter binding is shadowed by
1506                           ;; another binding it won't have a %CLASS
1507                           ;; declaration anymore, and this won't get
1508                           ;; executed.
1509                           (pushnew var parameters-setqd :test #'eq))))
1510                     form)
1511                    ((and (eq (car form) 'function)
1512                          (cond ((eq (cadr form) 'call-next-method)
1513                                 (setq call-next-method-p t)
1514                                 (setq closurep t)
1515                                 form)
1516                                ((eq (cadr form) 'next-method-p)
1517                                 (setq next-method-p-p t)
1518                                 (setq closurep t)
1519                                 form)
1520                                (t nil))))
1521                    ((and (memq (car form)
1522                                '(slot-value set-slot-value slot-boundp))
1523                          (constantp (caddr form) env))
1524                     (let ((fun (ecase (car form)
1525                                  (slot-value #'optimize-slot-value)
1526                                  (set-slot-value #'optimize-set-slot-value)
1527                                  (slot-boundp #'optimize-slot-boundp))))
1528                         (funcall fun form slots required-parameters env)))
1529                    (t form))))
1530
1531       (let ((walked-lambda (walk-form method-lambda env #'walk-function)))
1532         ;;; FIXME: the walker's rewriting of the source code causes
1533         ;;; trouble when doing code coverage. The rewrites should be
1534         ;;; removed, and the same operations done using
1535         ;;; compiler-macros or tranforms.
1536         (values (if (sb-c:policy env (= sb-c:store-coverage-data 0))
1537                     walked-lambda
1538                     method-lambda)
1539                 call-next-method-p
1540                 closurep
1541                 next-method-p-p
1542                 (not (null parameters-setqd))
1543                 parameters-setqd)))))
1544
1545 (defun generic-function-name-p (name)
1546   (and (legal-fun-name-p name)
1547        (fboundp name)
1548        (if (eq **boot-state** 'complete)
1549            (standard-generic-function-p (gdefinition name))
1550            (funcallable-instance-p (gdefinition name)))))
1551 \f
1552 (defun method-plist-value (method key &optional default)
1553   (let ((plist (if (consp method)
1554                    (getf (early-method-initargs method) 'plist)
1555                    (object-plist method))))
1556     (getf plist key default)))
1557
1558 (defun (setf method-plist-value) (new-value method key &optional default)
1559   (if (consp method)
1560       (setf (getf (getf (early-method-initargs method) 'plist) key default)
1561             new-value)
1562       (setf (getf (object-plist method) key default) new-value)))
1563 \f
1564 (defun load-defmethod (class name quals specls ll initargs source-location)
1565   (let ((method-cell (getf initargs 'method-cell)))
1566     (setq initargs (copy-tree initargs))
1567     (when method-cell
1568       (setf (getf initargs 'method-cell) method-cell))
1569     #+nil
1570     (setf (getf (getf initargs 'plist) :name)
1571           (make-method-spec name quals specls))
1572     (load-defmethod-internal class name quals specls
1573                              ll initargs source-location)))
1574
1575 (defun load-defmethod-internal
1576     (method-class gf-spec qualifiers specializers lambda-list
1577                   initargs source-location)
1578   (when (and (eq **boot-state** 'complete)
1579              (fboundp gf-spec))
1580     (let* ((gf (fdefinition gf-spec))
1581            (method (and (generic-function-p gf)
1582                         (generic-function-methods gf)
1583                         (find-method gf qualifiers specializers nil))))
1584       (when method
1585         (warn 'sb-kernel:redefinition-with-defmethod
1586               :name gf-spec
1587               :new-location source-location
1588               :old-method method
1589               :qualifiers qualifiers :specializers specializers))))
1590   (let ((method (apply #'add-named-method
1591                        gf-spec qualifiers specializers lambda-list
1592                        :definition-source source-location
1593                        initargs)))
1594     (unless (or (eq method-class 'standard-method)
1595                 (eq (find-class method-class nil) (class-of method)))
1596       ;; FIXME: should be STYLE-WARNING?
1597       (format *error-output*
1598               "~&At the time the method with qualifiers ~:S and~%~
1599                specializers ~:S on the generic function ~S~%~
1600                was compiled, the method-class for that generic function was~%~
1601                ~S. But, the method class is now ~S, this~%~
1602                may mean that this method was compiled improperly.~%"
1603               qualifiers specializers gf-spec
1604               method-class (class-name (class-of method))))
1605     method))
1606
1607 (defun make-method-spec (gf qualifiers specializers)
1608   (let ((name (generic-function-name gf))
1609         (unparsed-specializers (unparse-specializers gf specializers)))
1610     `(slow-method ,name ,@qualifiers ,unparsed-specializers)))
1611
1612 (defun initialize-method-function (initargs method)
1613   (let* ((mf (getf initargs :function))
1614          (mff (and (typep mf '%method-function)
1615                    (%method-function-fast-function mf)))
1616          (plist (getf initargs 'plist))
1617          (name (getf plist :name))
1618          (method-cell (getf initargs 'method-cell)))
1619     (when method-cell
1620       (setf (car method-cell) method))
1621     (when name
1622       (when mf
1623         (setq mf (set-fun-name mf name)))
1624       (when (and mff (consp name) (eq (car name) 'slow-method))
1625         (let ((fast-name `(fast-method ,@(cdr name))))
1626           (set-fun-name mff fast-name))))
1627     (when plist
1628       (let ((plist plist))
1629         (let ((snl (getf plist :slot-name-lists)))
1630           (when snl
1631             (setf (method-plist-value method :pv-table)
1632                   (intern-pv-table :slot-name-lists snl))))))))
1633 \f
1634 (defun analyze-lambda-list (lambda-list)
1635   (flet (;; FIXME: Is this redundant with SB-C::MAKE-KEYWORD-FOR-ARG?
1636          (parse-key-arg (arg)
1637            (if (listp arg)
1638                (if (listp (car arg))
1639                    (caar arg)
1640                    (keywordicate (car arg)))
1641                (keywordicate arg))))
1642     (let ((nrequired 0)
1643           (noptional 0)
1644           (keysp nil)
1645           (restp nil)
1646           (nrest 0)
1647           (allow-other-keys-p nil)
1648           (keywords ())
1649           (keyword-parameters ())
1650           (state 'required))
1651       (dolist (x lambda-list)
1652         (if (memq x lambda-list-keywords)
1653             (case x
1654               (&optional         (setq state 'optional))
1655               (&key              (setq keysp t
1656                                        state 'key))
1657               (&allow-other-keys (setq allow-other-keys-p t))
1658               (&rest             (setq restp t
1659                                        state 'rest))
1660               (&aux           (return t))
1661               (otherwise
1662                 (error "encountered the non-standard lambda list keyword ~S"
1663                        x)))
1664             (ecase state
1665               (required  (incf nrequired))
1666               (optional  (incf noptional))
1667               (key       (push (parse-key-arg x) keywords)
1668                          (push x keyword-parameters))
1669               (rest      (incf nrest)))))
1670       (when (and restp (zerop nrest))
1671         (error "Error in lambda-list:~%~
1672                 After &REST, a DEFGENERIC lambda-list ~
1673                 must be followed by at least one variable."))
1674       (values nrequired noptional keysp restp allow-other-keys-p
1675               (reverse keywords)
1676               (reverse keyword-parameters)))))
1677
1678 (defun keyword-spec-name (x)
1679   (let ((key (if (atom x) x (car x))))
1680     (if (atom key)
1681         (keywordicate key)
1682         (car key))))
1683
1684 (defun ftype-declaration-from-lambda-list (lambda-list name)
1685   (multiple-value-bind (nrequired noptional keysp restp allow-other-keys-p
1686                                   keywords keyword-parameters)
1687       (analyze-lambda-list lambda-list)
1688     (declare (ignore keyword-parameters))
1689     (let* ((old (info :function :type name)) ;FIXME:FDOCUMENTATION instead?
1690            (old-ftype (if (fun-type-p old) old nil))
1691            (old-restp (and old-ftype (fun-type-rest old-ftype)))
1692            (old-keys (and old-ftype
1693                           (mapcar #'key-info-name
1694                                   (fun-type-keywords
1695                                    old-ftype))))
1696            (old-keysp (and old-ftype (fun-type-keyp old-ftype)))
1697            (old-allowp (and old-ftype
1698                             (fun-type-allowp old-ftype)))
1699            (keywords (union old-keys (mapcar #'keyword-spec-name keywords))))
1700       `(function ,(append (make-list nrequired :initial-element t)
1701                           (when (plusp noptional)
1702                             (append '(&optional)
1703                                     (make-list noptional :initial-element t)))
1704                           (when (or restp old-restp)
1705                             '(&rest t))
1706                           (when (or keysp old-keysp)
1707                             (append '(&key)
1708                                     (mapcar (lambda (key)
1709                                               `(,key t))
1710                                             keywords)
1711                                     (when (or allow-other-keys-p old-allowp)
1712                                       '(&allow-other-keys)))))
1713                  *))))
1714 \f
1715 ;;;; early generic function support
1716
1717 (defvar *!early-generic-functions* ())
1718
1719 (defun ensure-generic-function (fun-name
1720                                 &rest all-keys
1721                                 &key environment definition-source
1722                                 &allow-other-keys)
1723   (declare (ignore environment))
1724   (let ((existing (and (fboundp fun-name)
1725                        (gdefinition fun-name))))
1726     (cond ((and existing
1727                 (eq **boot-state** 'complete)
1728                 (null (generic-function-p existing)))
1729            (generic-clobbers-function fun-name)
1730            (fmakunbound fun-name)
1731            (apply #'ensure-generic-function fun-name all-keys))
1732           (t
1733            (apply #'ensure-generic-function-using-class
1734                   existing fun-name all-keys)))))
1735
1736 (defun generic-clobbers-function (fun-name)
1737   (cerror "Replace the function binding"
1738           'simple-program-error
1739           :format-control "~S already names an ordinary function or a macro."
1740           :format-arguments (list fun-name)))
1741
1742 (defvar *sgf-wrapper*
1743   (boot-make-wrapper (early-class-size 'standard-generic-function)
1744                      'standard-generic-function))
1745
1746 (defvar *sgf-slots-init*
1747   (mapcar (lambda (canonical-slot)
1748             (if (memq (getf canonical-slot :name) '(arg-info source))
1749                 +slot-unbound+
1750                 (let ((initfunction (getf canonical-slot :initfunction)))
1751                   (if initfunction
1752                       (funcall initfunction)
1753                       +slot-unbound+))))
1754           (early-collect-inheritance 'standard-generic-function)))
1755
1756 (defconstant +sgf-method-class-index+
1757   (!bootstrap-slot-index 'standard-generic-function 'method-class))
1758
1759 (defun early-gf-p (x)
1760   (and (fsc-instance-p x)
1761        (eq (clos-slots-ref (get-slots x) +sgf-method-class-index+)
1762            +slot-unbound+)))
1763
1764 (defconstant +sgf-methods-index+
1765   (!bootstrap-slot-index 'standard-generic-function 'methods))
1766
1767 (defmacro early-gf-methods (gf)
1768   `(clos-slots-ref (get-slots ,gf) +sgf-methods-index+))
1769
1770 (defun safe-generic-function-methods (generic-function)
1771   (if (eq (class-of generic-function) *the-class-standard-generic-function*)
1772       (clos-slots-ref (get-slots generic-function) +sgf-methods-index+)
1773       (generic-function-methods generic-function)))
1774
1775 (defconstant +sgf-arg-info-index+
1776   (!bootstrap-slot-index 'standard-generic-function 'arg-info))
1777
1778 (defmacro early-gf-arg-info (gf)
1779   `(clos-slots-ref (get-slots ,gf) +sgf-arg-info-index+))
1780
1781 (defconstant +sgf-dfun-state-index+
1782   (!bootstrap-slot-index 'standard-generic-function 'dfun-state))
1783
1784 (defstruct (arg-info
1785             (:conc-name nil)
1786             (:constructor make-arg-info ())
1787             (:copier nil))
1788   (arg-info-lambda-list :no-lambda-list)
1789   arg-info-precedence
1790   arg-info-metatypes
1791   arg-info-number-optional
1792   arg-info-key/rest-p
1793   arg-info-keys   ;nil        no &KEY or &REST allowed
1794                   ;(k1 k2 ..) Each method must accept these &KEY arguments.
1795                   ;T          must have &KEY or &REST
1796
1797   gf-info-simple-accessor-type ; nil, reader, writer, boundp
1798   (gf-precompute-dfun-and-emf-p nil) ; set by set-arg-info
1799
1800   gf-info-static-c-a-m-emf
1801   (gf-info-c-a-m-emf-std-p t)
1802   gf-info-fast-mf-p)
1803
1804 #-sb-fluid (declaim (sb-ext:freeze-type arg-info))
1805
1806 (defun arg-info-valid-p (arg-info)
1807   (not (null (arg-info-number-optional arg-info))))
1808
1809 (defun arg-info-applyp (arg-info)
1810   (or (plusp (arg-info-number-optional arg-info))
1811       (arg-info-key/rest-p arg-info)))
1812
1813 (defun arg-info-number-required (arg-info)
1814   (length (arg-info-metatypes arg-info)))
1815
1816 (defun arg-info-nkeys (arg-info)
1817   (count-if (lambda (x) (neq x t)) (arg-info-metatypes arg-info)))
1818
1819 (defun create-gf-lambda-list (lambda-list)
1820   ;;; Create a gf lambda list from a method lambda list
1821   (loop for x in lambda-list
1822         collect (if (consp x) (list (car x)) x)
1823         if (eq x '&key) do (loop-finish)))
1824
1825 (defun set-arg-info (gf &key new-method (lambda-list nil lambda-list-p)
1826                         argument-precedence-order)
1827   (let* ((arg-info (if (eq **boot-state** 'complete)
1828                        (gf-arg-info gf)
1829                        (early-gf-arg-info gf)))
1830          (methods (if (eq **boot-state** 'complete)
1831                       (generic-function-methods gf)
1832                       (early-gf-methods gf)))
1833          (was-valid-p (integerp (arg-info-number-optional arg-info)))
1834          (first-p (and new-method (null (cdr methods)))))
1835     (when (and (not lambda-list-p) methods)
1836       (setq lambda-list (gf-lambda-list gf)))
1837     (when (or lambda-list-p
1838               (and first-p
1839                    (eq (arg-info-lambda-list arg-info) :no-lambda-list)))
1840       (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1841           (analyze-lambda-list lambda-list)
1842         (when (and methods (not first-p))
1843           (let ((gf-nreq (arg-info-number-required arg-info))
1844                 (gf-nopt (arg-info-number-optional arg-info))
1845                 (gf-key/rest-p (arg-info-key/rest-p arg-info)))
1846             (unless (and (= nreq gf-nreq)
1847                          (= nopt gf-nopt)
1848                          (eq (or keysp restp) gf-key/rest-p))
1849               (error "The lambda-list ~S is incompatible with ~
1850                      existing methods of ~S."
1851                      lambda-list gf))))
1852         (setf (arg-info-lambda-list arg-info)
1853               (if lambda-list-p
1854                   lambda-list
1855                    (create-gf-lambda-list lambda-list)))
1856         (when (or lambda-list-p argument-precedence-order
1857                   (null (arg-info-precedence arg-info)))
1858           (setf (arg-info-precedence arg-info)
1859                 (compute-precedence lambda-list nreq argument-precedence-order)))
1860         (setf (arg-info-metatypes arg-info) (make-list nreq))
1861         (setf (arg-info-number-optional arg-info) nopt)
1862         (setf (arg-info-key/rest-p arg-info) (not (null (or keysp restp))))
1863         (setf (arg-info-keys arg-info)
1864               (if lambda-list-p
1865                   (if allow-other-keys-p t keywords)
1866                   (arg-info-key/rest-p arg-info)))))
1867     (when new-method
1868       (check-method-arg-info gf arg-info new-method))
1869     (set-arg-info1 gf arg-info new-method methods was-valid-p first-p)
1870     arg-info))
1871
1872 (defun check-method-arg-info (gf arg-info method)
1873   (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1874       (analyze-lambda-list (if (consp method)
1875                                (early-method-lambda-list method)
1876                                (method-lambda-list method)))
1877     (flet ((lose (string &rest args)
1878              (error 'simple-program-error
1879                     :format-control "~@<attempt to add the method~2I~_~S~I~_~
1880                                      to the generic function~2I~_~S;~I~_~
1881                                      but ~?~:>"
1882                     :format-arguments (list method gf string args)))
1883            (comparison-description (x y)
1884              (if (> x y) "more" "fewer")))
1885       (let ((gf-nreq (arg-info-number-required arg-info))
1886             (gf-nopt (arg-info-number-optional arg-info))
1887             (gf-key/rest-p (arg-info-key/rest-p arg-info))
1888             (gf-keywords (arg-info-keys arg-info)))
1889         (unless (= nreq gf-nreq)
1890           (lose
1891            "the method has ~A required arguments than the generic function."
1892            (comparison-description nreq gf-nreq)))
1893         (unless (= nopt gf-nopt)
1894           (lose
1895            "the method has ~A optional arguments than the generic function."
1896            (comparison-description nopt gf-nopt)))
1897         (unless (eq (or keysp restp) gf-key/rest-p)
1898           (lose
1899            "the method and generic function differ in whether they accept~_~
1900             &REST or &KEY arguments."))
1901         (when (consp gf-keywords)
1902           (unless (or (and restp (not keysp))
1903                       allow-other-keys-p
1904                       (every (lambda (k) (memq k keywords)) gf-keywords))
1905             (lose "the method does not accept each of the &KEY arguments~2I~_~
1906                    ~S."
1907                   gf-keywords)))))))
1908
1909 (defconstant +sm-specializers-index+
1910   (!bootstrap-slot-index 'standard-method 'specializers))
1911 (defconstant +sm-%function-index+
1912   (!bootstrap-slot-index 'standard-method '%function))
1913 (defconstant +sm-qualifiers-index+
1914   (!bootstrap-slot-index 'standard-method 'qualifiers))
1915
1916 ;;; FIXME: we don't actually need this; we could test for the exact
1917 ;;; class and deal with it as appropriate.  In fact we probably don't
1918 ;;; need it anyway because we only use this for METHOD-SPECIALIZERS on
1919 ;;; the standard reader method for METHOD-SPECIALIZERS.  Probably.
1920 (dolist (s '(specializers %function))
1921   (aver (= (symbol-value (intern (format nil "+SM-~A-INDEX+" s)))
1922            (!bootstrap-slot-index 'standard-reader-method s)
1923            (!bootstrap-slot-index 'standard-writer-method s)
1924            (!bootstrap-slot-index 'standard-boundp-method s)
1925            (!bootstrap-slot-index 'global-reader-method s)
1926            (!bootstrap-slot-index 'global-writer-method s)
1927            (!bootstrap-slot-index 'global-boundp-method s))))
1928
1929 (defvar *standard-method-class-names*
1930   '(standard-method standard-reader-method
1931     standard-writer-method standard-boundp-method
1932     global-reader-method global-writer-method
1933     global-boundp-method))
1934
1935 (declaim (list **standard-method-classes**))
1936 (defglobal **standard-method-classes** nil)
1937
1938 (defun safe-method-specializers (method)
1939   (if (member (class-of method) **standard-method-classes** :test #'eq)
1940       (clos-slots-ref (std-instance-slots method) +sm-specializers-index+)
1941       (method-specializers method)))
1942 (defun safe-method-fast-function (method)
1943   (let ((mf (safe-method-function method)))
1944     (and (typep mf '%method-function)
1945          (%method-function-fast-function mf))))
1946 (defun safe-method-function (method)
1947   (if (member (class-of method) **standard-method-classes** :test #'eq)
1948       (clos-slots-ref (std-instance-slots method) +sm-%function-index+)
1949       (method-function method)))
1950 (defun safe-method-qualifiers (method)
1951   (if (member (class-of method) **standard-method-classes** :test #'eq)
1952       (clos-slots-ref (std-instance-slots method) +sm-qualifiers-index+)
1953       (method-qualifiers method)))
1954
1955 (defun set-arg-info1 (gf arg-info new-method methods was-valid-p first-p)
1956   (let* ((existing-p (and methods (cdr methods) new-method))
1957          (nreq (length (arg-info-metatypes arg-info)))
1958          (metatypes (if existing-p
1959                         (arg-info-metatypes arg-info)
1960                         (make-list nreq)))
1961          (type (if existing-p
1962                    (gf-info-simple-accessor-type arg-info)
1963                    nil)))
1964     (when (arg-info-valid-p arg-info)
1965       (dolist (method (if new-method (list new-method) methods))
1966         (let* ((specializers (if (or (eq **boot-state** 'complete)
1967                                      (not (consp method)))
1968                                  (safe-method-specializers method)
1969                                  (early-method-specializers method t)))
1970                (class (if (or (eq **boot-state** 'complete) (not (consp method)))
1971                           (class-of method)
1972                           (early-method-class method)))
1973                (new-type
1974                 (when (and class
1975                            (or (not (eq **boot-state** 'complete))
1976                                (eq (generic-function-method-combination gf)
1977                                    *standard-method-combination*)))
1978                   (cond ((or (eq class *the-class-standard-reader-method*)
1979                              (eq class *the-class-global-reader-method*))
1980                          'reader)
1981                         ((or (eq class *the-class-standard-writer-method*)
1982                              (eq class *the-class-global-writer-method*))
1983                          'writer)
1984                         ((or (eq class *the-class-standard-boundp-method*)
1985                              (eq class *the-class-global-boundp-method*))
1986                          'boundp)))))
1987           (setq metatypes (mapcar #'raise-metatype metatypes specializers))
1988           (setq type (cond ((null type) new-type)
1989                            ((eq type new-type) type)
1990                            (t nil)))))
1991       (setf (arg-info-metatypes arg-info) metatypes)
1992       (setf (gf-info-simple-accessor-type arg-info) type)))
1993   (when (or (not was-valid-p) first-p)
1994     (multiple-value-bind (c-a-m-emf std-p)
1995         (if (early-gf-p gf)
1996             (values t t)
1997             (compute-applicable-methods-emf gf))
1998       (setf (gf-info-static-c-a-m-emf arg-info) c-a-m-emf)
1999       (setf (gf-info-c-a-m-emf-std-p arg-info) std-p)
2000       (unless (gf-info-c-a-m-emf-std-p arg-info)
2001         (setf (gf-info-simple-accessor-type arg-info) t))))
2002   (unless was-valid-p
2003     (let ((name (if (eq **boot-state** 'complete)
2004                     (generic-function-name gf)
2005                     (!early-gf-name gf))))
2006       (setf (gf-precompute-dfun-and-emf-p arg-info)
2007             (cond
2008               ((and (consp name)
2009                     (member (car name)
2010                             *internal-pcl-generalized-fun-name-symbols*))
2011                 nil)
2012               (t (let* ((symbol (fun-name-block-name name))
2013                         (package (symbol-package symbol)))
2014                    (and (or (eq package *pcl-package*)
2015                             (memq package (package-use-list *pcl-package*)))
2016                         (not (eq package #.(find-package "CL")))
2017                         ;; FIXME: this test will eventually be
2018                         ;; superseded by the *internal-pcl...* test,
2019                         ;; above.  While we are in a process of
2020                         ;; transition, however, it should probably
2021                         ;; remain.
2022                         (not (find #\Space (symbol-name symbol))))))))))
2023   (setf (gf-info-fast-mf-p arg-info)
2024         (or (not (eq **boot-state** 'complete))
2025             (let* ((method-class (generic-function-method-class gf))
2026                    (methods (compute-applicable-methods
2027                              #'make-method-lambda
2028                              (list gf (class-prototype method-class)
2029                                    '(lambda) nil))))
2030               (and methods (null (cdr methods))
2031                    (let ((specls (method-specializers (car methods))))
2032                      (and (classp (car specls))
2033                           (eq 'standard-generic-function
2034                               (class-name (car specls)))
2035                           (classp (cadr specls))
2036                           (eq 'standard-method
2037                               (class-name (cadr specls)))))))))
2038   arg-info)
2039
2040 ;;; This is the early definition of ENSURE-GENERIC-FUNCTION-USING-CLASS.
2041 ;;;
2042 ;;; The STATIC-SLOTS field of the funcallable instances used as early
2043 ;;; generic functions is used to store the early methods and early
2044 ;;; discriminator code for the early generic function. The static
2045 ;;; slots field of the fins contains a list whose:
2046 ;;;    CAR    -   a list of the early methods on this early gf
2047 ;;;    CADR   -   the early discriminator code for this method
2048 (defun ensure-generic-function-using-class (existing spec &rest keys
2049                                             &key (lambda-list nil
2050                                                               lambda-list-p)
2051                                             argument-precedence-order
2052                                             definition-source
2053                                             documentation
2054                                             &allow-other-keys)
2055   (declare (ignore keys))
2056   (cond ((and existing (early-gf-p existing))
2057          (when lambda-list-p
2058            (set-arg-info existing :lambda-list lambda-list))
2059          existing)
2060         ((assoc spec *!generic-function-fixups* :test #'equal)
2061          (if existing
2062              (make-early-gf spec lambda-list lambda-list-p existing
2063                             argument-precedence-order definition-source
2064                             documentation)
2065              (bug "The function ~S is not already defined." spec)))
2066         (existing
2067          (bug "~S should be on the list ~S."
2068               spec '*!generic-function-fixups*))
2069         (t
2070          (pushnew spec *!early-generic-functions* :test #'equal)
2071          (make-early-gf spec lambda-list lambda-list-p nil
2072                         argument-precedence-order definition-source
2073                         documentation))))
2074
2075 (defun make-early-gf (spec &optional lambda-list lambda-list-p
2076                       function argument-precedence-order source-location
2077                       documentation)
2078   (let ((fin (allocate-standard-funcallable-instance
2079               *sgf-wrapper* *sgf-slots-init*)))
2080     (set-funcallable-instance-function
2081      fin
2082      (or function
2083          (if (eq spec 'print-object)
2084              #'(lambda (instance stream)
2085                  (print-unreadable-object (instance stream :identity t)
2086                    (format stream "std-instance")))
2087              #'(lambda (&rest args)
2088                  (declare (ignore args))
2089                  (error "The function of the funcallable-instance ~S~
2090                          has not been set." fin)))))
2091     (setf (gdefinition spec) fin)
2092     (!bootstrap-set-slot 'standard-generic-function fin 'name spec)
2093     (!bootstrap-set-slot 'standard-generic-function fin
2094                          'source source-location)
2095     (!bootstrap-set-slot 'standard-generic-function fin
2096                          '%documentation documentation)
2097     (set-fun-name fin spec)
2098     (let ((arg-info (make-arg-info)))
2099       (setf (early-gf-arg-info fin) arg-info)
2100       (when lambda-list-p
2101         (setf (info :function :type spec)
2102               (specifier-type
2103                (ftype-declaration-from-lambda-list lambda-list spec))
2104               (info :function :where-from spec) :defined-method)
2105         (if argument-precedence-order
2106             (set-arg-info fin
2107                           :lambda-list lambda-list
2108                           :argument-precedence-order argument-precedence-order)
2109             (set-arg-info fin :lambda-list lambda-list))))
2110     fin))
2111
2112 (defun safe-gf-dfun-state (generic-function)
2113   (if (eq (class-of generic-function) *the-class-standard-generic-function*)
2114       (clos-slots-ref (fsc-instance-slots generic-function) +sgf-dfun-state-index+)
2115       (gf-dfun-state generic-function)))
2116 (defun (setf safe-gf-dfun-state) (new-value generic-function)
2117   (if (eq (class-of generic-function) *the-class-standard-generic-function*)
2118       (setf (clos-slots-ref (fsc-instance-slots generic-function)
2119                             +sgf-dfun-state-index+)
2120             new-value)
2121       (setf (gf-dfun-state generic-function) new-value)))
2122
2123 (defun set-dfun (gf &optional dfun cache info)
2124   (let ((new-state (if (and dfun (or cache info))
2125                        (list* dfun cache info)
2126                        dfun)))
2127     (cond
2128       ((eq **boot-state** 'complete)
2129        ;; Check that we are under the lock.
2130        #+sb-thread
2131        (aver (eq sb-thread:*current-thread* (sb-thread::spinlock-value (gf-lock gf))))
2132        (setf (safe-gf-dfun-state gf) new-state))
2133       (t
2134        (setf (clos-slots-ref (get-slots gf) +sgf-dfun-state-index+)
2135              new-state))))
2136   dfun)
2137
2138 (defun gf-dfun-cache (gf)
2139   (let ((state (if (eq **boot-state** 'complete)
2140                    (safe-gf-dfun-state gf)
2141                    (clos-slots-ref (get-slots gf) +sgf-dfun-state-index+))))
2142     (typecase state
2143       (function nil)
2144       (cons (cadr state)))))
2145
2146 (defun gf-dfun-info (gf)
2147   (let ((state (if (eq **boot-state** 'complete)
2148                    (safe-gf-dfun-state gf)
2149                    (clos-slots-ref (get-slots gf) +sgf-dfun-state-index+))))
2150     (typecase state
2151       (function nil)
2152       (cons (cddr state)))))
2153
2154 (defconstant +sgf-name-index+
2155   (!bootstrap-slot-index 'standard-generic-function 'name))
2156
2157 (defun !early-gf-name (gf)
2158   (clos-slots-ref (get-slots gf) +sgf-name-index+))
2159
2160 (defun gf-lambda-list (gf)
2161   (let ((arg-info (if (eq **boot-state** 'complete)
2162                       (gf-arg-info gf)
2163                       (early-gf-arg-info gf))))
2164     (if (eq :no-lambda-list (arg-info-lambda-list arg-info))
2165         (let ((methods (if (eq **boot-state** 'complete)
2166                            (generic-function-methods gf)
2167                            (early-gf-methods gf))))
2168           (if (null methods)
2169               (progn
2170                 (warn "no way to determine the lambda list for ~S" gf)
2171                 nil)
2172               (let* ((method (car (last methods)))
2173                      (ll (if (consp method)
2174                              (early-method-lambda-list method)
2175                              (method-lambda-list method))))
2176                 (create-gf-lambda-list ll))))
2177         (arg-info-lambda-list arg-info))))
2178
2179 (defmacro real-ensure-gf-internal (gf-class all-keys env)
2180   `(progn
2181      (cond ((symbolp ,gf-class)
2182             (setq ,gf-class (find-class ,gf-class t ,env)))
2183            ((classp ,gf-class))
2184            (t
2185             (error "The :GENERIC-FUNCTION-CLASS argument (~S) was neither a~%~
2186                     class nor a symbol that names a class."
2187                    ,gf-class)))
2188      (unless (class-finalized-p ,gf-class)
2189        (if (class-has-a-forward-referenced-superclass-p ,gf-class)
2190            ;; FIXME: reference MOP documentation -- this is an
2191            ;; additional requirement on our users
2192            (error "The generic function class ~S is not finalizeable" ,gf-class)
2193            (finalize-inheritance ,gf-class)))
2194      (remf ,all-keys :generic-function-class)
2195      (remf ,all-keys :environment)
2196      (let ((combin (getf ,all-keys :method-combination '.shes-not-there.)))
2197        (unless (eq combin '.shes-not-there.)
2198          (setf (getf ,all-keys :method-combination)
2199                (find-method-combination (class-prototype ,gf-class)
2200                                         (car combin)
2201                                         (cdr combin)))))
2202     (let ((method-class (getf ,all-keys :method-class '.shes-not-there.)))
2203       (unless (eq method-class '.shes-not-there.)
2204         (setf (getf ,all-keys :method-class)
2205               (cond ((classp method-class)
2206                      method-class)
2207                     (t (find-class method-class t ,env))))))))
2208
2209 (defun note-gf-signature (fun-name lambda-list-p lambda-list)
2210   (unless lambda-list-p
2211     ;; Use the existing lambda-list, if any. It is reasonable to do eg.
2212     ;;
2213     ;;   (if (fboundp name)
2214     ;;       (ensure-generic-function name)
2215     ;;       (ensure-generic-function name :lambda-list '(foo)))
2216     ;;
2217     ;; in which case we end up here with no lambda-list in the first leg.
2218     (setf (values lambda-list lambda-list-p)
2219           (handler-case
2220               (values (generic-function-lambda-list (fdefinition fun-name))
2221                       t)
2222             ((or warning error) ()
2223               (values nil nil)))))
2224   (let ((gf-type
2225          (specifier-type
2226           (if lambda-list-p
2227               (ftype-declaration-from-lambda-list lambda-list fun-name)
2228               'function)))
2229         (old-type nil))
2230     ;; FIXME: Ideally we would like to not clobber it, but because generic
2231     ;; functions assert their FTYPEs callers believing the FTYPE are left with
2232     ;; unsafe assumptions. Hence the clobbering. Be quiet when the new type
2233     ;; is a subtype of the old one, though -- even though the type is not
2234     ;; trusted anymore, the warning is still not quite as interesting.
2235     (when (and (eq :declared (info :function :where-from fun-name))
2236                (not (csubtypep gf-type (setf old-type (info :function :type fun-name)))))
2237       (style-warn "~@<Generic function ~S clobbers an earlier ~S proclamation ~S ~
2238                    for the same name with ~S.~:@>"
2239                   fun-name 'ftype
2240                   (type-specifier old-type)
2241                   (type-specifier gf-type)))
2242     (setf (info :function :type fun-name) gf-type
2243           (info :function :where-from fun-name) :defined-method)
2244     fun-name))
2245
2246 (defun real-ensure-gf-using-class--generic-function
2247        (existing
2248         fun-name
2249         &rest all-keys
2250         &key environment (lambda-list nil lambda-list-p)
2251         (generic-function-class 'standard-generic-function)
2252         &allow-other-keys)
2253   (real-ensure-gf-internal generic-function-class all-keys environment)
2254   ;; KLUDGE: the above macro does SETQ on GENERIC-FUNCTION-CLASS,
2255   ;; which is what makes the next line work
2256   (unless (eq (class-of existing) generic-function-class)
2257     (change-class existing generic-function-class))
2258   (prog1
2259       (apply #'reinitialize-instance existing all-keys)
2260     (note-gf-signature fun-name lambda-list-p lambda-list)))
2261
2262 (defun real-ensure-gf-using-class--null
2263        (existing
2264         fun-name
2265         &rest all-keys
2266         &key environment (lambda-list nil lambda-list-p)
2267              (generic-function-class 'standard-generic-function)
2268         &allow-other-keys)
2269   (declare (ignore existing))
2270   (real-ensure-gf-internal generic-function-class all-keys environment)
2271   (prog1
2272       (setf (gdefinition fun-name)
2273             (apply #'make-instance generic-function-class
2274                    :name fun-name all-keys))
2275     (note-gf-signature fun-name lambda-list-p lambda-list)))
2276 \f
2277 (defun safe-gf-arg-info (generic-function)
2278   (if (eq (class-of generic-function) *the-class-standard-generic-function*)
2279       (clos-slots-ref (fsc-instance-slots generic-function)
2280                       +sgf-arg-info-index+)
2281       (gf-arg-info generic-function)))
2282
2283 ;;; FIXME: this function took on a slightly greater role than it
2284 ;;; previously had around 2005-11-02, when CSR fixed the bug whereby
2285 ;;; having more than one subclass of standard-generic-function caused
2286 ;;; the whole system to die horribly through a metacircle in
2287 ;;; GF-ARG-INFO.  The fix is to be slightly more disciplined about
2288 ;;; calling accessor methods -- we call GET-GENERIC-FUN-INFO when
2289 ;;; computing discriminating functions, so we need to be careful about
2290 ;;; having a base case for the recursion, and we provide that with the
2291 ;;; STANDARD-GENERIC-FUNCTION case below.  However, we are not (yet)
2292 ;;; as disciplined as CLISP's CLOS/MOP, and it would be nice to get to
2293 ;;; that stage, where all potentially dangerous cases are enumerated
2294 ;;; and stopped.  -- CSR, 2005-11-02.
2295 (defun get-generic-fun-info (gf)
2296   ;; values   nreq applyp metatypes nkeys arg-info
2297   (multiple-value-bind (applyp metatypes arg-info)
2298       (let* ((arg-info (if (early-gf-p gf)
2299                            (early-gf-arg-info gf)
2300                            (safe-gf-arg-info gf)))
2301              (metatypes (arg-info-metatypes arg-info)))
2302         (values (arg-info-applyp arg-info)
2303                 metatypes
2304                 arg-info))
2305     (let ((nreq 0)
2306           (nkeys 0))
2307       (declare (fixnum nreq nkeys))
2308       (dolist (x metatypes)
2309         (incf nreq)
2310         (unless (eq x t)
2311           (incf nkeys)))
2312       (values nreq applyp metatypes
2313               nkeys
2314               arg-info))))
2315
2316 (defun generic-function-nreq (gf)
2317   (let* ((arg-info (if (early-gf-p gf)
2318                        (early-gf-arg-info gf)
2319                        (safe-gf-arg-info gf)))
2320          (metatypes (arg-info-metatypes arg-info)))
2321     (declare (list metatypes))
2322     (length metatypes)))
2323
2324 (defun early-make-a-method (class qualifiers arglist specializers initargs doc
2325                             &key slot-name object-class method-class-function
2326                             definition-source)
2327   (let ((parsed ())
2328         (unparsed ()))
2329     ;; Figure out whether we got class objects or class names as the
2330     ;; specializers and set parsed and unparsed appropriately. If we
2331     ;; got class objects, then we can compute unparsed, but if we got
2332     ;; class names we don't try to compute parsed.
2333     ;;
2334     ;; Note that the use of not symbolp in this call to every should be
2335     ;; read as 'classp' we can't use classp itself because it doesn't
2336     ;; exist yet.
2337     (if (every (lambda (s) (not (symbolp s))) specializers)
2338         (setq parsed specializers
2339               unparsed (mapcar (lambda (s)
2340                                  (if (eq s t) t (class-name s)))
2341                                specializers))
2342         (setq unparsed specializers
2343               parsed ()))
2344     (let ((result
2345            (list :early-method
2346
2347                  (getf initargs :function)
2348                  (let ((mf (getf initargs :function)))
2349                    (aver mf)
2350                    (and (typep mf '%method-function)
2351                         (%method-function-fast-function mf)))
2352
2353                  ;; the parsed specializers. This is used by
2354                  ;; EARLY-METHOD-SPECIALIZERS to cache the parse.
2355                  ;; Note that this only comes into play when there is
2356                  ;; more than one early method on an early gf.
2357                  parsed
2358
2359                  ;; A list to which REAL-MAKE-A-METHOD can be applied
2360                  ;; to make a real method corresponding to this early
2361                  ;; one.
2362                  (append
2363                   (list class qualifiers arglist unparsed
2364                         initargs doc)
2365                   (when slot-name
2366                     (list :slot-name slot-name :object-class object-class
2367                           :method-class-function method-class-function))
2368                   (list :definition-source definition-source)))))
2369       (initialize-method-function initargs result)
2370       result)))
2371
2372 (defun real-make-a-method
2373        (class qualifiers lambda-list specializers initargs doc
2374         &rest args &key slot-name object-class method-class-function
2375         definition-source)
2376   (if method-class-function
2377       (let* ((object-class (if (classp object-class) object-class
2378                                (find-class object-class)))
2379              (slots (class-direct-slots object-class))
2380              (slot-definition (find slot-name slots
2381                                     :key #'slot-definition-name)))
2382         (aver slot-name)
2383         (aver slot-definition)
2384         (let ((initargs (list* :qualifiers qualifiers :lambda-list lambda-list
2385                                :specializers specializers :documentation doc
2386                                :slot-definition slot-definition
2387                                :slot-name slot-name initargs)))
2388           (apply #'make-instance
2389                  (apply method-class-function object-class slot-definition
2390                         initargs)
2391                  :definition-source definition-source
2392                  initargs)))
2393       (apply #'make-instance class :qualifiers qualifiers
2394              :lambda-list lambda-list :specializers specializers
2395              :documentation doc (append args initargs))))
2396
2397 (defun early-method-function (early-method)
2398   (values (cadr early-method) (caddr early-method)))
2399
2400 (defun early-method-class (early-method)
2401   (find-class (car (fifth early-method))))
2402
2403 (defun early-method-standard-accessor-p (early-method)
2404   (let ((class (first (fifth early-method))))
2405     (or (eq class 'standard-reader-method)
2406         (eq class 'standard-writer-method)
2407         (eq class 'standard-boundp-method))))
2408
2409 (defun early-method-standard-accessor-slot-name (early-method)
2410   (eighth (fifth early-method)))
2411
2412 ;;; Fetch the specializers of an early method. This is basically just
2413 ;;; a simple accessor except that when the second argument is t, this
2414 ;;; converts the specializers from symbols into class objects. The
2415 ;;; class objects are cached in the early method, this makes
2416 ;;; bootstrapping faster because the class objects only have to be
2417 ;;; computed once.
2418 ;;;
2419 ;;; NOTE:
2420 ;;;  The second argument should only be passed as T by
2421 ;;;  early-lookup-method. This is to implement the rule that only when
2422 ;;;  there is more than one early method on a generic function is the
2423 ;;;  conversion from class names to class objects done. This
2424 ;;;  corresponds to the fact that we are only allowed to have one
2425 ;;;  method on any generic function up until the time classes exist.
2426 (defun early-method-specializers (early-method &optional objectsp)
2427   (if (and (listp early-method)
2428            (eq (car early-method) :early-method))
2429       (cond ((eq objectsp t)
2430              (or (fourth early-method)
2431                  (setf (fourth early-method)
2432                        (mapcar #'find-class (cadddr (fifth early-method))))))
2433             (t
2434              (fourth (fifth early-method))))
2435       (error "~S is not an early-method." early-method)))
2436
2437 (defun early-method-qualifiers (early-method)
2438   (second (fifth early-method)))
2439
2440 (defun early-method-lambda-list (early-method)
2441   (third (fifth early-method)))
2442
2443 (defun early-method-initargs (early-method)
2444   (fifth (fifth early-method)))
2445
2446 (defun (setf early-method-initargs) (new-value early-method)
2447   (setf (fifth (fifth early-method)) new-value))
2448
2449 (defun early-add-named-method (generic-function-name qualifiers
2450                                specializers arglist &rest initargs
2451                                &key documentation definition-source
2452                                &allow-other-keys)
2453   (let* (;; we don't need to deal with the :generic-function-class
2454          ;; argument here because the default,
2455          ;; STANDARD-GENERIC-FUNCTION, is right for all early generic
2456          ;; functions.  (See REAL-ADD-NAMED-METHOD)
2457          (gf (ensure-generic-function generic-function-name))
2458          (existing
2459            (dolist (m (early-gf-methods gf))
2460              (when (and (equal (early-method-specializers m) specializers)
2461                         (equal (early-method-qualifiers m) qualifiers))
2462                (return m)))))
2463     (setf (getf (getf initargs 'plist) :name)
2464           (make-method-spec gf qualifiers specializers))
2465     (let ((new (make-a-method 'standard-method qualifiers arglist
2466                               specializers initargs documentation
2467                               :definition-source definition-source)))
2468       (when existing (remove-method gf existing))
2469       (add-method gf new))))
2470
2471 ;;; This is the early version of ADD-METHOD. Later this will become a
2472 ;;; generic function. See !FIX-EARLY-GENERIC-FUNCTIONS which has
2473 ;;; special knowledge about ADD-METHOD.
2474 (defun add-method (generic-function method)
2475   (when (not (fsc-instance-p generic-function))
2476     (error "Early ADD-METHOD didn't get a funcallable instance."))
2477   (when (not (and (listp method) (eq (car method) :early-method)))
2478     (error "Early ADD-METHOD didn't get an early method."))
2479   (push method (early-gf-methods generic-function))
2480   (set-arg-info generic-function :new-method method)
2481   (unless (assoc (!early-gf-name generic-function)
2482                  *!generic-function-fixups*
2483                  :test #'equal)
2484     (update-dfun generic-function)))
2485
2486 ;;; This is the early version of REMOVE-METHOD. See comments on
2487 ;;; the early version of ADD-METHOD.
2488 (defun remove-method (generic-function method)
2489   (when (not (fsc-instance-p generic-function))
2490     (error "An early remove-method didn't get a funcallable instance."))
2491   (when (not (and (listp method) (eq (car method) :early-method)))
2492     (error "An early remove-method didn't get an early method."))
2493   (setf (early-gf-methods generic-function)
2494         (remove method (early-gf-methods generic-function)))
2495   (set-arg-info generic-function)
2496   (unless (assoc (!early-gf-name generic-function)
2497                  *!generic-function-fixups*
2498                  :test #'equal)
2499     (update-dfun generic-function)))
2500
2501 ;;; This is the early version of GET-METHOD. See comments on the early
2502 ;;; version of ADD-METHOD.
2503 (defun get-method (generic-function qualifiers specializers
2504                                     &optional (errorp t))
2505   (if (early-gf-p generic-function)
2506       (or (dolist (m (early-gf-methods generic-function))
2507             (when (and (or (equal (early-method-specializers m nil)
2508                                   specializers)
2509                            (equal (early-method-specializers m t)
2510                                   specializers))
2511                        (equal (early-method-qualifiers m) qualifiers))
2512               (return m)))
2513           (if errorp
2514               (error "can't get early method")
2515               nil))
2516       (real-get-method generic-function qualifiers specializers errorp)))
2517
2518 (defun !fix-early-generic-functions ()
2519   (let ((accessors nil))
2520     ;; Rearrange *!EARLY-GENERIC-FUNCTIONS* to speed up
2521     ;; FIX-EARLY-GENERIC-FUNCTIONS.
2522     (dolist (early-gf-spec *!early-generic-functions*)
2523       (when (every #'early-method-standard-accessor-p
2524                    (early-gf-methods (gdefinition early-gf-spec)))
2525         (push early-gf-spec accessors)))
2526     (dolist (spec (nconc accessors
2527                          '(accessor-method-slot-name
2528                            generic-function-methods
2529                            method-specializers
2530                            specializerp
2531                            specializer-type
2532                            specializer-class
2533                            slot-definition-location
2534                            slot-definition-name
2535                            class-slots
2536                            gf-arg-info
2537                            class-precedence-list
2538                            slot-boundp-using-class
2539                            (setf slot-value-using-class)
2540                            slot-value-using-class
2541                            structure-class-p
2542                            standard-class-p
2543                            funcallable-standard-class-p
2544                            specializerp)))
2545       (/show spec)
2546       (setq *!early-generic-functions*
2547             (cons spec
2548                   (delete spec *!early-generic-functions* :test #'equal))))
2549
2550     (dolist (early-gf-spec *!early-generic-functions*)
2551       (/show early-gf-spec)
2552       (let* ((gf (gdefinition early-gf-spec))
2553              (methods (mapcar (lambda (early-method)
2554                                 (let ((args (copy-list (fifth
2555                                                         early-method))))
2556                                   (setf (fourth args)
2557                                         (early-method-specializers
2558                                          early-method t))
2559                                   (apply #'real-make-a-method args)))
2560                               (early-gf-methods gf))))
2561         (setf (generic-function-method-class gf) *the-class-standard-method*)
2562         (setf (generic-function-method-combination gf)
2563               *standard-method-combination*)
2564         (set-methods gf methods)))
2565
2566     (dolist (fn *!early-functions*)
2567       (/show fn)
2568       (setf (gdefinition (car fn)) (fdefinition (caddr fn))))
2569
2570     (dolist (fixup *!generic-function-fixups*)
2571       (/show fixup)
2572       (let* ((fspec (car fixup))
2573              (gf (gdefinition fspec))
2574              (methods (mapcar (lambda (method)
2575                                 (let* ((lambda-list (first method))
2576                                        (specializers (mapcar #'find-class (second method)))
2577                                        (method-fn-name (third method))
2578                                        (fn-name (or method-fn-name fspec))
2579                                        (fn (fdefinition fn-name))
2580                                        (initargs
2581                                         (list :function
2582                                               (set-fun-name
2583                                                (lambda (args next-methods)
2584                                                  (declare (ignore
2585                                                            next-methods))
2586                                                  (apply fn args))
2587                                                `(call ,fn-name)))))
2588                                   (declare (type function fn))
2589                                   (make-a-method 'standard-method
2590                                                  ()
2591                                                  lambda-list
2592                                                  specializers
2593                                                  initargs
2594                                                  nil)))
2595                               (cdr fixup))))
2596         (setf (generic-function-method-class gf) *the-class-standard-method*)
2597         (setf (generic-function-method-combination gf)
2598               *standard-method-combination*)
2599         (set-methods gf methods))))
2600   (/show "leaving !FIX-EARLY-GENERIC-FUNCTIONS"))
2601 \f
2602 ;;; PARSE-DEFMETHOD is used by DEFMETHOD to parse the &REST argument
2603 ;;; into the 'real' arguments. This is where the syntax of DEFMETHOD
2604 ;;; is really implemented.
2605 (defun parse-defmethod (cdr-of-form)
2606   (declare (list cdr-of-form))
2607   (let ((name (pop cdr-of-form))
2608         (qualifiers ())
2609         (spec-ll ()))
2610     (loop (if (and (car cdr-of-form) (atom (car cdr-of-form)))
2611               (push (pop cdr-of-form) qualifiers)
2612               (return (setq qualifiers (nreverse qualifiers)))))
2613     (setq spec-ll (pop cdr-of-form))
2614     (values name qualifiers spec-ll cdr-of-form)))
2615
2616 (defun parse-specializers (generic-function specializers)
2617   (declare (list specializers))
2618   (flet ((parse (spec)
2619            (parse-specializer-using-class generic-function spec)))
2620     (mapcar #'parse specializers)))
2621
2622 (defun unparse-specializers (generic-function specializers)
2623   (declare (list specializers))
2624   (flet ((unparse (spec)
2625            (unparse-specializer-using-class generic-function spec)))
2626     (mapcar #'unparse specializers)))
2627 \f
2628 (defun extract-parameters (specialized-lambda-list)
2629   (multiple-value-bind (parameters ignore1 ignore2)
2630       (parse-specialized-lambda-list specialized-lambda-list)
2631     (declare (ignore ignore1 ignore2))
2632     parameters))
2633
2634 (defun extract-lambda-list (specialized-lambda-list)
2635   (multiple-value-bind (ignore1 lambda-list ignore2)
2636       (parse-specialized-lambda-list specialized-lambda-list)
2637     (declare (ignore ignore1 ignore2))
2638     lambda-list))
2639
2640 (defun extract-specializer-names (specialized-lambda-list)
2641   (multiple-value-bind (ignore1 ignore2 specializers)
2642       (parse-specialized-lambda-list specialized-lambda-list)
2643     (declare (ignore ignore1 ignore2))
2644     specializers))
2645
2646 (defun extract-required-parameters (specialized-lambda-list)
2647   (multiple-value-bind (ignore1 ignore2 ignore3 required-parameters)
2648       (parse-specialized-lambda-list specialized-lambda-list)
2649     (declare (ignore ignore1 ignore2 ignore3))
2650     required-parameters))
2651
2652 (define-condition specialized-lambda-list-error
2653     (reference-condition simple-program-error)
2654   ()
2655   (:default-initargs :references (list '(:ansi-cl :section (3 4 3)))))
2656
2657 (defun parse-specialized-lambda-list
2658     (arglist
2659      &optional supplied-keywords (allowed-keywords '(&optional &rest &key &aux))
2660      &aux (specialized-lambda-list-keywords
2661            '(&optional &rest &key &allow-other-keys &aux)))
2662   (let ((arg (car arglist)))
2663     (cond ((null arglist) (values nil nil nil nil))
2664           ((eq arg '&aux)
2665            (values nil arglist nil nil))
2666           ((memq arg lambda-list-keywords)
2667            ;; non-standard lambda-list-keywords are errors.
2668            (unless (memq arg specialized-lambda-list-keywords)
2669              (error 'specialized-lambda-list-error
2670                     :format-control "unknown specialized-lambda-list ~
2671                                      keyword ~S~%"
2672                     :format-arguments (list arg)))
2673            ;; no multiple &rest x &rest bla specifying
2674            (when (memq arg supplied-keywords)
2675              (error 'specialized-lambda-list-error
2676                     :format-control "multiple occurrence of ~
2677                                      specialized-lambda-list keyword ~S~%"
2678                     :format-arguments (list arg)))
2679            ;; And no placing &key in front of &optional, either.
2680            (unless (memq arg allowed-keywords)
2681              (error 'specialized-lambda-list-error
2682                     :format-control "misplaced specialized-lambda-list ~
2683                                      keyword ~S~%"
2684                     :format-arguments (list arg)))
2685            ;; When we are at a lambda-list keyword, the parameters
2686            ;; don't include the lambda-list keyword; the lambda-list
2687            ;; does include the lambda-list keyword; and no
2688            ;; specializers are allowed to follow the lambda-list
2689            ;; keywords (at least for now).
2690            (multiple-value-bind (parameters lambda-list)
2691                (parse-specialized-lambda-list (cdr arglist)
2692                                               (cons arg supplied-keywords)
2693                                               (if (eq arg '&key)
2694                                                   (cons '&allow-other-keys
2695                                                         (cdr (member arg allowed-keywords)))
2696                                                 (cdr (member arg allowed-keywords))))
2697              (when (and (eq arg '&rest)
2698                         (or (null lambda-list)
2699                             (memq (car lambda-list)
2700                                   specialized-lambda-list-keywords)
2701                             (not (or (null (cadr lambda-list))
2702                                      (memq (cadr lambda-list)
2703                                            specialized-lambda-list-keywords)))))
2704                (error 'specialized-lambda-list-error
2705                       :format-control
2706                       "in a specialized-lambda-list, excactly one ~
2707                        variable must follow &REST.~%"
2708                       :format-arguments nil))
2709              (values parameters
2710                      (cons arg lambda-list)
2711                      ()
2712                      ())))
2713           (supplied-keywords
2714            ;; After a lambda-list keyword there can be no specializers.
2715            (multiple-value-bind (parameters lambda-list)
2716                (parse-specialized-lambda-list (cdr arglist)
2717                                               supplied-keywords
2718                                               allowed-keywords)
2719              (values (cons (if (listp arg) (car arg) arg) parameters)
2720                      (cons arg lambda-list)
2721                      ()
2722                      ())))
2723           (t
2724            (multiple-value-bind (parameters lambda-list specializers required)
2725                (parse-specialized-lambda-list (cdr arglist))
2726              ;; Check for valid arguments.
2727              (unless (or (and (symbolp arg) (not (null arg)))
2728                          (and (consp arg)
2729                               (consp (cdr arg))
2730                               (null (cddr arg))))
2731                (error 'specialized-lambda-list-error
2732                       :format-control "arg is not a non-NIL symbol or a list of two elements: ~A"
2733                       :format-arguments (list arg)))
2734              (values (cons (if (listp arg) (car arg) arg) parameters)
2735                      (cons (if (listp arg) (car arg) arg) lambda-list)
2736                      (cons (if (listp arg) (cadr arg) t) specializers)
2737                      (cons (if (listp arg) (car arg) arg) required)))))))
2738 \f
2739 (setq **boot-state** 'early)
2740 \f
2741 ;;; FIXME: In here there was a #-CMU definition of SYMBOL-MACROLET
2742 ;;; which used %WALKER stuff. That suggests to me that maybe the code
2743 ;;; walker stuff was only used for implementing stuff like that; maybe
2744 ;;; it's not needed any more? Hunt down what it was used for and see.
2745
2746 (defun extract-the (form)
2747   (cond ((and (consp form) (eq (car form) 'the))
2748          (aver (proper-list-of-length-p form 3))
2749          (third form))
2750         (t
2751          form)))
2752
2753 (defmacro with-slots (slots instance &body body)
2754   (let ((in (gensym)))
2755     `(let ((,in ,instance))
2756        (declare (ignorable ,in))
2757        ,@(let ((instance (extract-the instance)))
2758            (and (symbolp instance)
2759                 `((declare (%variable-rebinding ,in ,instance)))))
2760        ,in
2761        (symbol-macrolet ,(mapcar (lambda (slot-entry)
2762                                    (let ((var-name
2763                                           (if (symbolp slot-entry)
2764                                               slot-entry
2765                                               (car slot-entry)))
2766                                          (slot-name
2767                                           (if (symbolp slot-entry)
2768                                               slot-entry
2769                                               (cadr slot-entry))))
2770                                      `(,var-name
2771                                        (slot-value ,in ',slot-name))))
2772                                  slots)
2773                         ,@body))))
2774
2775 (defmacro with-accessors (slots instance &body body)
2776   (let ((in (gensym)))
2777     `(let ((,in ,instance))
2778        (declare (ignorable ,in))
2779        ,@(let ((instance (extract-the instance)))
2780            (and (symbolp instance)
2781                 `((declare (%variable-rebinding ,in ,instance)))))
2782        ,in
2783        (symbol-macrolet ,(mapcar (lambda (slot-entry)
2784                                    (let ((var-name (car slot-entry))
2785                                          (accessor-name (cadr slot-entry)))
2786                                      `(,var-name (,accessor-name ,in))))
2787                                  slots)
2788           ,@body))))