Predicate Dispatching
Total Page:16
File Type:pdf, Size:1020Kb
This pap er app ears in ECOOP the th Europ ean Conference on Ob ject Oriented Programming Brussels Belgium July pp Predicate Dispatching A Unied Theory of Dispatch Michael Ernst Craig Kaplan and Craig Chambers Department of Computer Science and Engineering University of Washington Seattle WA USA fmernstcskchambersgcswashingtonedu httpwwwcswashingtoneduresearchprojectscecil Abstract Predicate dispatching generalizes previous metho d dispatch mechanisms by p ermitting arbitrary predicates to control metho d ap plicabili ty and by using logical implication b etween predicates as the overriding relationship The metho d selected to handle a message send can dep end not just on the classes of the arguments as in ordinary ob jectoriented dispatch but also on the classes of sub comp onents on an arguments state and on relationships b etween ob jects This simple mechanism subsumes and extends ob jectoriented single and multiple dispatch MLstyle pattern matching predicate classes and classiers which can all b e regarded as syntactic sugar for predicate dispatching This pap er introduces predicate dispatching gives motivating examples and presents its static and dynamic semantics An implementation of predicate dispatching is available Introduction Many programming languages supp ort some mechanism for dividing the b o dy of a pro cedure into a set of cases with a declarative mechanism for selecting the right case for each dynamic invocation of the pro cedure Case selection can b e broken down into tests for applicability a case is a candidate for invocation if its guard is satised and overriding which selects one of the applicable cases for invocation Ob jectoriented languages use overloaded metho ds as the cases and generic functions implicit or explicit as the pro cedures A metho d is applicable if the runtime class of the receiver argument is the same as or a sub class of the class on which the receiver is sp ecialized Multiple dispatching BKK Cha enables testing the classes of all of the arguments One metho d overrides another if its sp ecializer classes are sub classes of the others using either lexicographic CLOS Ste or p ointwise Cecil Chaa ordering Predicate classes Chab automatically classify an ob ject of class A as an instance of virtual sub class B a sub class of A whenever B s predicate an ar bitrary expression typically testing the runtime state of an ob ject is true This creation of virtual class hierarchies makes metho d dispatching applicable even in cases where the eective class of an ob ject may change over time Classi ers HHMb and mo des Tai are similar mechanisms for reclassifying an ob ject into one of a number of sub classes based on a casestatementlike test of arbitrary b o olean conditions Pattern matching as in ML MTH bases applicability tests on the run time datatype constructor tags of the arguments and their sub comp onents As with classiers and mo des textual ordering determines overriding Some lan guages such as Haskell HJW allow arbitrary b o olean guards to accom pany patterns restricting applicability Views Wad extend pattern matching to abstract data types by enabling them to oer interfaces like various concrete datatypes Predicate dispatching integrates generalizes and provides a uniform inter face to these similar but previously incomparable mechanisms A metho d dec laration sp ecies its applicability via a predicate expression which is a logical formula over class tests ie tests that an ob ject is of a particular class or one of its sub classes and arbitrary b o oleanvalued expressions from the underlying programming language A metho d is applicable when its predicate expression evaluates to true Metho d m overrides metho d m when m s predicate logi cally implies that of m this relationship is computed at compile time Static typechecking veries that for all p ossible combinations of arguments to a generic function there is always a single mostsp ecic applicable metho d This ensures that there are no message not understo o d errors called match not exhaus tive in ML or message ambiguous errors at runtime Predicate expressions capture the basic primitive mechanisms underlying a wide range of declarative dispatching mechanisms Combining these primitives in an orthogonal and general manner enables new sorts of dispatching that are not expressible by previous dispatch mechanisms Predicate dispatching pre serves several desirable prop erties from its ob jectoriented heritage including that metho ds can b e declared in any order and that new metho ds can b e added to existing generic functions without mo difying the existing metho ds or clients these prop erties are not shared by patternmatchingbased mechanisms Section introduces the syntax semantics and use of predicate dispatching through a series of examples Section denes its dynamic and static semantics formally Section discusses predicate tautology testing which is the key mech anism required by the dynamic and static semantics Section surveys related work Section concludes with a discussion of future directions for research Overview This section demonstrates some of the capabilities of predicate dispatching by way of a series of examples We incrementally present a highlevel syntax which app ears in full in Fig Fig lists supp orting syntactic domains Words and symbols in b oldface represent terminals Angle brackets denote zero or more commaseparated rep etitions of an item Square brackets contain optional ex pressions E expr The set of expressions in the underlying programming language Body metho db o dy The set of metho d b o dies in the underlying programming language T type The set of types in the underlying programming language c classid The namespace of classes m metho did The namespace of metho ds and elds f eldid The namespace of metho ds and elds p predid The namespace of predicate abstractions v w varid The namespace of variables Fig Syntactic domains and variables Metho d and eld names app ear in the same namespace the metho did or eldid name is chosen for clarity in the text Predicate dispatching is parameterized by the syntax and semantics of the host programming language in which predicate dispatching is embedded The ideas of predicate dispatching are indep endent of the host language this pap er sp ecies only a predicate dispatching sublanguage with expr the generic nonter minal for expressions in the host language Types and signatures are used when the host language is statically typed and omitted when it is dynamically typed Dynamic dispatch Each metho d implementation has a predicate expression which sp ecies when the metho d is applicable Class tests are predicate expressions as are negations conjunctions and disjunctions of predicate expressions metho dsig signature metho did h type i type metho ddecl metho d metho did h formalpattern i when predexpr metho db o dy formalpattern varid predexpr expr classid succeeds if expr evaluates to an instance of classid or one of its sub classes j not predexpr negation j predexpr and predexpr conjunction shortcircuited j predexpr or predexpr disjunction shortcircuited Predicate expressions are evaluated in an environment with the metho ds for mal arguments b ound see Sect for details An omitted when clause indicates that the metho d handles all typecorrect arguments Metho d signature declarations give the type signature shared by a family of metho d implementations in a generic function A message send expression need examine only the corresp onding metho d signature declaration to determine its typecorrectness while a set of overloaded metho d implementations must completely and unambiguously implement the corresp onding signature in order to b e typecorrect Predicate dispatching can simulate b oth singly and multiplydispatched meth o ds by sp ecializing formal parameters on a class via the classid syntax Sp ecialization limits the applicability of a metho d to ob jects that are instances of the given class or one of its sub classes More generally predicate dispatching supp orts the construction of arbitrary conjunctions disjunctions and negations of class tests The following example uses predicate dispatching to implement the Zip function which converts a pair of lists into a list of pairs type List class Cons subtypes List headAny tailList class Nil subtypes List signature ZipList ListList method Zipl l when lCons and lCons return ConsPairlhead lhead Zipltail ltail method Zipl l when lNil or lNil return Nil The rst Zip metho d applies when b oth of its arguments are instances of Cons or some sub class The second Zip metho d uses disjunction to test whether either argument is an instance of Nil or some sub class The type checker can verify statically that the two implementations of Zip are mutually exclusive and exhaustive over all p ossible arguments that match the signature ensuring that there will b e no message not understo o d or message ambiguous errors at runtime without requiring the cases to b e put in any particular order There are several unsatisfactory alternatives to the use of implication to de termine overriding relationships MLstyle pattern matching requires all cases to b e written in one place and put in a particular total order resolving ambiguities in favor of the rst successfully matching pattern Likewise a lexicographic or dering for multimethods Ste is errorprone and unnatural and programmers are not warned of p otential ambiguities In a traditional singly or multiply dispatched ob jectoriented language without