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