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