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