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