7975e13dfa2b330a8ff7bef781a241122db6ceef
[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     (dolist (m applicable-methods)
132       (let ((qualifiers (method-qualifiers m)))
133         (flet ((lose (method why)
134                  (invalid-method-error
135                    method
136                    "The method ~S ~A.~%~
137                     The method combination type ~S was defined with the~%~
138                     short form of DEFINE-METHOD-COMBINATION and so requires~%~
139                     all methods have either the single qualifier ~S or the~%~
140                     single qualifier :AROUND."
141                    method why type type)))
142           (cond ((null qualifiers)
143                  (lose m "has no qualifiers"))
144                 ((cdr qualifiers)
145                  (lose m "has more than one qualifier"))
146                 ((eq (car qualifiers) :around)
147                  (push m around))
148                 ((eq (car qualifiers) type)
149                  (push m primary))
150                 (t
151                  (lose m "has an illegal qualifier"))))))
152     (setq around (nreverse around))
153     (ecase order
154       (:most-specific-last) ; nothing to be done, already in correct order
155       (:most-specific-first
156        (setq primary (nreverse primary))))
157     (let ((main-method
158             (if (and (null (cdr primary))
159                      (not (null ioa)))
160                 `(call-method ,(car primary) ())
161                 `(,operator ,@(mapcar (lambda (m) `(call-method ,m ()))
162                                       primary)))))
163       (cond ((null primary)
164              `(error "No ~S methods for the generic function ~S."
165                      ',type ',generic-function))
166             ((null around) main-method)
167             (t
168              `(call-method ,(car around)
169                            (,@(cdr around) (make-method ,main-method))))))))
170 \f
171 ;;;; long method combinations
172
173 (defun expand-long-defcombin (form)
174   (let ((type (cadr form))
175         (lambda-list (caddr form))
176         (method-group-specifiers (cadddr form))
177         (body (cddddr form))
178         (args-option ())
179         (gf-var nil))
180     (when (and (consp (car body)) (eq (caar body) :arguments))
181       (setq args-option (cdr (pop body))))
182     (when (and (consp (car body)) (eq (caar body) :generic-function))
183       (setq gf-var (cadr (pop body))))
184     (multiple-value-bind (documentation function)
185         (make-long-method-combination-function
186           type lambda-list method-group-specifiers args-option gf-var
187           body)
188       `(load-long-defcombin ',type ',documentation #',function
189                             ',args-option))))
190
191 (defvar *long-method-combination-functions* (make-hash-table :test 'eq))
192
193 (defun load-long-defcombin (type doc function args-lambda-list)
194   (let* ((specializers
195            (list (find-class 'generic-function)
196                  (intern-eql-specializer type)
197                  *the-class-t*))
198          (old-method
199            (get-method #'find-method-combination () specializers nil))
200          (new-method
201            (make-instance 'standard-method
202              :qualifiers ()
203              :specializers specializers
204              :lambda-list '(generic-function type options)
205              :function (lambda (args nms &rest cm-args)
206                          (declare (ignore nms cm-args))
207                          (apply
208                           (lambda (generic-function type options)
209                             (declare (ignore generic-function))
210                             (make-instance 'long-method-combination
211                                            :type type
212                                            :options options
213                                            :args-lambda-list args-lambda-list
214                                            :documentation doc))
215                           args))
216              :definition-source `((define-method-combination ,type)
217                                   ,*load-pathname*))))
218     (setf (gethash type *long-method-combination-functions*) function)
219     (when old-method (remove-method #'find-method-combination old-method))
220     (add-method #'find-method-combination new-method)
221     type))
222
223 (defmethod compute-effective-method ((generic-function generic-function)
224                                      (combin long-method-combination)
225                                      applicable-methods)
226   (funcall (gethash (method-combination-type combin)
227                     *long-method-combination-functions*)
228            generic-function
229            combin
230            applicable-methods))
231
232 (defun make-long-method-combination-function
233        (type ll method-group-specifiers args-option gf-var body)
234   (declare (ignore type))
235   (multiple-value-bind (real-body declarations documentation)
236       ;; (Note that PARSE-BODY ignores its second arg ENVIRONMENT.)
237       (parse-body body nil)
238
239     (let ((wrapped-body
240             (wrap-method-group-specifier-bindings method-group-specifiers
241                                                   declarations
242                                                   real-body)))
243       (when gf-var
244         (push `(,gf-var .generic-function.) (cadr wrapped-body)))
245
246       (when args-option
247         (setq wrapped-body (deal-with-args-option wrapped-body args-option)))
248
249       (when ll
250         (setq wrapped-body
251               `(apply #'(lambda ,ll ,wrapped-body)
252                       (method-combination-options .method-combination.))))
253
254       (values
255         documentation
256         `(lambda (.generic-function. .method-combination. .applicable-methods.)
257            (declare (ignorable .generic-function.
258                      .method-combination. .applicable-methods.))
259            (block .long-method-combination-function. ,wrapped-body))))))
260
261 ;; parse-method-group-specifiers parse the method-group-specifiers
262
263 (defun wrap-method-group-specifier-bindings
264        (method-group-specifiers declarations real-body)
265   (let (names
266         specializer-caches
267         cond-clauses
268         required-checks
269         order-cleanups)
270       (dolist (method-group-specifier method-group-specifiers)
271         (multiple-value-bind (name tests description order required)
272             (parse-method-group-specifier method-group-specifier)
273           (declare (ignore description))
274           (let ((specializer-cache (gensym)))
275             (push name names)
276             (push specializer-cache specializer-caches)
277             (push `((or ,@tests)
278                     (if (and (equal ,specializer-cache .specializers.)
279                              (not (null .specializers.)))
280                         (return-from .long-method-combination-function.
281                           '(error "More than one method of type ~S ~
282                                       with the same specializers."
283                                    ',name))
284                         (setq ,specializer-cache .specializers.))
285                     (push .method. ,name))
286                   cond-clauses)
287             (when required
288               (push `(when (null ,name)
289                          (return-from .long-method-combination-function.
290                            '(error "No ~S methods." ',name)))
291                       required-checks))
292             (loop (unless (and (constantp order)
293                                (neq order (setq order (eval order))))
294                     (return t)))
295             (push (cond ((eq order :most-specific-first)
296                            `(setq ,name (nreverse ,name)))
297                           ((eq order :most-specific-last) ())
298                           (t
299                            `(ecase ,order
300                               (:most-specific-first
301                                 (setq ,name (nreverse ,name)))
302                               (:most-specific-last))))
303                     order-cleanups))))
304    `(let (,@(nreverse names) ,@(nreverse specializer-caches))
305       ,@declarations
306       (dolist (.method. .applicable-methods.)
307         (let ((.qualifiers. (method-qualifiers .method.))
308               (.specializers. (method-specializers .method.)))
309           (declare (ignorable .qualifiers. .specializers.))
310           (cond ,@(nreverse cond-clauses))))
311       ,@(nreverse required-checks)
312       ,@(nreverse order-cleanups)
313       ,@real-body)))
314
315 (defun parse-method-group-specifier (method-group-specifier)
316   ;;(declare (values name tests description order required))
317   (let* ((name (pop method-group-specifier))
318          (patterns ())
319          (tests
320            (let (collect)
321              (block collect-tests
322                (loop
323                  (if (or (null method-group-specifier)
324                          (memq (car method-group-specifier)
325                                '(:description :order :required)))
326                      (return-from collect-tests t)
327                      (let ((pattern (pop method-group-specifier)))
328                        (push pattern patterns)
329                        (push (parse-qualifier-pattern name pattern)
330                              collect)))))
331              (nreverse collect))))
332     (values name
333             tests
334             (getf method-group-specifier :description
335                   (make-default-method-group-description patterns))
336             (getf method-group-specifier :order :most-specific-first)
337             (getf method-group-specifier :required nil))))
338
339 (defun parse-qualifier-pattern (name pattern)
340   (cond ((eq pattern '()) `(null .qualifiers.))
341         ((eq pattern '*) t)
342         ((symbolp pattern) `(,pattern .qualifiers.))
343         ((listp pattern) `(qualifier-check-runtime ',pattern .qualifiers.))
344         (t (error "In the method group specifier ~S,~%~
345                    ~S isn't a valid qualifier pattern."
346                   name pattern))))
347
348 (defun qualifier-check-runtime (pattern qualifiers)
349   (loop (cond ((and (null pattern) (null qualifiers))
350                (return t))
351               ((eq pattern '*) (return t))
352               ((and pattern qualifiers (eq (car pattern) (car qualifiers)))
353                (pop pattern)
354                (pop qualifiers))
355               (t (return nil)))))
356
357 (defun make-default-method-group-description (patterns)
358   (if (cdr patterns)
359       (format nil
360               "methods matching one of the patterns: ~{~S, ~} ~S"
361               (butlast patterns) (car (last patterns)))
362       (format nil
363               "methods matching the pattern: ~S"
364               (car patterns))))
365
366 ;;; This baby is a complete mess. I can't believe we put it in this
367 ;;; way. No doubt this is a large part of what drives MLY crazy.
368 ;;;
369 ;;; At runtime (when the effective-method is run), we bind an intercept
370 ;;; lambda-list to the arguments to the generic function.
371 ;;;
372 ;;; At compute-effective-method time, the symbols in the :arguments
373 ;;; option are bound to the symbols in the intercept lambda list.
374 (defun deal-with-args-option (wrapped-body args-lambda-list)
375   (let ((intercept-rebindings
376          (let (rebindings)
377            (dolist (arg args-lambda-list (nreverse rebindings))
378              (unless (member arg lambda-list-keywords)
379                (push `(,arg ',arg) rebindings)))))
380         (nreq 0)
381         (nopt 0)
382         (whole nil))
383     ;; Count the number of required and optional parameters in
384     ;; ARGS-LAMBDA-LIST into NREQ and NOPT, and set WHOLE to the
385     ;; name of a &WHOLE parameter, if any.
386     (when (member '&whole (rest args-lambda-list))
387       (error 'simple-program-error
388              :format-control "~@<The value of the :ARGUMENTS option of~
389                 DEFINE-METHOD-COMBINATION is~2I~_~S,~I~_but &WHOLE may~
390                 only appear first in the lambda list.~:>"
391              :format-arguments (list args-lambda-list)))
392     (loop with state = 'required
393           for arg in args-lambda-list do
394             (if (memq arg lambda-list-keywords)
395                 (setq state arg)
396                 (case state
397                   (required (incf nreq))
398                   (&optional (incf nopt))
399                   (&whole (setq whole arg state 'required)))))
400     ;; This assumes that the head of WRAPPED-BODY is a let, and it
401     ;; injects let-bindings of the form (ARG 'SYM) for all variables
402     ;; of the argument-lambda-list; SYM is a gensym.
403     (aver (memq (first wrapped-body) '(let let*)))
404     (setf (second wrapped-body)
405           (append intercept-rebindings (second wrapped-body)))
406     ;; Be sure to fill out the args lambda list so that it can be too
407     ;; short if it wants to.
408     (unless (or (memq '&rest args-lambda-list)
409                 (memq '&allow-other-keys args-lambda-list))
410       (let ((aux (memq '&aux args-lambda-list)))
411         (setq args-lambda-list
412               (append (ldiff args-lambda-list aux)
413                       (if (memq '&key args-lambda-list)
414                           '(&allow-other-keys)
415                           '(&rest .ignore.))
416                       aux))))
417     ;; .GENERIC-FUNCTION. is bound to the generic function in the
418     ;; method combination function, and .GF-ARGS* is bound to the
419     ;; generic function arguments in effective method functions
420     ;; created for generic functions having a method combination that
421     ;; uses :ARGUMENTS.
422     ;;
423     ;; The DESTRUCTURING-BIND binds the parameters of the
424     ;; ARGS-LAMBDA-LIST to actual generic function arguments.  Because
425     ;; ARGS-LAMBDA-LIST may be shorter or longer than the generic
426     ;; function's lambda list, which is only known at run time, this
427     ;; destructuring has to be done on a slighly modified list of
428     ;; actual arguments, from which values might be stripped or added.
429     ;;
430     ;; Using one of the variable names in the body inserts a symbol
431     ;; into the effective method, and running the effective method
432     ;; produces the value of actual argument that is bound to the
433     ;; symbol.
434     `(let ((inner-result. ,wrapped-body)
435            (gf-lambda-list (generic-function-lambda-list .generic-function.)))
436        `(destructuring-bind ,',args-lambda-list
437             (frob-combined-method-args
438              .gf-args. ',gf-lambda-list
439              ,',nreq ,',nopt)
440           ,,(when (memq '.ignore. args-lambda-list)
441               ''(declare (ignore .ignore.)))
442           ;; If there is a &WHOLE in the args-lambda-list, let
443           ;; it result in the actual arguments of the generic-function
444           ;; not the frobbed list.
445           ,,(when whole
446               ``(setq ,',whole .gf-args.))
447           ,inner-result.))))
448
449 ;;; Partition VALUES into three sections: required, optional, and the
450 ;;; rest, according to required, optional, and other parameters in
451 ;;; LAMBDA-LIST.  Make the required and optional sections NREQ and
452 ;;; NOPT elements long by discarding values or adding NILs.  Value is
453 ;;; the concatenated list of required and optional sections, and what
454 ;;; is left as rest from VALUES.
455 (defun frob-combined-method-args (values lambda-list nreq nopt)
456   (loop with section = 'required
457         for arg in lambda-list
458         if (memq arg lambda-list-keywords) do
459           (setq section arg)
460           (unless (eq section '&optional)
461             (loop-finish))
462         else if (eq section 'required)
463           count t into nr
464           and collect (pop values) into required
465         else if (eq section '&optional)
466           count t into no
467           and collect (pop values) into optional
468         finally
469           (flet ((frob (list n m)
470                    (cond ((> n m) (butlast list (- n m)))
471                          ((< n m) (nconc list (make-list (- m n))))
472                          (t list))))
473             (return (nconc (frob required nr nreq)
474                            (frob optional no nopt)
475                            values)))))