0.8.3.4:
[sbcl.git] / src / pcl / defcombin.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 (defmacro define-method-combination (&whole form &rest args)
27   (declare (ignore args))
28   (if (and (cddr form)
29            (listp (caddr form)))
30       (expand-long-defcombin form)
31       (expand-short-defcombin form)))
32 \f
33 ;;;; standard method combination
34
35 ;;; The STANDARD method combination type is implemented directly by
36 ;;; the class STANDARD-METHOD-COMBINATION. The method on
37 ;;; COMPUTE-EFFECTIVE-METHOD does standard method combination directly
38 ;;; and is defined by hand in the file combin.lisp. The method for
39 ;;; FIND-METHOD-COMBINATION must appear in this file for bootstrapping
40 ;;; reasons.
41 (defmethod find-method-combination ((generic-function generic-function)
42                                     (type (eql 'standard))
43                                     options)
44   (when options
45     (method-combination-error
46       "The method combination type STANDARD accepts no options."))
47   *standard-method-combination*)
48 \f
49 ;;;; short method combinations
50 ;;;;
51 ;;;; Short method combinations all follow the same rule for computing the
52 ;;;; effective method. So, we just implement that rule once. Each short
53 ;;;; method combination object just reads the parameters out of the object
54 ;;;; and runs the same rule.
55
56 (defclass short-method-combination (standard-method-combination)
57   ((operator
58     :reader short-combination-operator
59     :initarg :operator)
60    (identity-with-one-argument
61     :reader short-combination-identity-with-one-argument
62     :initarg :identity-with-one-argument))
63   (:predicate-name short-method-combination-p))
64
65 (defun expand-short-defcombin (whole)
66   (let* ((type (cadr whole))
67          (documentation
68            (getf (cddr whole) :documentation ""))
69          (identity-with-one-arg
70            (getf (cddr whole) :identity-with-one-argument nil))
71          (operator
72            (getf (cddr whole) :operator type)))
73     `(load-short-defcombin
74      ',type ',operator ',identity-with-one-arg ',documentation)))
75
76 (defun load-short-defcombin (type operator ioa doc)
77   (let* ((pathname *load-pathname*)
78          (specializers
79            (list (find-class 'generic-function)
80                  (intern-eql-specializer type)
81                  *the-class-t*))
82          (old-method
83            (get-method #'find-method-combination () specializers nil))
84          (new-method nil))
85     (setq new-method
86           (make-instance 'standard-method
87             :qualifiers ()
88             :specializers specializers
89             :lambda-list '(generic-function type options)
90             :function (lambda (args nms &rest cm-args)
91                         (declare (ignore nms cm-args))
92                         (apply
93                          (lambda (gf type options)
94                            (declare (ignore gf))
95                            (short-combine-methods
96                             type options operator ioa new-method doc))
97                          args))
98             :definition-source `((define-method-combination ,type) ,pathname)))
99     (when old-method
100       (remove-method #'find-method-combination old-method))
101     (add-method #'find-method-combination new-method)
102     type))
103
104 (defun short-combine-methods (type options operator ioa method doc)
105   (cond ((null options) (setq options '(:most-specific-first)))
106         ((equal options '(:most-specific-first)))
107         ((equal options '(:most-specific-last)))
108         (t
109          (method-combination-error
110           "Illegal options to a short method combination type.~%~
111            The method combination type ~S accepts one option which~%~
112            must be either :MOST-SPECIFIC-FIRST or :MOST-SPECIFIC-LAST."
113           type)))
114   (make-instance 'short-method-combination
115                  :type type
116                  :options options
117                  :operator operator
118                  :identity-with-one-argument ioa
119                  :definition-source method
120                  :documentation doc))
121
122 (defmethod compute-effective-method ((generic-function generic-function)
123                                      (combin short-method-combination)
124                                      applicable-methods)
125   (let ((type (method-combination-type combin))
126         (operator (short-combination-operator combin))
127         (ioa (short-combination-identity-with-one-argument combin))
128         (order (car (method-combination-options combin)))
129         (around ())
130         (primary ()))
131     (flet ((invalid (gf combin m)
132              (if *in-precompute-effective-methods-p*
133                  (return-from compute-effective-method
134                    `(%invalid-qualifiers ',gf ',combin ',m))
135                  (invalid-qualifiers gf combin m))))
136       (dolist (m applicable-methods)
137         (let ((qualifiers (method-qualifiers m)))
138           (cond ((null qualifiers) (invalid generic-function combin m))
139                 ((cdr qualifiers) (invalid generic-function combin m))
140                 ((eq (car qualifiers) :around)
141                  (push m around))
142                 ((eq (car qualifiers) type)
143                  (push m primary))
144                 (t (invalid generic-function combin m))))))
145     (setq around (nreverse around))
146     (ecase order
147       (:most-specific-last) ; nothing to be done, already in correct order
148       (:most-specific-first
149        (setq primary (nreverse primary))))
150     (let ((main-method
151             (if (and (null (cdr primary))
152                      (not (null ioa)))
153                 `(call-method ,(car primary) ())
154                 `(,operator ,@(mapcar (lambda (m) `(call-method ,m ()))
155                                       primary)))))
156       (cond ((null primary)
157              ;; As of sbcl-0.8.0.80 we don't seem to need to need
158              ;; to do anything messy like
159              ;;        `(APPLY (FUNCTION (IF AROUND
160              ;;                              'NO-PRIMARY-METHOD
161              ;;                              'NO-APPLICABLE-METHOD)
162              ;;                           ',GENERIC-FUNCTION
163              ;;                           .ARGS.)
164              ;; here because (for reasons I don't understand at the
165              ;; moment -- WHN) control will never reach here if there
166              ;; are no applicable methods, but instead end up
167              ;; in NO-APPLICABLE-METHODS first.
168              ;;
169              ;; FIXME: The way that we arrange for .ARGS. to be bound 
170              ;; here seems weird. We rely on EXPAND-EFFECTIVE-METHOD-FUNCTION
171              ;; recognizing any form whose operator is %NO-PRIMARY-METHOD
172              ;; as magical, and carefully surrounding it with a
173              ;; LAMBDA form which binds .ARGS. But...
174              ;;   1. That seems fragile, because the magicalness of
175              ;;      %NO-PRIMARY-METHOD forms is scattered around
176              ;;      the system. So it could easily be broken by
177              ;;      locally-plausible maintenance changes like,
178              ;;      e.g., using the APPLY expression above.
179              ;;   2. That seems buggy w.r.t. to MOPpish tricks in
180              ;;      user code, e.g.
181              ;;         (DEFMETHOD COMPUTE-EFFECTIVE-METHOD :AROUND (...)
182              ;;           `(PROGN ,(CALL-NEXT-METHOD) (INCF *MY-CTR*)))
183              `(%no-primary-method ',generic-function .args.))
184             ((null around) main-method)
185             (t
186              `(call-method ,(car around)
187                            (,@(cdr around) (make-method ,main-method))))))))
188
189 (defmethod invalid-qualifiers ((gf generic-function)
190                                (combin short-method-combination)
191                                method)
192   (let ((qualifiers (method-qualifiers method))
193         (type (method-combination-type combin)))
194     (let ((why (cond
195                  ((null qualifiers) "has no qualifiers")
196                  ((cdr qualifiers) "has too many qualifiers")
197                  (t (aver (and (neq (car qualifiers) type)
198                                (neq (car qualifiers) :around)))
199                     "has an invalid qualifier"))))
200       (invalid-method-error
201        method
202        "The method ~S on ~S ~A.~%~
203         The method combination type ~S was defined with the~%~
204         short form of DEFINE-METHOD-COMBINATION and so requires~%~
205         all methods have either the single qualifier ~S or the~%~
206         single qualifier :AROUND."
207        method gf why type type))))
208 \f
209 ;;;; long method combinations
210
211 (defun expand-long-defcombin (form)
212   (let ((type (cadr form))
213         (lambda-list (caddr form))
214         (method-group-specifiers (cadddr form))
215         (body (cddddr form))
216         (args-option ())
217         (gf-var nil))
218     (when (and (consp (car body)) (eq (caar body) :arguments))
219       (setq args-option (cdr (pop body))))
220     (when (and (consp (car body)) (eq (caar body) :generic-function))
221       (setq gf-var (cadr (pop body))))
222     (multiple-value-bind (documentation function)
223         (make-long-method-combination-function
224           type lambda-list method-group-specifiers args-option gf-var
225           body)
226       `(load-long-defcombin ',type ',documentation #',function
227                             ',args-option))))
228
229 (defvar *long-method-combination-functions* (make-hash-table :test 'eq))
230
231 (defun load-long-defcombin (type doc function args-lambda-list)
232   (let* ((specializers
233            (list (find-class 'generic-function)
234                  (intern-eql-specializer type)
235                  *the-class-t*))
236          (old-method
237            (get-method #'find-method-combination () specializers nil))
238          (new-method
239            (make-instance 'standard-method
240              :qualifiers ()
241              :specializers specializers
242              :lambda-list '(generic-function type options)
243              :function (lambda (args nms &rest cm-args)
244                          (declare (ignore nms cm-args))
245                          (apply
246                           (lambda (generic-function type options)
247                             (declare (ignore generic-function))
248                             (make-instance 'long-method-combination
249                                            :type type
250                                            :options options
251                                            :args-lambda-list args-lambda-list
252                                            :documentation doc))
253                           args))
254              :definition-source `((define-method-combination ,type)
255                                   ,*load-pathname*))))
256     (setf (gethash type *long-method-combination-functions*) function)
257     (when old-method (remove-method #'find-method-combination old-method))
258     (add-method #'find-method-combination new-method)
259     type))
260
261 (defmethod compute-effective-method ((generic-function generic-function)
262                                      (combin long-method-combination)
263                                      applicable-methods)
264   (funcall (gethash (method-combination-type combin)
265                     *long-method-combination-functions*)
266            generic-function
267            combin
268            applicable-methods))
269
270 (defun make-long-method-combination-function
271        (type ll method-group-specifiers args-option gf-var body)
272   (declare (ignore type))
273   (multiple-value-bind (real-body declarations documentation)
274       (parse-body body)
275     (let ((wrapped-body
276             (wrap-method-group-specifier-bindings method-group-specifiers
277                                                   declarations
278                                                   real-body)))
279       (when gf-var
280         (push `(,gf-var .generic-function.) (cadr wrapped-body)))
281
282       (when args-option
283         (setq wrapped-body (deal-with-args-option wrapped-body args-option)))
284
285       (when ll
286         (setq wrapped-body
287               `(apply #'(lambda ,ll ,wrapped-body)
288                       (method-combination-options .method-combination.))))
289
290       (values
291         documentation
292         `(lambda (.generic-function. .method-combination. .applicable-methods.)
293            (declare (ignorable .generic-function.
294                      .method-combination. .applicable-methods.))
295            (block .long-method-combination-function. ,wrapped-body))))))
296
297 ;; parse-method-group-specifiers parse the method-group-specifiers
298
299 (defun wrap-method-group-specifier-bindings
300        (method-group-specifiers declarations real-body)
301   (let (names
302         specializer-caches
303         cond-clauses
304         required-checks
305         order-cleanups)
306       (dolist (method-group-specifier method-group-specifiers)
307         (multiple-value-bind (name tests description order required)
308             (parse-method-group-specifier method-group-specifier)
309           (declare (ignore description))
310           (let ((specializer-cache (gensym)))
311             (push name names)
312             (push specializer-cache specializer-caches)
313             (push `((or ,@tests)
314                     (if (and (equal ,specializer-cache .specializers.)
315                              (not (null .specializers.)))
316                         (return-from .long-method-combination-function.
317                           '(error "More than one method of type ~S ~
318                                       with the same specializers."
319                                    ',name))
320                         (setq ,specializer-cache .specializers.))
321                     (push .method. ,name))
322                   cond-clauses)
323             (when required
324               (push `(when (null ,name)
325                          (return-from .long-method-combination-function.
326                            '(error "No ~S methods." ',name)))
327                       required-checks))
328             (loop (unless (and (constantp order)
329                                (neq order (setq order (eval order))))
330                     (return t)))
331             (push (cond ((eq order :most-specific-first)
332                            `(setq ,name (nreverse ,name)))
333                           ((eq order :most-specific-last) ())
334                           (t
335                            `(ecase ,order
336                               (:most-specific-first
337                                 (setq ,name (nreverse ,name)))
338                               (:most-specific-last))))
339                     order-cleanups))))
340    `(let (,@(nreverse names) ,@(nreverse specializer-caches))
341       ,@declarations
342       (dolist (.method. .applicable-methods.)
343         (let ((.qualifiers. (method-qualifiers .method.))
344               (.specializers. (method-specializers .method.)))
345           (declare (ignorable .qualifiers. .specializers.))
346           (cond ,@(nreverse cond-clauses))))
347       ,@(nreverse required-checks)
348       ,@(nreverse order-cleanups)
349       ,@real-body)))
350
351 (defun parse-method-group-specifier (method-group-specifier)
352   ;;(declare (values name tests description order required))
353   (let* ((name (pop method-group-specifier))
354          (patterns ())
355          (tests
356            (let (collect)
357              (block collect-tests
358                (loop
359                  (if (or (null method-group-specifier)
360                          (memq (car method-group-specifier)
361                                '(:description :order :required)))
362                      (return-from collect-tests t)
363                      (let ((pattern (pop method-group-specifier)))
364                        (push pattern patterns)
365                        (push (parse-qualifier-pattern name pattern)
366                              collect)))))
367              (nreverse collect))))
368     (values name
369             tests
370             (getf method-group-specifier :description
371                   (make-default-method-group-description patterns))
372             (getf method-group-specifier :order :most-specific-first)
373             (getf method-group-specifier :required nil))))
374
375 (defun parse-qualifier-pattern (name pattern)
376   (cond ((eq pattern '()) `(null .qualifiers.))
377         ((eq pattern '*) t)
378         ((symbolp pattern) `(,pattern .qualifiers.))
379         ((listp pattern) `(qualifier-check-runtime ',pattern .qualifiers.))
380         (t (error "In the method group specifier ~S,~%~
381                    ~S isn't a valid qualifier pattern."
382                   name pattern))))
383
384 (defun qualifier-check-runtime (pattern qualifiers)
385   (loop (cond ((and (null pattern) (null qualifiers))
386                (return t))
387               ((eq pattern '*) (return t))
388               ((and pattern qualifiers (eq (car pattern) (car qualifiers)))
389                (pop pattern)
390                (pop qualifiers))
391               (t (return nil)))))
392
393 (defun make-default-method-group-description (patterns)
394   (if (cdr patterns)
395       (format nil
396               "methods matching one of the patterns: ~{~S, ~} ~S"
397               (butlast patterns) (car (last patterns)))
398       (format nil
399               "methods matching the pattern: ~S"
400               (car patterns))))
401
402 ;;; This baby is a complete mess. I can't believe we put it in this
403 ;;; way. No doubt this is a large part of what drives MLY crazy.
404 ;;;
405 ;;; At runtime (when the effective-method is run), we bind an intercept
406 ;;; lambda-list to the arguments to the generic function.
407 ;;;
408 ;;; At compute-effective-method time, the symbols in the :arguments
409 ;;; option are bound to the symbols in the intercept lambda list.
410 (defun deal-with-args-option (wrapped-body args-lambda-list)
411   (let ((intercept-rebindings
412          (let (rebindings)
413            (dolist (arg args-lambda-list (nreverse rebindings))
414              (unless (member arg lambda-list-keywords)
415                (push `(,arg ',arg) rebindings)))))
416         (nreq 0)
417         (nopt 0)
418         (whole nil))
419     ;; Count the number of required and optional parameters in
420     ;; ARGS-LAMBDA-LIST into NREQ and NOPT, and set WHOLE to the
421     ;; name of a &WHOLE parameter, if any.
422     (when (member '&whole (rest args-lambda-list))
423       (error 'simple-program-error
424              :format-control "~@<The value of the :ARGUMENTS option of ~
425                 DEFINE-METHOD-COMBINATION is~2I~_~S,~I~_but &WHOLE may ~
426                 only appear first in the lambda list.~:>"
427              :format-arguments (list args-lambda-list)))
428     (loop with state = 'required
429           for arg in args-lambda-list do
430             (if (memq arg lambda-list-keywords)
431                 (setq state arg)
432                 (case state
433                   (required (incf nreq))
434                   (&optional (incf nopt))
435                   (&whole (setq whole arg state 'required)))))
436     ;; This assumes that the head of WRAPPED-BODY is a let, and it
437     ;; injects let-bindings of the form (ARG 'SYM) for all variables
438     ;; of the argument-lambda-list; SYM is a gensym.
439     (aver (memq (first wrapped-body) '(let let*)))
440     (setf (second wrapped-body)
441           (append intercept-rebindings (second wrapped-body)))
442     ;; Be sure to fill out the args lambda list so that it can be too
443     ;; short if it wants to.
444     (unless (or (memq '&rest args-lambda-list)
445                 (memq '&allow-other-keys args-lambda-list))
446       (let ((aux (memq '&aux args-lambda-list)))
447         (setq args-lambda-list
448               (append (ldiff args-lambda-list aux)
449                       (if (memq '&key args-lambda-list)
450                           '(&allow-other-keys)
451                           '(&rest .ignore.))
452                       aux))))
453     ;; .GENERIC-FUNCTION. is bound to the generic function in the
454     ;; method combination function, and .GF-ARGS* is bound to the
455     ;; generic function arguments in effective method functions
456     ;; created for generic functions having a method combination that
457     ;; uses :ARGUMENTS.
458     ;;
459     ;; The DESTRUCTURING-BIND binds the parameters of the
460     ;; ARGS-LAMBDA-LIST to actual generic function arguments.  Because
461     ;; ARGS-LAMBDA-LIST may be shorter or longer than the generic
462     ;; function's lambda list, which is only known at run time, this
463     ;; destructuring has to be done on a slighly modified list of
464     ;; actual arguments, from which values might be stripped or added.
465     ;;
466     ;; Using one of the variable names in the body inserts a symbol
467     ;; into the effective method, and running the effective method
468     ;; produces the value of actual argument that is bound to the
469     ;; symbol.
470     `(let ((inner-result. ,wrapped-body)
471            (gf-lambda-list (generic-function-lambda-list .generic-function.)))
472        `(destructuring-bind ,',args-lambda-list
473             (frob-combined-method-args
474              .gf-args. ',gf-lambda-list
475              ,',nreq ,',nopt)
476           ,,(when (memq '.ignore. args-lambda-list)
477               ''(declare (ignore .ignore.)))
478           ;; If there is a &WHOLE in the args-lambda-list, let
479           ;; it result in the actual arguments of the generic-function
480           ;; not the frobbed list.
481           ,,(when whole
482               ``(setq ,',whole .gf-args.))
483           ,inner-result.))))
484
485 ;;; Partition VALUES into three sections: required, optional, and the
486 ;;; rest, according to required, optional, and other parameters in
487 ;;; LAMBDA-LIST.  Make the required and optional sections NREQ and
488 ;;; NOPT elements long by discarding values or adding NILs.  Value is
489 ;;; the concatenated list of required and optional sections, and what
490 ;;; is left as rest from VALUES.
491 (defun frob-combined-method-args (values lambda-list nreq nopt)
492   (loop with section = 'required
493         for arg in lambda-list
494         if (memq arg lambda-list-keywords) do
495           (setq section arg)
496           (unless (eq section '&optional)
497             (loop-finish))
498         else if (eq section 'required)
499           count t into nr
500           and collect (pop values) into required
501         else if (eq section '&optional)
502           count t into no
503           and collect (pop values) into optional
504         finally
505           (flet ((frob (list n m)
506                    (cond ((> n m) (butlast list (- n m)))
507                          ((< n m) (nconc list (make-list (- m n))))
508                          (t list))))
509             (return (nconc (frob required nr nreq)
510                            (frob optional no nopt)
511                            values)))))
512