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