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