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