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