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