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