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