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