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