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