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