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