Christophe Weblog Wiki Code Publications Music
59b1bd16fb0a6f2be7fccca6c9fdb8baf2941bb8
[paper-els-specializers.git] / els-specializers.org
1 #+TITLE: Generalizers: New Metaobjects for Generalized Dispatch
2 #+AUTHOR: Christophe Rhodes, Jan Moringen, David Lichteblau
3 #+OPTIONS: toc:nil
4
5 #+LaTeX_HEADER: \usepackage[margin=1in]{geometry}
6
7 #+begin_abstract
8 1. This paper introduces a new metaobject, the generalizer, which
9    complements the existing specializer metaobject.
10 2. With the help of examples, we show that this metaobject allows for
11    the efficient implementation of complex non-class-based dispatch
12    within the framework of existing metaobject protocols
13 3. We present the generalizer protocol, implemented within the SBCL
14    implementation of Common Lisp
15 4. In combination with previous work, this produces a fully-functional
16    extension of the existing mechanism for method selection and
17    effective method computation, including support for standard and
18    user-defined method combination independent from method selection.
19 #+end_abstract
20
21 * Introduction
22   The revisions to the original Common Lisp language \cite{CLtL1}
23   included the detailed specification of an object system, known as
24   the Common Lisp Object System (CLOS), which was eventually
25   standardized as part of the ANSI Common Lisp standard \cite{CLtS}.
26   The object system as presented to the standardization committee was
27   formed of three parts, the first two of which covered XXX [what?]
28   and were incorporated into the final standard, and the third,
29   covering a Metaobject Protocol (MOP) for CLOS, was not.
30
31   Nevertheless, the CLOS MOP has proven to be a robust design, and
32   while many implementations have derived their implementations of
33   CLOS from either the Closette illustrative implementation in
34   \cite{AMOP}, or the Portable Common Loops implementation of CLOS
35   from Xerox Parc, there have been from-scratch reimplementations of
36   CLOS (in at least CLISP; check for others -- ABCL?  Lisp500?!)
37   incorporating the majority of the Metaobject Protocol as described.
38
39   Although it has stood the test of time, the MOP is neither without
40   issues (e.g. M-M-L considered harmful; slot-definition initargs
41   issue) nor a complete framework for the metaprogrammer to implement
42   all conceivable variations of object-oriented behaviour; indeed,
43   while metaprogramming offers some possibilities for customization of
44   the object system behaviour, those possibilities cannot extend
45   arbitrarily in all directions.  There is still an expectation that
46   functionality is implemented with methods on generic functions,
47   acting on objects with slots.  [XXX find Paepke picture here?  Not
48   Paepke; AMOP?].  XXX include typical examples of MOP: object
49   persistence; maybe ref. Kizcales "MOPs: why we want them and what
50   else they can do"? (Fig. 2 in that is good) ORMs; sparse slots.
51   jmoringe:
52   + introspection, e.g. documentation generation
53   + programmatic construction of classes and generic functions
54     e.g. for IDL compilers, model transformations
55
56   One area of functionality where there is scope for customization by
57   the metaprogrammer is in the mechanics and semantics of method
58   applicability and dispatch.  While in principle AMOP allows
59   customization of dispatch in various different ways (the
60   metaprogrammer can define methods on protocol functions such as
61   =compute-applicable-methods=,
62   =compute-applicable-methods-using-classes=), for example, in
63   practice implementation support for this was weak until relatively
64   recently (ref. closer, also check how ContextL and filtered dispatch
65   are implemented).
66   jmoringe: filtered dispatch uses a custom method combination, i
67   think
68
69   Another potential mechanism for customizing dispatch is implicit in
70   the class structure defined by AMOP: standard specializer objects
71   (instances of =class= and =eql-specializer=) are generalized
72   instances of the =specializer= protocol class, and in principle
73   there are no restrictions on the metaprogrammer constructing
74   additional subclasses.  Previous work [Newton/Rhodes] has explored
75   the potential for customizing generic function dispatch using
76   extended specializers, but as of that work the metaprogrammer must
77   override the entirety of the generic function invocation protocol
78   (from =compute-discriminating-function= on down), leading to toy
79   implementations and duplicated effort.
80
81   This paper introduces a protocol for efficient and controlled
82   handling of arbitrary subclasses of =specializer=.  In particular,
83   it introduces the =generalizer= protocol class, which generalizes
84   (ahem) the return value of =class-of=, and allows the metaprogrammer
85   to hook into cacheing schemes to avoid needless recomputation of
86   effective methods for sufficiently similar generic function
87   arguments (See Figure\nbsp\ref{fig:dispatch}).
88
89   #+CAPTION:    Dispatch Comparison
90   #+LABEL:      fig:dispatch
91   #+ATTR_LATEX: width=0.9\linewidth float
92   [[file:figures/dispatch-comparison.pdf]]
93
94   The remaining sections in this paper can be read in any order.  We
95   give some motivating examples in section XX, including
96   reimplementations of examples from previous work, as well as
97   examples which are poorly supported by previous protocols.  We
98   describe the protocol itself in section YY, describing each protocol
99   function in detail and, where applicable, relating it to existing
100   protocol functions within the CLOS MOP.  We survey related work in
101   more detail in section ZZ, touching on work on customized dispatch
102   schemes in other environments.  Finally, we draw our conclusions
103   from this work, and indicate directions for further development, in
104   section WW; reading that section before the others indicates
105   substantial trust in the authors' work.
106 * Examples
107   In this section, we present a number of examples of dispatch
108   implemented using our protocol, which we describe in section YY.
109   For reasons of space, the metaprogram code examples in this section
110   do not include some of the necessary support code to run; complete
111   implementations of each of these cases are included in an appendix /
112   in the accompanying repository snapshot / at this location.
113
114   A note on terminology: we will attempt to distinguish between the
115   user of an individual case of generalized dispatch (the
116   “programmer”), the implementor of a particular case of generalized
117   dispatch (the “metaprogrammer”), and the authors as the designers
118   and implementors of our generalized dispatch protocol (the
119   “metametaprogammer”, or more likely ”we”).
120
121   - [ ] =cons-specializer= (can be done using filtered dispatch)
122   - [ ] factorial (like filtered dispatch)
123   - [ ] HTTP Accept header
124   - [ ] xpattern
125   - [ ] prototype/multimethod
126 ** car-of-cons
127    We start by presenting our original use case, performing
128    dispatching on the first element of lists.  Semantically, we allow
129    the programmer to specialize any argument of methods with a new
130    kind of specializer, =cons-specializer=, which is applicable if and
131    only if the corresponding object is a =cons= whose =car= is =eql=
132    to the symbol associated with the =cons-specializer=; these
133    specializers are more specific than the =cons= class, but less
134    specific than an =eql-specializer= on any given =cons=.
135
136    One motivation for the use of this specializer is in an extensible
137    code walker: a new special form can be handled simply by writing an
138    additional method on the walking generic function, seamlessly
139    interoperating with all existing methods.
140  
141    The programmer code using these specializers is unchanged from
142    \cite{Newton.Rhodes.2008}; the benefits of the protocol described
143    here are centered on performance: in an application such as walking
144    source code, we would expect to encounter special forms
145    (distinguished by particular atoms in the =car= position) multiple
146    times, and hence to dispatch to the same effective method
147    repeatedly.
148 #+begin_src lisp
149 (defclass cons-specializer (specializer)
150   ((%car :reader %car :initarg :car)))
151 (defclass cons-generalizer (generalizer)
152   ((%car :reader %car :initarg :car)))
153 (defmethod generalizer-of-using-class ((gf cons-generic-function) arg)
154   (typecase arg
155     ((cons symbol) (make-instance 'cons-generalizer :car (car arg)))
156     (t (call-next-method))))
157 (defmethod generalizer-equal-hash-key ((gf cons-generic-function)
158                                        (g cons-generalizer))
159   (%car g))
160 (defmethod specializer-accepts-generalizer-p ((gf cons-generic-function)
161                                               (s cons-specializer)
162                                               (g cons-generalizer))
163   (if (eql (%car s) (%car g))
164       (values t t)
165       (values nil t)))
166 (defmethod specializer-accepts-p ((s cons-specializer) o)
167   (and (consp o) (eql (car o) (%car s))))
168
169 #| less interesting methods elided: jmoringe: (un)parsing, specializer<?, more? |#
170
171 #| XXX insert motivating example from Newton/Rhodes here |#
172 #+end_src
173
174    TODO Timings: generalizer-enabled vs not vs case (car x) for CL special
175    operators.  Tweak so that the overhead of =case= is actually important.
176
177    Note that in this example there is no strict need for
178    =cons-specializer= and =cons-generalizer= to be distinct classes –
179    just as in the normal protocol involving
180    =compute-applicable-methods= and
181    =compute-applicable-methods-using-classes=, the specializer object
182    for mediating dispatch contains the same information as the object
183    representing the equivalence class of objects to which that
184    specializer is applicable: here it is the =car= of the =cons=
185    object; in the standard dispatch it is the =class= of the object.
186    This feature also characterizes those use cases where the
187    metaprogrammer could straightforwardly use filtered dispatch
188    \cite{Costanza.etal:2008} to implement their dispatch semantics.
189    We will see in section XX.x an example of a case where filtered
190    dispatch is incapable of efficiently implementing the dispatch, but
191    first we present our implementation of the motivating case from
192    \cite{Costanza.etal:2008}.
193 ** signum
194    Our second example of the implementation and use of generalized
195    specializers is a reimplementation of one of the examples in
196    \cite{Costanza.etal:2008}: specifically, the factorial function.
197    Here, we will perform dispatch based on the =signum= of the
198    argument, and again, at most one method with a =signum= specializer
199    will be appliable to any given argument, which makes the structure
200    of the specializer implementation very similar to the =cons=
201    specializers in the previous section.
202
203    We have chosen to compare signum values using \texttt{=}, which
204    means that a method with specializer =(signum 1)= will be
205    applicable to positive floating-point arguments (see the first
206    method on =specializer-accepts-generalizer-p= and the method on
207    =specializer=accepts-p= below).  This leads to one subtle
208    difference in behaviour compared to that of the =cons=
209    specializers: in the case of =signum= specializers, the /next/
210    method after any =signum= specializer can be different, depending
211    on the class of the argument.  This aspect of the dispatch is
212    handled by the second method on =specializer-accepts-generalizer-p=
213    below.
214 #+begin_src lisp
215 (defclass signum-specializer (specializer)
216   ((%signum :reader %signum :initarg :signum)))
217 (defclass signum-generalizer (generalizer)
218   ((%signum :reader %signum :initarg :signum)))
219 (defmethod generalizer-of-using-class ((gf signum-generic-function) arg)
220   (typecase arg
221     (real (make-instance 'signum-generalizer :signum (signum arg)))
222     (t (call-next-method))))
223 (defmethod generalizer-equal-hash-key ((gf signum-generic-function)
224                                        (g signum-specializer))
225   (%signum g)) ; this will create multiple entries for the same emf, but that's OK
226 (defmethod specializer-accepts-generalizer-p ((gf signum-generic-function)
227                                               (s signum-specializer)
228                                               (g signum-generalizer))
229   (if (= (%signum s) (%signum g)) ; or EQL?
230       (values t t)
231       (values nil t)))
232
233 ;; this method is perhaps interesting enough to talk about?
234 (defmethod specializer-accepts-generalizer-p ((gf signum-generic-function) (specializer sb-mop:specializer) (thing signum-specializer))
235   (specializer-accepts-generalizer-p gf specializer (class-of (%signum thing))))
236
237
238 (defmethod specializer-accepts-p ((s signum-specializer) o)
239   (and (realp o) (= (%signum s) (signum o))))
240
241 #| again elide more boring methods |#
242 #+end_src
243
244    Given these definitions, and some more straightforward ones elided
245    for reasons of space, we can implement the factorial function as
246    follows:
247
248 #+begin_src lisp
249 (defgeneric fact (n)
250   (:generic-function-class signum-generic-function))
251 (defmethod fact ((n (signum 0))) 1)
252 (defmethod fact ((n (signum 1))) (* n (fact (1- n))))
253 #+end_src
254
255    We do not need to include a method on =(signum -1)=, as the
256    standard =no-applicable-method= protocol will automatically apply to
257    negative real or non-real arguments.
258
259    Benchmarketing: we chose to benchmark 20! because that is the
260    largest factorial whose answer fits in SBCL's 63-bit fixnums, so as
261    to attempt to measure the maximum effect of dispatch (unobscured by
262    allocation / gc issues)
263
264 #+begin_src lisp
265 (progn (gc :full t) (time (dotimes (i 10000) (%fact 20))))
266 #+end_src
267
268    | fact (signum-gf) | %fact (fun) | %%fact (gf / 1meth) | fact (signum-gf / 1arg hash-special-case) |
269    |------------------+-------------+---------------------+-------------------------------------------|
270    |            0.284 |       0.004 |               0.016 |                                     0.032 |
271    |            0.076 |       0.008 |               0.012 |                                     0.024 |
272    |            0.072 |       0.004 |               0.012 |                                     0.116 |
273    |            0.264 |       0.004 |               0.008 |                                     0.120 |
274    |            0.292 |       0.008 |               0.012 |                                     0.120 |
275    |            0.264 |       0.004 |               0.016 |                                     0.084 |
276    |            0.276 |       0.008 |               0.012 |                                     0.092 |
277    |            0.264 |       0.008 |               0.012 |                                     0.036 |
278    |            0.276 |       0.008 |               0.004 |                                     0.104 |
279    |            0.272 |       0.004 |               0.012 |                                     0.020 |
280
281    We could allow the metaprogrammer to improve on the one-argument
282    performance by constructing a specialized cache: for =signum=
283    arguments of =rational= arguments, the logical cache structure is
284    to index a three-element vector with =(1+ signum)=.  The current
285    protocol does not provide a way of eliding the two generic function
286    calls for the generic cache; we discuss possible approaches in
287    section WW.
288 ** HTTP Accept header
289    In this section, we implement a non-trivial form of dispatch.  The
290    application in question is a web server, and specifically to allow
291    the programmer to support RFC 2616 \cite{rfc2616} content
292    negotiation, of particular interest to publishers and consumers of
293    REST-style Web APIs.
294
295    The basic mechanism in content negotiation is as follows: the web
296    client sends an HTTP request with an =Accept:= header, which is a
297    string describing the media types it is willing to receive as a
298    response to the request, along with numerical preferences.  The web
299    server compares these stated client preferences with the resources
300    it has available to satisfy this request, and sends the best
301    matching resource in its response.
302
303    In the case where there are static files on the filesystem, and the
304    web server must merely select between them, there is not much more
305    to say.  However, it is not unusual for a web service to be backed
306    by some other form of data, and responses computed and sent on the
307    fly, and in these circumstances the web server must compute which
308    of its known output formats it can use to satisfy the request
309    before actually generating the best matching response.
310
311    The =accept-specializer= below implements the dispatch.  It depends
312    on a lazily-computed =tree= to represent the information in the
313    accept header, and a function =q= to compute the (defaulted)
314    preference level for a given content-type and =tree=; then, method
315    selection and ordering involves finding the =q= for each
316    =accept-specializer='s content type given the =tree=, and sorting
317    them according to the preference level.
318
319 #+begin_src lisp
320 (defclass accept-specializer (extended-specializer)
321   ((media-type :initarg :media-type :reader media-type)))
322 (defclass accept-generalizer ()
323   ((header :initarg :header :reader header)
324    (tree)
325    (next :initarg :next :reader next)))
326 (defmethod generalizer-equal-hash-key
327     ((gf accept-generic-function) (g accept-generalizer))
328    `(accept-generalizer ,(header g)))
329 (defmethod specializer-accepts-generalizer-p ((gf accept-generic-function) (s acc
330 ept-specializer) (generalizer accept-generalizer))
331   (values (q (media-type s) (tree generalizer)) t))
332 (defmethod specializer-accepts-generalizer-p ((gf accept-generic-function) (s sb-
333 mop:specializer) (generalizer accept-generalizer))
334   (specializer-accepts-generalizer-p gf s (next generalizer)))
335
336 (defmethod specializer< ((gf accept-generic-function) (s1 accept-specializer) (s2
337  accept-specializer) generalizer)
338   (cond
339     ((string= (media-type s1) (media-type s2)) '=)
340     (t (let ((q1 (q (media-type s1) (tree generalizer)))
341              (q2 (q (media-type s2) (tree generalizer))))
342          (cond
343            ((= q1 q2) '=)
344            ((< q1 q2) '>)
345            (t '<))))))
346
347 ;; here are the only methods that actually know about TBNL
348 (defmethod generalizer-of-using-class ((gf accept-generic-function) (arg tbnl:request))
349   (make-instance 'accept-generalizer
350                  :header (tbnl:header-in :accept arg)
351                  :next (class-of arg)))
352 (defmethod specializer-accepts-p ((specializer accept-specializer) (obj tbnl:requ
353 est))
354   (q (media-type specializer) (parse-accept-string (tbnl:header-in :accept obj)))
355 )
356 #+end_src
357
358    This dispatch can't be done with filtered dispatch, except by
359    generating anonymous classes with all the right mime-types as
360    direct superclasses in dispatch order,so the filter does
361 #+begin_src lisp
362 (ensure-class nil :direct-superclasses '(text/html image/webp ...))
363 #+end_src
364    and dispatch is defined by using those classes.  And that's even
365    more awkward than it sounds, because that means that in principle
366    all the mime types in the universe need an existence as classes, to
367    cater for arbitrary mime types in accept headers.  And handling
368    wildcards is pretty much impossible, too.  See that in
369    =specializer<= which involves a nontrivial ordering of methods
370    (whereas in two above previous cases only a single extended
371    specializer could be applicable to any given argument)
372
373    Also of interest: note that we can have these
374    specializer/generalizers handle arbitrary objects: we can define
375    methods on =string=, completely independently from the methods on
376    =tbnl:request= methods are independent of each other; this
377    generalizes to dealing with multiple web server libraries.
378
379 #+begin_src lisp
380 ;; we can define methods on STRING too, for debugging/simulation purposes
381 (defmethod generalizer-of-using-class ((gf accept-generic-function) (s string))
382   (make-instance 'accept-generalizer
383                  :header s
384                  :next (class-of s)))
385 (defmethod specializer-accepts-p ((s accept-specializer) (string string))
386   (q (media-type s) (parse-accept-string string)))
387 #+end_src
388
389    jmoringe: the name =accept-specializer=, while sensible, may
390    confusing in this context because "accept" occurs as part of the
391    protocol with a different semantic.
392 ** Pattern / xpattern / regex / optima
393    Here's the /really/ interesting bit, but on the other hand we're
394    probably going to run out of space, and the full description of
395    these is going to take us into =make-method-lambda= territory.
396    A second paper?  Future work?
397 * Protocol
398 ** Generalizer
399    - [ ] =generalizer-of-using-class= (NB class of gf not class of object)
400    - [ ] =compute-applicable-methods-using-generalizers=
401    - [ ] =generalizer-equal-hash-key=
402    - [ ] =specializer-accepts-generalizer-p=
403    - [ ] =specializer-accepts-p=
404    - [ ] =specializer<=
405      jmoringe: If I remember correctly, closette has
406      =method-more-specific-p= should we aim for parity with that and
407      use =specializer-more-specific-p=? The downside would be that
408      =-p= indicates a Boolean return value which is not the case here.
409 ** Full protocol
410    Description and specification left for reasons of space (we'll see?)
411    - [ ] =same-specializer-p=
412    - [ ] =parse/unparse-specializer-using-class=
413    - [ ] =make-method-specializers-form=
414    - [ ] jmoringe: In an email, I suggested
415      =make-specializer-form-using-class=:
416
417      #+begin_quote
418      Could we change =make-method-specializers-form='s default
419      behaviour to call a new generic function
420      #+begin_src
421        make-specializer-form-using-class gf method name env
422      #+end_src
423      with builtin methods on =sb-mop:specializer=, =symbol=, =cons= (for
424      eql-specializers)? This would make it unnecessary to repeat
425      boilerplate along the lines of
426      #+begin_src lisp
427      (flet ((make-parse-form (name)
428               (if <name-is-interesting>
429                 <handle-interesting-specializer>
430                 <repeat-handling-of-standard-specializers>)))
431        `(list ,@(mapcar #'make-parse-form specializer-names)))
432      #+end_src
433      for each generic function class.
434      #+end_quote
435    - [ ] =make-method-lambda= revision (use environment arg?)
436
437      jmoringe: would only be relevant for pattern dispatch, right? I
438      think, we didn't finish the discussion regarding special
439      variables vs. environment vs. new protocol function
440 * Related Work
441   - [ ] Newton/Rhodes
442   - [ ] filtered dispatch -- the point is that our work continues to
443     be useful in cases where there are unbounded numbers of
444     equivalence classes but each given invokation involves a small
445     number of methods.
446   - [ ] ContextL / context-oriented programming -- dispatch occurs on
447     hidden layer argument being an instance of an anonymous class with
448     suitably arranged superclasses -- OK because set of layers is
449     bounded and under programmer control
450   - [ ] http://soft.vub.ac.be/Publications/2010/vub-tr-soft-10-04.pdf
451   - [ ] http://soft.vub.ac.be/lambic/files/lambic-ilc09.pdf
452   - [ ] http://soft.vub.ac.be/Publications/2011/vub-soft-phd-11-03.pdf
453   - [ ] Prototypes with Multiple Dispatch
454     http://sauerbraten.org/lee/ecoop.pdf -- extension of Self-style
455     object system to handle multiple equally-privileged "receivers".
456     A good test case for our protocol; handled adequately with
457     generalizer being the tuple of (roles,delegations), with some
458     thought needed for method redefinitions but otherwise working
459     fine.
460   - [ ] Sheeple
461 * Conclusions
462 ** Acknowledgments
463    We thank Lee Salzman, Pascal Costanza, Mikel Evins for their
464    helpful discussions