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