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