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