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