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