chiark / gitweb /
src/method-impl.lisp: Typo in docstring.
[sod] / src / method-impl.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; Method combination implementation
4 ;;;
5 ;;; (c) 2009 Straylight/Edgeware
6 ;;;
7
8 ;;;----- Licensing notice ---------------------------------------------------
9 ;;;
10 ;;; This file is part of the Sensble Object Design, an object system for C.
11 ;;;
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;;
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 (cl:in-package #:sod)
27
28 ;;;--------------------------------------------------------------------------
29 ;;; Message classes.
30
31 (export 'basic-message)
32 (defclass basic-message (sod-message)
33   ((argument-tail :type list :reader sod-message-argument-tail)
34    (no-varargs-tail :type list :reader sod-message-no-varargs-tail))
35   (:documentation
36    "Base class for built-in message classes.
37
38    Provides the basic functionality for the built-in method combinations.
39    This is a separate class so that `special effect' messages can avoid
40    inheriting its default behaviour.
41
42    The function type protocol is implemented on `basic-message' using slot
43    reader methods.  The actual values are computed on demand in methods
44    defined on `slot-unbound'."))
45
46 (defmethod slot-unbound (class
47                          (message basic-message)
48                          (slot-name (eql 'argument-tail)))
49   (declare (ignore class))
50   (let ((seq 0))
51     (setf (slot-value message 'argument-tail)
52           (mapcar (lambda (arg)
53                     (if (or (eq arg :ellipsis) (argument-name arg)) arg
54                         (make-argument (make-instance 'temporary-argument
55                                                       :tag (prog1 seq
56                                                              (incf seq)))
57                                        (argument-type arg))))
58                   (c-function-arguments (sod-message-type message))))))
59
60 (defmethod slot-unbound (class
61                          (message basic-message)
62                          (slot-name (eql 'no-varargs-tail)))
63   (declare (ignore class))
64   (setf (slot-value message 'no-varargs-tail)
65         (mapcar (lambda (arg)
66                   (if (eq arg :ellipsis)
67                       (make-argument *sod-ap* (c-type va-list))
68                       arg))
69                 (sod-message-argument-tail message))))
70
71 (defmethod sod-message-method-class
72     ((message basic-message) (class sod-class) pset)
73   (let ((role (get-property pset :role :keyword nil)))
74     (case role
75       ((:before :after) 'daemon-direct-method)
76       (:around 'delegating-direct-method)
77       ((nil) (error "How odd: a primary method slipped through the net"))
78       (t (error "Unknown method role ~A" role)))))
79
80 (export 'simple-message)
81 (defclass simple-message (basic-message)
82   ()
83   (:documentation
84    "Base class for messages with `simple' method combinations.
85
86    A simple method combination is one which has only one method role other
87    than the `before', `after' and `around' methods provided by
88    `basic-message'.  We call these `primary' methods, and the programmer
89    designates them by not specifying an explicit role.
90
91    If the programmer doesn't define any primary methods then the effective
92    method is null -- i.e., the method entry pointer shows up as a null
93    pointer."))
94
95 (defmethod sod-message-method-class
96     ((message simple-message) (class sod-class) pset)
97   (if (get-property pset :role :keyword nil)
98       (call-next-method)
99       (primary-method-class message)))
100
101 (defmethod primary-method-class ((message simple-message))
102   'basic-direct-method)
103
104 ;;;--------------------------------------------------------------------------
105 ;;; Direct method classes.
106
107 (export 'basic-direct-method)
108 (defclass basic-direct-method (sod-method)
109   ((role :initarg :role :type symbol :reader sod-method-role)
110    (function-type :type c-function-type :reader sod-method-function-type))
111   (:documentation
112    "Base class for built-in direct method classes.
113
114    Provides the basic functionality for the built-in direct-method classes.
115    This is a separate class so that `special effect' methods can avoid
116    inheriting its default behaviour and slots.
117
118    A basic method can be assigned a `role', which may be set either as an
119    initarg or using the `:role' property.  Roles are used for method
120    categorization.
121
122    The function type protocol is implemented on `basic-direct-method' using
123    slot reader methods.  The actual values are computed on demand in methods
124    defined on `slot-unbound'."))
125
126 (defmethod shared-initialize :after
127     ((method basic-direct-method) slot-names &key pset)
128   (declare (ignore slot-names))
129   (default-slot (method 'role) (get-property pset :role :keyword nil)))
130
131 (defmethod slot-unbound
132     (class (method basic-direct-method) (slot-name (eql 'function-type)))
133   (declare (ignore class))
134   (let ((type (sod-method-type method)))
135     (setf (slot-value method 'function-type)
136           (c-type (fun (lisp (c-type-subtype type))
137                        ("me" (* (class (sod-method-class method))))
138                        . (c-function-arguments type))))))
139
140 (defmethod sod-method-function-name ((method basic-direct-method))
141   (with-slots (class role message) method
142     (format nil "~A__~@[~(~A~)_~]method_~A__~A" class role
143             (sod-class-nickname (sod-message-class message))
144             (sod-message-name message))))
145
146 (export 'daemon-direct-method)
147 (defclass daemon-direct-method (basic-direct-method)
148   ()
149   (:documentation
150    "A daemon direct method is invoked for side effects and cannot override.
151
152    This is the direct method class for `before' and `after' methods, which
153    cannot choose to override the remaining methods and are not involved in
154    the computation of the final result.
155
156    In C terms, a daemon method must return `void', and is not passed a
157    `next_method' pointer."))
158
159 (defmethod check-method-type ((method daemon-direct-method)
160                               (message sod-message)
161                               (type c-function-type))
162   (with-slots ((msgtype type)) message
163     (unless (c-type-equal-p (c-type-subtype type) (c-type void))
164       (error "Method return type ~A must be `void'" (c-type-subtype type)))
165     (unless (argument-lists-compatible-p (c-function-arguments msgtype)
166                                          (c-function-arguments type))
167       (error "Method arguments ~A don't match message ~A" type msgtype))))
168
169 (export 'delegating-direct-method)
170 (defclass delegating-direct-method (basic-direct-method)
171   ((next-method-type :type c-function-type
172                      :reader sod-method-next-method-type))
173   (:documentation
174    "A delegating direct method can choose to override other methods.
175
176    This is the direct method class for `around' and standard-method-
177    combination primary methods, which are given the choice of computing the
178    entire method's result or delegating to (usually) less-specific methods.
179
180    In C terms, a delegating method is passed a `next_method' pointer so that
181    it can delegate part of its behaviour.  (A delegating direct method for a
182    varargs message is also given an additional `va_list' argument,
183    conventionally named `sod__ap_master', which it is expected to pass on to
184    its `next_method' function if necessary.)
185
186    The function type protocol is implemented on `delegating-direct-method'
187    using slot reader methods.  The actual values are computed on demand in
188    methods defined on `slot-unbound'."))
189
190 (defmethod slot-unbound (class
191                          (method delegating-direct-method)
192                          (slot-name (eql 'next-method-type)))
193   (declare (ignore class))
194   (let* ((message (sod-method-message method))
195          (type (sod-message-type message)))
196     (setf (slot-value method 'next-method-type)
197           (c-type (fun (lisp (c-type-subtype type))
198                        ("me" (* (class (sod-method-class method))))
199                        .
200                        (c-function-arguments type))))))
201
202 (defmethod slot-unbound (class
203                          (method delegating-direct-method)
204                          (slot-name (eql 'function-type)))
205   (declare (ignore class))
206   (let* ((message (sod-method-message method))
207          (type (sod-method-type method))
208          (method-args (c-function-arguments type)))
209     (setf (slot-value method 'function-type)
210           (c-type (fun (lisp (c-type-subtype type))
211                        ("me" (* (class (sod-method-class method))))
212                        ("next_method" (* (lisp (commentify-function-type
213                                                 (sod-method-next-method-type
214                                                  method)))))
215                        .
216                        (if (varargs-message-p message)
217                            (cons (make-argument *sod-master-ap*
218                                                 (c-type va-list))
219                                  method-args)
220                            method-args))))))
221
222 ;;;--------------------------------------------------------------------------
223 ;;; Effective method classes.
224
225 (export 'basic-effective-method)
226 (defclass basic-effective-method (effective-method)
227   ((around-methods :initarg :around-methods :initform nil
228                    :type list :reader effective-method-around-methods)
229    (before-methods :initarg :before-methods :initform nil
230                    :type list :reader effective-method-before-methods)
231    (after-methods :initarg :after-methods :initform nil
232                   :type list :reader effective-method-after-methods)
233    (basic-argument-names :type list
234                          :reader effective-method-basic-argument-names)
235    (functions :type list :reader effective-method-functions))
236   (:documentation
237    "Base class for built-in effective method classes.
238
239    This class maintains lists of the applicable `before', `after' and
240    `around' methods and provides behaviour for invoking these methods
241    correctly.
242
243    The argument names protocol is implemented on `basic-effective-method'
244    using a slot reader method.  The actual values are computed on demand in
245    methods defined on `slot-unbound'."))
246
247 (defmethod slot-unbound (class
248                          (method basic-effective-method)
249                          (slot-name (eql 'basic-argument-names)))
250   (declare (ignore class))
251   (let ((message (effective-method-message method)))
252     (setf (slot-value method 'basic-argument-names)
253           (subst *sod-master-ap* *sod-ap*
254                  (mapcar #'argument-name
255                          (sod-message-no-varargs-tail message))))))
256
257 (defmethod effective-method-function-name ((method effective-method))
258   (let* ((class (effective-method-class method))
259          (message (effective-method-message method))
260          (message-class (sod-message-class message)))
261     (format nil "~A__emethod_~A__~A"
262             class
263             (sod-class-nickname message-class)
264             (sod-message-name message))))
265
266 (defmethod slot-unbound
267     (class (method basic-effective-method) (slot-name (eql 'functions)))
268   (declare (ignore class))
269   (setf (slot-value method 'functions)
270         (compute-method-entry-functions method)))
271
272 (export 'simple-effective-method)
273 (defclass simple-effective-method (basic-effective-method)
274   ((primary-methods :initarg :primary-methods :initform nil
275                     :type list :reader effective-method-primary-methods))
276   (:documentation
277    "Effective method counterpart to `simple-message'."))
278
279 (defmethod shared-initialize :after
280     ((method simple-effective-method) slot-names &key direct-methods)
281   (declare (ignore slot-names))
282   (categorize (method direct-methods :bind ((role (sod-method-role method))))
283       ((primary (null role))
284        (before (eq role :before))
285        (after (eq role :after))
286        (around (eq role :around)))
287     (with-slots (primary-methods before-methods after-methods around-methods)
288         method
289       (setf primary-methods primary
290             before-methods before
291             after-methods (reverse after)
292             around-methods around))))
293
294 ;;;--------------------------------------------------------------------------
295 ;;; Code generation.
296
297 (defmethod shared-initialize :after
298     ((codegen method-codegen) slot-names &key)
299   (declare (ignore slot-names))
300   (with-slots (message target) codegen
301     (setf target
302           (if (eq (c-type-subtype (sod-message-type message)) (c-type void))
303               :void
304               :return))))
305
306 ;;;--------------------------------------------------------------------------
307 ;;; Invoking direct methods.
308
309 (export 'basic-effective-method-body)
310 (defun basic-effective-method-body (codegen target method body)
311   "Build the common method-invocation structure.
312
313    Writes to CODEGEN some basic method-invocation instructions.  It invokes
314    the `around' methods, from most- to least-specific.  If they all delegate,
315    then the `before' methods are run, most-specific first; next, the
316    instructions generated by BODY (invoked with a target argument); then, the
317    `after' methods are run, least-specific first; and, finally, the value
318    delivered by the BODY is returned to the `around' methods.  The result
319    returned by the outermost `around' method -- or, if there are none,
320    delivered by the BODY -- is finally delivered to the TARGET."
321
322   (with-slots (message class before-methods after-methods around-methods)
323       method
324     (let* ((message-type (sod-message-type message))
325            (return-type (c-type-subtype message-type))
326            (voidp (eq return-type (c-type void)))
327            (basic-tail (effective-method-basic-argument-names method)))
328       (flet ((method-kernel (target)
329                (dolist (before before-methods)
330                  (invoke-method codegen :void basic-tail before))
331                (if (or voidp (null after-methods))
332                    (funcall body target)
333                    (convert-stmts codegen target return-type
334                                   (lambda (target)
335                                     (funcall body target)
336                                     (dolist (after (reverse after-methods))
337                                       (invoke-method codegen :void
338                                                      after basic-tail)))))))
339         (invoke-delegation-chain codegen target basic-tail
340                                  around-methods #'method-kernel)))))
341
342 ;;;--------------------------------------------------------------------------
343 ;;; Method entry points.
344
345 (defparameter *method-entry-inline-threshold* 200
346   "Threshold below which effective method bodies are inlined into entries.
347
348    After the effective method body has been computed, we calculate its
349    metric, multiply by the number of entries we need to generate, and compare
350    it with this threshold.  If the metric is below the threshold then we
351    fold the method body into the entry functions; otherwise we split the
352    effective method out into its own function.")
353
354 (defmethod method-entry-function-name
355     ((method effective-method) (chain-head sod-class))
356   (let* ((class (effective-method-class method))
357          (message (effective-method-message method))
358          (message-class (sod-message-class message)))
359     (if (or (not (slot-boundp method 'functions))
360             (slot-value method 'functions))
361         (format nil "~A__mentry_~A__~A__chain_~A"
362                 class
363                 (sod-class-nickname message-class)
364                 (sod-message-name message)
365                 (sod-class-nickname chain-head))
366         0)))
367
368 (defmethod method-entry-function-type ((entry method-entry))
369   (let* ((method (method-entry-effective-method entry))
370          (message (effective-method-message method))
371          (type (sod-message-type message)))
372     (c-type (fun (lisp (c-type-subtype type))
373                  ("me" (* (class (method-entry-chain-tail entry))))
374                  . (sod-message-argument-tail message)))))
375
376 (defmethod make-method-entry ((method basic-effective-method)
377                               (chain-head sod-class) (chain-tail sod-class))
378   (make-instance 'method-entry
379                  :method method
380                  :chain-head chain-head
381                  :chain-tail chain-tail))
382
383 (defmethod compute-method-entry-functions ((method basic-effective-method))
384
385   ;; OK, there's quite a lot of this, so hold tight.
386   ;;
387   ;; The first thing we need to do is find all of the related objects.  This
388   ;; is a bit verbose but fairly straightforward.
389   ;;
390   ;; Next, we generate the effective method body -- using `compute-effective-
391   ;; method-body' of all things.  This gives us the declarations and body for
392   ;; an effective method function, but we don't have an actual function yet.
393   ;;
394   ;; Now we look at the chains which are actually going to need a method
395   ;; entry: only those chains whose tail (most specific) class is a
396   ;; superclass of the class which defined the message need an entry.  We
397   ;; build a list of these tail classes.
398   ;;
399   ;; Having done this, we decide whether it's better to generate a standalone
400   ;; effective-method function and call it from each of the method entries,
401   ;; or to inline the effective method body into each of the entries.
402   ;;
403   ;; Most of the complexity here comes from (a) dealing with the two
404   ;; different strategies for constructing method entry functions and (b)
405   ;; (unsurprisingly) the mess involved with dealing with varargs messages.
406
407   (let* ((message (effective-method-message method))
408          (class (effective-method-class method))
409          (message-class (sod-message-class message))
410          (return-type (c-type-subtype (sod-message-type message)))
411          (codegen (make-instance 'method-codegen
412                                  :message message
413                                  :class class
414                                  :method method))
415
416          ;; Effective method function details.
417          (emf-name (effective-method-function-name method))
418          (ilayout-type (c-type (* (struct (ilayout-struct-tag class)))))
419          (emf-arg-tail (mapcar (lambda (arg)
420                                  (if (eq (argument-name arg) *sod-ap*)
421                                      (make-argument *sod-master-ap*
422                                                     (c-type va-list))
423                                      arg))
424                                (sod-message-no-varargs-tail message)))
425          (emf-type (c-type (fun (lisp return-type)
426                                 ("sod__obj" (lisp ilayout-type))
427                                 . (sod-message-no-varargs-tail message))))
428
429          ;; Method entry details.
430          (chain-tails (remove-if-not (lambda (super)
431                                        (sod-subclass-p super message-class))
432                                      (mapcar #'car
433                                              (sod-class-chains class))))
434          (n-entries (length chain-tails))
435          (entry-args (sod-message-argument-tail message))
436          (parm-n (do ((prev "me" (car args))
437                       (args entry-args (cdr args)))
438                      ((endp args) nil)
439                    (when (eq (car args) :ellipsis)
440                      (return prev))))
441          (entry-target (codegen-target codegen)))
442
443     (flet ((setup-entry (tail)
444              (let ((head (sod-class-chain-head tail)))
445                (codegen-push codegen)
446                (ensure-var codegen "sod__obj" ilayout-type
447                            (make-convert-to-ilayout-inst class
448                                                          head "me"))))
449            (varargs-prologue ()
450              (ensure-var codegen *sod-master-ap* (c-type va-list))
451              (emit-inst codegen
452                         (make-va-start-inst *sod-master-ap* parm-n)))
453            (varargs-epilogue ()
454              (emit-inst codegen (make-va-end-inst *sod-master-ap*)))
455            (finish-entry (tail)
456              (let* ((head (sod-class-chain-head tail))
457                     (name (method-entry-function-name method head))
458                     (type (c-type (fun (lisp return-type)
459                                        ("me" (* (class tail)))
460                                        . entry-args))))
461                (codegen-pop-function codegen name type))))
462
463       ;; Generate the method body.  We'll work out what to do with it later.
464       (codegen-push codegen)
465       (let* ((result (if (eq return-type (c-type void)) nil
466                          (temporary-var codegen return-type)))
467              (emf-target (or result :void)))
468         (compute-effective-method-body method codegen emf-target)
469         (multiple-value-bind (vars insts) (codegen-pop codegen)
470           (cond ((or (= n-entries 1)
471                      (<= (* n-entries (reduce #'+ insts :key #'inst-metric))
472                          *method-entry-inline-threshold*))
473
474                  ;; The effective method body is simple -- or there's only
475                  ;; one of them.  We'll inline the method body into the entry
476                  ;; functions.
477                  (dolist (tail chain-tails)
478                    (setup-entry tail)
479                    (dolist (var vars)
480                      (if (typep var 'var-inst)
481                          (ensure-var codegen (inst-name var)
482                                      (inst-type var) (inst-init var))
483                          (emit-decl codegen var)))
484                    (when parm-n (varargs-prologue))
485                    (emit-insts codegen insts)
486                    (when parm-n (varargs-epilogue))
487                    (deliver-expr codegen entry-target result)
488                    (finish-entry tail)))
489
490                 (t
491
492                  ;; The effective method body is complicated and we'd need
493                  ;; more than one copy.  We'll generate an effective method
494                  ;; function and call it a lot.
495                  (codegen-build-function codegen emf-name emf-type vars
496                   (nconc insts (and result
497                                     (list (make-return-inst result)))))
498
499                  (let ((call (make-call-inst emf-name
500                               (cons "sod__obj" (mapcar #'argument-name
501                                                        emf-arg-tail)))))
502                    (dolist (tail chain-tails)
503                      (setup-entry tail)
504                      (cond (parm-n
505                             (varargs-prologue)
506                             (convert-stmts codegen entry-target return-type
507                                            (lambda (target)
508                                              (deliver-expr codegen
509                                                            target call)
510                                              (varargs-epilogue))))
511                            (t
512                             (deliver-expr codegen entry-target call)))
513                      (finish-entry tail)))))))
514
515       (codegen-functions codegen))))
516
517 (defmethod compute-method-entry-functions
518     ((method simple-effective-method))
519   (if (effective-method-primary-methods method)
520       (call-next-method)
521       nil))
522
523 (defmethod compute-effective-method-body
524     ((method simple-effective-method) codegen target)
525   (with-slots (message basic-argument-names primary-methods) method
526     (basic-effective-method-body codegen target method
527                                  (lambda (target)
528                                    (simple-method-body method
529                                                        codegen
530                                                        target)))))
531
532 ;;;--------------------------------------------------------------------------
533 ;;; Standard method combination.
534
535 (export 'standard-message)
536 (defclass standard-message (simple-message)
537   ()
538   (:documentation
539    "Message class for standard method combinations.
540
541    Standard method combination is a simple method combination where the
542    primary methods are invoked as a delegation chain, from most- to
543    least-specific."))
544
545 (export 'standard-effective-method)
546 (defclass standard-effective-method (simple-effective-method) ()
547   (:documentation "Effective method counterpart to `standard-message'."))
548
549 (defmethod primary-method-class ((message standard-message))
550   'delegating-direct-method)
551
552 (defmethod message-effective-method-class ((message standard-message))
553   'standard-effective-method)
554
555 (defmethod simple-method-body
556     ((method standard-effective-method) codegen target)
557   (invoke-delegation-chain codegen
558                            target
559                            (effective-method-basic-argument-names method)
560                            (effective-method-primary-methods method)
561                            nil))
562
563 ;;;----- That's all, folks --------------------------------------------------