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

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 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 the ability to order cases either

the base case of Zip must b e written as the default case for all pairs of List ob

jects unnaturally and unsafely in the face of future additions of new sub classes

of List or three separate but identical base metho ds must b e written one for

NilAny one for AnyNil and a third for NilNil to resolve the ambiguity

b etween the rst two In our exp erience with ob jectoriented languages using a

p ointwise not lexicographic ordering these triplicate base metho ds for binary

messages o ccur frequently

As a syntactic convenience class tests can b e written in the formal argument

list

formalpattern varid classid like varid classid in predexpr

The class name can b e omitted if the argument is not dispatched up on and

the formal name can b e omitted if the argument is not used elsewhere in the

predicate or metho d b o dy

The rst Zip metho d ab ove could then b e rewritten as

1

Any is the top class sub classed by all other classes and Pair returns an ob ject

containing its two arguments

method ZiplCons lCons

return ConsPairlhead lhead Zipltail ltail

This form uses an implicit conjunction of class tests like a multimethod

Pattern matching

Predicates can test the runtime classes of comp onents of an argument just as

pattern matching can query substructures by suxing the class test with a

recordlike list of eld names and corresp onding class tests names can b e b ound

to eld contents at the same time

predexpr

j expr sp ecializer

sp ecializer classid f h eldpat i g

eldpat eldid varid sp ecializer

A sp ecializer succeeds if all of the sp ecied elds or results of invoking metho ds

named by eldid satisfy their own sp ecializer s in which case the varid s are

b ound to the eld values or metho d results As with formalpattern the formal

name or sp ecializer may b e omitted

Our syntax for pattern matching on records is analogous to that for creating

a record x y creates a twocomponent record binding the x

eld to and the y eld to while x xval patternmatches against a

record containing an x eld binding the new variable xval to the contents of that

eld and ignoring any other elds that might b e present The similarity b etween

the record construction and matching syntaxes follows ML Our presentation

syntax also uses curly braces in two other places for record type sp eciers as

in the declaration of the Cons class ab ove and to delimit co de blo cks as in the

denitions of the Zip metho ds ab ove

The following example adapted from our implementation of an optimizing

compiler shows how a ConstantFold metho d can dispatch for binary op erators

whose arguments are constants and whose op erator is integer addition

type Expr

signature ConstantFoldExprExpr

default constantfold optimization do nothing

method ConstantFolde return e

type AtomicExpr subtypes Expr

class VarRef subtypes AtomicExpr

class IntConst subtypes AtomicExpr valueint

other atomic expressions here

type Binop

class IntPlus subtypes Binop

class IntMul subtypes Binop

other binary operators here

class BinopExpr subtypes Expr opBinop argExpr argExpr

override default to constantfold binops with constant arguments

method ConstantFoldeBinopExpr opIntPlus argIntConst argIntConst

return new IntConst value eargvalue eargvalue

more similarly expressed cases for other binary and unary operators here

The ability in pattern matching to test for constants of builtin types is a

simple extension of class tests In a prototypebased language op erates over

ob jects as well as classes as in answer

As with pattern matching testing the representation of comp onents of an

ob ject makes sense when the ob ject and the tested comp onents together imple

ment a single abstraction We do not advocate using pattern matching to test

comp onents of ob jects in a way that crosses natural abstraction b oundaries

Bo olean expressions

To increase the expressiveness of predicate dispatching predicates may test arbi

trary b o olean expressions from the underlying programming language Addition

ally names may b e b ound to values for use later in the predicate expressions

and in the metho d b o dy Expressions from the underlying programming lan

guage that app ear in predicate expressions should have no externally observable

side eects

predexpr

j test expr succeeds if expr evaluates to true

j let varid expr evaluate expr and bind varid to its value

always succeeds

The following extension to the ConstantFold example illustrates these fea

tures Recall that in valuev the lefthand side is a eld name and the

righthand side is a variable b eing b ound

Hand le case of adding zero to anything but dont be ambiguous

with existing method for zero plus a constant

method ConstantFold

eBinopExpr opIntPlus argIntConst valuev arga

when testv and notaIntConst

return a

method ConstantFold

eBinopExpr opIntPlus arga argIntConst valuev

when testv and notaIntConst

return a

other special cases for operations on here

2

We do not presently enforce this restriction but there is no guarantee regarding in

what order or how many times predicate expressions are evaluated

Predicate abstractions

Named predicate abstractions can factor out recurring tests and give names to

semantically meaningful concepts in the application domain Named predicates

abstract over b oth tests and variable bindings the two capabilities of inline

predicate expressions by b oth succeeding or failing and returning a record

like set of bindings These bindings resemble the elds of a record or class and

similar supp ort is given to pattern matching against a subset of the results of

a named predicate invocation Predicate abstractions thus can act like views

or virtual sub classes of some ob ject or tuple of ob jects with the results of

predicate abstractions acting like the virtual elds of the virtual class If the

prop erties of an ob ject tested by a collection of predicates are mutable the

ob ject may b e given dierent virtual sub class bindings at dierent times in its

life providing the b enets of using classes to organize co de even in situations

where an ob jects class is not xed

predsig predsignature predid h type i

return f h eldid type i g

preddecl predicate predid h formalpattern i

when predexpr return f h eldid expr i g

predexpr

j predid h expr i > f h eldpat i g

test predicate abstraction

sp ecializer classsp ec f h eldpat i g

classsp ec classid expr classid is a class test

j predid expr predid f g is alternate syntax

for predid expr > f g

A predicate abstraction takes a list of arguments and succeeds or fails as

determined by its own predicate expression A succeeding predicate abstraction

invocation can exp ose bindings of names to values it computed during its evalu

ation and the caller can retrieve any subset of the predicate abstractions result

bindings Predicate signatures sp ecify the type interface used in typechecking

predicate abstraction callers and implementations In this presentation we pro

hibit recursive predicates

Simple predicate abstractions can b e used just like ordinary classes

predicate onxaxisppoint

when pcartesianPoint and testpy

or ppolarPoint and testptheta or testptheta pi

method drawppoint draw the point

method drawponxaxis use a contrasting color so point is visible

In the following example taken from our compiler implementation CFGsucc

is a control ow graph CFG no de with two successors Each successor is marked

with whether it is a lo op exit information which in our implementation is dy

namically maintained when the CFG is mo died and the innermost lo op it do es

not exit It is advantageous for an iterative dataow algorithm to propagate val

ues along the lo op exit only after reaching a xed p oint within the lo op such an

algorithm would dispatch on the LoopExit predicate Similarly the algorithm

could switch from iterative to noniterative mo de when exiting the outermost

lo op as indicated by TopLevelLoopExit

predsignature LoopExitCFGnode

return loopCFGloop

predicate LoopExitnCFGsucc nexttrue t nextfalse f

when testtisloopexit or testfisloopexit

return loop outermosttcontainingloop fcontainingloop

predicate TopLevelLoopExitnLoopExit loopTopLevelScope

Only one denition p er predicate abstraction is p ermitted App B relaxes

this restriction

Because ob ject identity is not aected by these dierent views on an ob ject

named predicate abstractions are more exible than co ercions in environments

with sideeects Additionally a single ob ject can b e classied in multiple in

dep endent ways by dierent predicate abstractions without b eing forced to de

ne all the p ossible conjunctions of indep endent predicates as explicit classes

relieving some of the problems asso ciated with a mixin style of class organiza

tion HHMbHHMa

Classiers

Classiers HHMb are a convenient syntax for imp osing a linear ordering on a

collection of predicates ensuring mutual exclusion They combine the state test

ing of predicate classes and the total ordering of pattern matching An optional

otherwise case which executes if none of the predicates in the classier eval

uates to true adds the guarantee of complete coverage Multiple indep endent

classications of a particular class or ob ject do not interfere with one another

classierdecl classify h formalpattern i

h as predid when predexpr return f h eldid expr i g i

as predid otherwise return f h eldid expr i g

Here is an example of the use of classiers

class Window

classifywWindow

as Iconified when testwiconified

as FullScreen when testwarea RootWindowarea

as Big when testwarea RootWindowarea

as Small otherwise

method movewFullScreen xint yint nothing to do

method movewBig xint yint move a wireframe outline

method movewSmall xint yint move an opaque window

method movewIconified xint yint modify icon coordinates

resize maximize and iconify similarly test these predicates

metho dsig signature metho did h type i type

metho ddecl metho d metho did h varid i when predexpr metho db o dy

predsig predsignature predid h type i return f h eldid type i g

preddecl predicate predid h varid i when predexpr

return f h eldid expr i g

P Q predexpr varid classid succeeds if varid is an instance

of classid or a sub class

j test varid succeeds if varid s value is true

j let varid expr evaluate expr and bind varid

to that value always succeeds

j predid h varid i > f h eldid varid i g

test predicate abstraction

j true always succeeds

j not predexpr negation

j predexpr and predexpr conjunction shortcircuited

j predexpr or predexpr disjunction shortcircuited

Fig Abstract syntax of the core language Words and symbols in b oldface represent

terminals Angle brackets denote zero or more commaseparated rep etitions of an item

Square brackets contain optional expressions The text uses parentheses around pred

expr s to indicate order of op erations Each predicate may b e dened only once App B

relaxes this restriction and recursive predicates are forbidden

Classiers introduce no new primitives but provide syntactic supp ort for a

common programming idiom To force the classication to b e mutually exclusive

each case is transformed into a predicate which includes the negation of the

disjunction of all previous predicates for details see App A Therefore an

ob ject is classied by some case only when it cannot b e classied by any earlier

case

Dynamic and static semantics

The rest of this pap er formalizes the dynamic and static semantics of a core

predicate dispatching sublanguage Figure presents the abstract syntax of the

core sublanguage which is used throughout this section App endix A denes

desugaring rules that translate the highlevel syntax of Fig into the core

syntax

In the remainder of this pap er we assume that all variable names are distinct

so that the semantic rules can ignore the details of avoiding variable capture

Dynamic semantics

This section explains how to select the mostsp ecic applicable metho d at each

message send This selection relies on two key tests on predicated metho ds

whether a metho d is applicable to a call and whether one metho d overrides

another

value Values in the underlying programming language

b ftrue falseg Mathematical b o oleans

K varid value Environments mapping variables to values

predid preddecl and predicate names to predicate declarations

lo okup v K Lo ok up variable v in environment K returning the value

0

K v K Bind name v to value in environment K resulting in the new

0

environment K Any existing binding for v is overridden

evalE K Evaluate expression E in environment K returning the value

instanceof c b Determine whether value is an instance of c or a sub class of c

accept b Co erce arbitrary program values to true or false for use with test

Fig Dynamic semantics domains and help er functions Evaluation rules app ear in

Fig The host programming language supplies functions eval instanceof and accept

A metho d is applicable if its predicate evaluates to true Predicate evaluation

also provides an extended environment in which the metho ds b o dy is executed

Bindings created via let in a predicate may b e used in a metho d b o dy predicate

return clause or the second conjunct of a conjunction whose rst conjunct

created the binding Such bindings p ermit reuse of values without recomputation

as well as simplifying and clarifying the co de Figures and dene the execution

mo del of predicate evaluation

Predicate dispatching considers one metho d m to override another metho d

m exactly when m s predicate implies m s predicate and not vice versa Sec

tion describ es how to compute the overriding relation which can b e p erformed

at compile time

Given the evaluation mo del for predicate expressions and the ability to com

pare predicate expressions for overriding the execution of generic function invo

cations is straightforward Supp ose that generic function m is dened with the

following cases

metho d mv v when P Body

n

metho d mv v when P Body

n

metho d mv v when P Body

n k

k

To evaluate the invocation mE E in the environment K rst obtain

n

evalE K for all i n Then for j k obtain a truth

i i

value b and a new environment K through hP K v v i

j j j n n

hb K i as in the predicate invocation rules of Fig

j j

Now let I b e the set of integers i such that b true and nd i I such

i

overrides all others in fP g The result of evaluating mE E that P

i i2I n i

0

3

Since we assume that all variable names are distinct and disallow lexicall y nested

predicate abstractions we can safely use the dynamic environment at the call site

instead of preserving the static environment at the predicate abstractions denition

p oint

htrue K i htrue K i

lo okup v K instanceof c b

hv c K i hb K i

lo okup v K accept b

htest v K i hb K i

0

evalE K K v K

0

hlet v E K i htrue K i

i f ng lo okup v K

i i

0 0 0 0

lo okup p K predicate pv v when P return ff w f w g

1 m

1 n 1 m

0 0 0

i hfalse K i v hP K v

n 1

n 1

hp v v > ff w f w g K i hfalse K i

1 n 1 1 m m

i f ng lo okup v K

i i

0 0 0 0

lo okup p K predicate pv v when P return ff w f w g

1 m

1 n 1 m

0 0 0

hP K v v i htrue K i

1 n

1 n

0 0

i f mg lo okup w K

i

i

00

K w w K

1 1 m m

00

hpv v > ff w f w g K i htrue K i

1 n 1 1 m m

0

hP K i hb K i

hnot P K i hb K i

0

hP K i hfalse K i

hP and Q K i hfalse K i

0 0 00

hP K i htrue K i hQ K i hfalse K i

hP and Q K i hfalse K i

0 0 00

hP K i htrue K i hQ K i htrue K i

00

hP and Q K i htrue K i

0

hP K i htrue K i

hP or Q K i htrue K i

0 00

hP K i hfalse K i hQ K i htrue K i

hP or Q K i htrue K i

0 00

hP K i hfalse K i hQ K i hfalse K i

hP or Q K i hfalse K i

Fig Dynamic semantics evaluation rules Domains and help er functions app ear in

0

Fig We say hP K i hb K i when the predicate P evaluates in the environment

0

K to the b o olean result b pro ducing the new environment K If the result b is false

0

then the resulting environment K is ignored Bindings do not escap e from not or or

constructs App B relaxes the latter restriction The starred hypothesis uses K not

0 00

K to construct the result environment K b ecause only the bindings sp ecied in the

return clause not all bindings in the predicates when clause are exp osed at the call

site

so that variables in the environment K is then the result of evaluating Body

i

0 i

0

b ound in the predicate can b e referred to in the b o dy If no such i exists then

an exception is raised a message not understo o d error if I is empty or a

message ambiguous error if there is no unique most sp ecic element of I

An implementation can make a number of improvements to this base algo

rithm Here we briey mention just a few such optimizations First common

sub expression elimination over predicate expressions can limit the computation

done in evaluating guards Second precomputed implication relationships can

prevent the necessity for evaluating every predicate expression If a more sp e

cic one is true then the less sp ecic one is certain to b e satised however such

satisfaction is irrelevant since the more sp ecic predicate will b e chosen Third

clauses and metho ds can b e reordered to succeed or fail more quickly as in some

Prolog implementations Zel

Static semantics and typechecking

The op erational mo del of predicate dispatch describ ed in Sect can raise

a runtime exception at a message send if no metho d is applicable or if no

applicable metho d overrides all the others We extend the typechecking rules of

the underlying language to guarantee that no such exception o ccurs

Figure presents the static semantic domains help er functions and type

checking rules for the core predicate dispatching sublanguage The return type

for a predicate invocation is an unordered record Bindings do not escap e from

not or or constructs App B makes bindings on b oth sides of a or disjunct

visible outside the disjunct

We can separate typechecking into two parts clientside which handles

all checking of expressions in the underlying language and uses metho d sig

natures to typecheck message sends and implementationside which checks

metho d and predicate implementations against their corresp onding signatures

Only implementationside checking is aected by predicate dispatching

Implementationside typechecking must guarantee completeness and unique

ness Completeness guarantees that no message not understo o d error is raised

for every p ossible set of arguments at each call site some metho d is applicable

Let P b e the disjunction of the predicates of all of ms implementations and

m

let P b e a predicate expressing the set of argument classes that conform to the

s

types in the metho d signature See b elow for the details of predicate P a class

s

c conforms to a type T if every ob ject which is an instance of that class has type

T or a subtype of T If P implies P then some metho d is always applicable

s m

Uniqueness guarantees that no message ambiguous error is raised for no p os

sible set of arguments at any call site are there multiple mostsp ecic metho ds

Uniqueness is guaranteed if for each pair of predicates P and Q attached to two

dierent implementations either P and Q are disjoint so their asso ciated meth

o ds can never b e simultaneously applicable or one of the predicates implies the

other so one of the metho ds overrides the other Section presents implication

and disjointness tests over predicate expressions

0 0

T T Type T is a subtype of T

conformanttype T c Return the mostsp ecic with resp ect to the partial

0 0

order type T such that every sub class c of c that conforms

0

to T also conforms to T This help er function is supplied by

the underlyin g programming language

0 00

Overriding extension of typing environments For each v

0 0 0 00 0

dom if j v T then j v T for each

0 00

v dom n dom if j v T then j v T

signature mT T T fm T T T g

1 n r 1 n r

j m T T T

1 n r

0 0

fv T v T g P j Body T T T

1 1 n n b b r

metho d mv v when P Body

1 n

r r

h predsignature pT T return ff T f T gi

1 n 1 m

m

1

r r

fp T T ff T f T g g

1 n 1 m

1 m

r r

j p T T ff T f T g

1 n 1 m

1 m

0

fv T v T g P

1 1 n n

0 0 0 0 r

i f mg j v T T T

i i i i

0 0

predicate pv v when P return ff v f v g

1 n 1 m

1 m

true

0

j v T conformanttype c T T

0

v c fv T g

j v B ool

test v

j expr T

let v expr fv T g

r r

j p T T ff T f T g

1 n 1 m

m

1

0 0 0 0

j v T j v T T T T T

1 n 1 n

1 n 1 n

0 0 0 r 0 r

p v v > ff v f v g fv T v T g

1 n 1 m

1 m 1 1 m m

0

P

not P

0 0 00

P P

1 2

00

P and P

1 2

0 00

P P

1 2

P or P

1 2

Fig Typechecking rules The hypothesis j E T indicates that typechecking

in typing environment assigns type T to expression E The judgment P

0

represents extension of typechecking environments given type environment P

0

typechecks and pro duces new typechecking environment

Completeness checking requires a predicate P that expresses the set of tuples

s

of values v v conforming to some signatures argument types T T

n n

this predicate dep ends on the host languages mo del of classes and typing If

classes and types are the same and all classes are concrete then the corre

sp onding predicate is simply v T and and v T If abstract classes are

n n

allowed then each v T is replaced with v T or or v T where

i i i i i im

the T are the top concrete sub classes of T If inheritance and subtyping are

ij i

separate notions then the predicates b ecome more complex

Our typechecking need not test that metho ds conform to signatures unlike

previous work on typechecking multimethods CL In predicate dispatching

a metho ds formal argument has two distinct types the external type derived

from the signature declaration and the p ossibly ner internal type guaranteed

by successful evaluation of the metho ds predicate The individual tests narrow

the type of the tested value to the mostsp ecic type to which all classes passing

the test conform in a hostlanguagesp ecic manner using conformanttype

The conformanttype function replaces the more complicated conformance test

of earlier work

Comparing predicate expressions

The static and dynamic semantics of predicate dispatching require compiletime

tests of implication b etween predicates to determine the metho d overriding re

lationship The static semantics also requires tests of completeness and unique

ness to ensure the absence of message not understo o d errors and message

ambiguous errors resp ectively All of these tests reduce to tautology tests over

predicates Metho d m with predicate p overrides metho d m with predicate p

i p implies p that is if not p or p is true A set of metho ds is complete

if the disjunction of their predicates is true Uniqueness for a set of metho ds re

quires that for any pair of metho ds either ones predicate overrides the others

or the two predicates are logically exclusive Two formulas are mutually exclusive

exactly if one implies the negation of the other

Section presents a tautology test over predicate expressions which is sim

ple sound and complete up to equivalence of arbitrary program expressions

in test constructs which we treat as black b oxes Because determining logi

cal tautology is NPcomplete in the worst case an algorithm takes exp onential

time in the size of the predicate expressions For ob jectoriented dispatch this

is the number of arguments to a metho d a small constant Simple optimiza

tions Sect make the tests fast in many practical situations This cost is

incurred only at compile time at run time precomputed overriding relations

among metho ds are simply lo oked up

We treat expressions from the underlying programming language as black

b oxes but do identify those whose canonicalizations are structurally identical

Tests involving the runtime values of arbitrary host language expressions are

undecidable The algorithm presented here also do es not address recursive pred

icates While we have a set of heuristics that succeed in many common practical

cases we do not yet have a complete sound and ecient algorithm

The base algorithm

The base algorithm for testing predicate tautology has three comp onents First

the predicate expression is canonicalized to macroexpand predicate abstrac

tions eliminate variable bindings and use canonical names for formal arguments

This transformation prevents dierent names for the same value from b eing con

sidered distinct Second implication relations are computed among the atomic

predicates for instance x int implies x num Finally the canonicalized

predicate is tested for every assignment of atomic predicates to truth values

which is consistent with the atomic predicate implications The predicate is a

tautology i evaluating it in every consistent truth assignment yields true

Canonicalization Canonicalization p erforms the following transformations

Expand predicate calls inline replacing the > clause by a series of let

bindings

Replace letb ound variables by the expressions to which they are b ound

and replace let expressions by true

Canonically rename formal parameters according to their p osition in the

formal list

After canonicalization each predicate expression is a logical formula over the

following atoms with connectives and or and not

predatom true

j test expr

j expr classid

Canonicalized predicates are a compiletime construct used only for predicate

comparison they are never executed Canonicalized predicates bind no variables

and they use only global variables and formal parameters

In the worst case canonicalization exp onentially blows up expression sizes

For instance in

let x xx and let x x x and let x x x and and test x y

n

n

instances of x Inline the nal x is replaced by an expression containing

n

expansion of predicate abstractions similarly contributes to this blowup As with

ML typechecking KM which is exp onential in the worst case but linear in

practice we anticipate that predicates leading to exp onential b ehavior will b e

rare

In what follows we consider two expressions identical if after canonicaliza

tion they have the same abstract syntax tree

Omitting the canonicalization step prevents some equivalent expressions from

b eing recognized as such but do es not prevent the remainder of the algorithm

from succeeding when results are named and reused rather than the computation

rep eated

Truth assignment checking We present a simple exp onentialtime algorithm

to check logical tautology b ecause the problem is NPcomplete any algorithm

takes exp onential time in the worst case Let there b e n distinct predicate atoms

n

in the predicate there are dierent truth assignments for those atoms Not

all of those truth assignments are consistent with the implications over predicate

atoms for instance it is not sensible to set a int to true but a num to

false b ecause a int implies a num If every consistent truth assignment

satises the predicate then the predicate is a tautology Each check of a single

truth assignment takes time linear in the size of the predicate expression for a

n

total time of O n

The following rules sp ecify implication over p ossibly negated canonical

predicate atoms

E c E c i E E and c is a sub class of c

E c notE c i E E and c is disjoint from c

a a i not a not a

a not a i a not a

Two classes are disjoint if they have no common descendant and not not a a

Optimizations

The worstcase exp onentialtime cost to check predicate tautology need not pre

vent its use in practice Satisability is checked only at compile time When

computing overriding relationships the predicates tend to b e small linear in

the number of arguments to a metho d We present heuristics that reduce the

costs even further

Logical simplication such as eliminating uses of true false a and not a

and a or not a and replacing not not a by a can b e p erformed as part of

canonicalization to reduce the size of predicate expressions

Unrelated atomic predicates can b e treated separately To determine whether

metho d m f c f c fg overrides metho d m f c f c fg it is

sucient to indep endently determine the relationship b etween c and c and

that b etween c and c Two tests with a smaller exp onent replace one with a

larger one substantially reducing the overall cost This technique always solves

ordinary single and multiple dispatching overriding in time constant and linear

in the number of formals resp ectively by examining each formal p osition inde

p endently The technique also applies to more complicated cases by examining

subsets of formal parameters which app ear together in tests from the underlying

programming language

It is not always necessary to completely expand predicate abstraction calls

as part of canonicalization If relations b etween predicate abstractions or other

predicate expressions are known then the tautology test can use them directly

As one example dierent cases of a classier are mutually exclusive by denition

The side conditions on atomic predicate values their implication relation

n

ships usually prevent the need to check all dierent truth assignments for

a predicate containing n atomic predicates When a int is set to true then

all truth assignments which set a num to false can b e skipp ed without further

consideration

Finally it may b e p ossible to achieve faster results in some cases by recasting

the tautology test Rather than attempting to prove that every truth assignment

satises a predicate expression it may b e advantageous to search for a single

truth assignment that satises its negation

Related work

Ob jectoriented approaches

In the mo del of predicate dispatching traditional ob jectoriented dispatching

translates to either a single class test on the receiver argument or for multi

ple dispatching a conjunction of class tests over several arguments Full predi

cate dispatching additionally enables testing arbitrary b o olean expressions from

the underlying language accessing and naming sub comp onents of the argu

ments p erforming tests over multiple arguments and arbitrarily combining

tests via conjunction disjunction and negation Also named predicate ab

stractions eectively introduce new virtual classes and corresp onding sub class

ing links into the program inheritance hierarchy Predicate dispatching pre

serves the ability in ob jectoriented languages to statically determine when

one metho d overrides another and when no message lo okup error can o ccur

Singlydispatched ob jectoriented languages have ecient metho d lo okup algo

rithms and separate typechecking which dep end crucially on the absence of

any separate mo dules that dispatch on other argument p ositions Multiply

dispatched ob jectoriented languages have more challenging problems in imple

mentation KRCTKAGS and typechecking CL and predicate dis

patching in its unrestricted form shares these challenges

Predicate classes Chab are an earlier extension of ob jectoriented dis

patching to include arbitrary b o olean predicates A predicate class which in

herits from class A and has an asso ciated predicate expression guard would b e

mo deled as a named predicate abstraction that tests A and guard Predicate

dispatching is more general for example by b eing able to dene predicates over

multiple arguments Predicate dispatching exploits the structure of and or and

not to automatically determine when no message lo okup error can o ccur while

typechecking of predicate classes relies on uncheckable user assertions ab out the

relations b etween the predicate classes guard expressions

Classiers in Kea HHMbHHMaMHH let an instance of a class b e

dynamically reclassied as b eing of a sub class A classier for a class is com

p osed of a sequence of predicatesub class pairs with an ob ject of the input class

automatically classied as b eing of the sub class with the rst successful predi

cate Because the sequence of predicates is totally ordered and the rst successful

predicate takes precedence over all later predicates a classier provides a concise

syntax for a set of mutually exclusive exhaustive predicate abstractions Predi

cate abstractions are more general than classiers in many of the ways discussed

ab ove but they also provide syntactic supp ort for this imp ortant idiom Kea is a

purely functional language so classiers do not need to consider the semantics of

reclassifying ob jects when the values of predicates change predicate dispatching

addresses this issue by conceptually p erforming reclassication as needed as

part of message dispatching

Mo des Tai are another mechanism for adding dynamic reclassication of a

class into a sub class Unlike predicate classes and classiers the mo des of a class

are not rstclass sub classes but rather internal comp onents of a class that cannot

b e extended externally and that cannot exploit inheritance to factor shared co de

Mo de reselection can b e done either explicitly at the end of each metho d or

implicitly after each assignment using a declaratively sp ecied classication

Pattern matching approaches

Predicate dispatching supp orts many of the facilities found in pattern matching

as in ML MTH and Haskell HJW including tests over arbitrary nested

structure binding of names to sub comp onents and arbitrary b o olean guard ex

pressions Predicate dispatching additionally supp orts inheritance its class tests

are more general than datatype constructor patterns disjunctions and negations

of tests and conjunctions of tests on the same ob ject and named predicate ab

stractions to factor out common patterns of tests and to oer conditional views

of ob jects extended with virtual elds The patterns in a function are totally

ordered while predicate dispatching computes a partial order over predicates

and warns when two patterns might b e ambiguous Finally new metho ds can b e

added to existing generic functions without changing any existing co de while

new patterns can b e added to a function only by mo difying it

Views Wad extend pattern matching to abstract data types by allowing

an abstract data type to oer a number of views of itself as a concrete datatype

over which pattern matching is dened Predicate dispatching supp orts pattern

matching over the results of metho ds by letbinding their results to names and

then testing those names just as eld contents are b ound and tested and those

metho ds can serve as accessor functions to a virtual view of the ob ject for

instance rho and theta metho ds presenting a p olar view of a cartesian p oint

Views must b e isomorphisms which enables equational reasoning over them by

contrast named predicate abstractions provide conditional views of an ob ject

without requiring the presence of b oth in and out views

Pizza OW supp orts b oth algebraic datatypes and asso ciated pattern

matching and ob jectoriented dispatching but the two mechanisms are largely

distinct The authors argue that datatypes are go o d for xed numbers of rep

resentations with extensible op erations while classes are go o d for a xed set of

op erations with extensible representations By integrating pattern matching and

dispatching including multimethods predicate dispatching achieves extensibility

in b oth dimensions along with the syntactic convenience of pattern matching

Predicate dispatching faces more dicult implementation and separate type

checking challenges with the shift to multimethodlike dispatching

Conclusions

Many language features express the concept of selecting a mostsp ecic applica

ble metho d from a collection of candidates including ob jectoriented dispatch

pattern matching views predicate classes and classiers Predicate dispatching

integrates and generalizes these mechanisms in a single framework based on a

core language of b o olean expressions over class tests and arbitrary expressions

explicit binding forms to generalize features of pattern matching and named

predicate abstractions with result bindings By providing a single integrated

mechanism programs can take advantage of various styles of dispatch and even

combine them to create applicability conditions that were previously either im

p ossible or inconvenient to express

We have implemented predicate dispatching in the context of Dubious a

simple core multiplydispatched ob jectoriented programming language The

implementation supp orts all the examples presented in this pap er although

for clarity this pap er uses a slightly dierent presentation syntax The imple

mentation supp orts the full core language of Sect and many of the syn

tactic sugars of App A This implementation was helpful in verifying our

base design We exp ect that it will also provide insight into the advantages

and disadvantages of programming with predicate dispatching as well as help

us to evaluate optimization strategies The implementation is available from

httpwwwcswashingtoneduresearchprojectscecilwwwGud

So far we have fo cused on developing the static and dynamic semantics for

predicate dispatching Two unresolved practical issues that we will address in

the future are ecient implementation techniques and separate typechecking

supp ort for predicate dispatching We anticipate that ecient implementations

of unrestricted predicate dispatching will build up on work on ecient implemen

tation of multimethod dispatching and on predicate classes In addition static

analyses that factor a collection of predicates to avoid redundant tests and side

eect analyses that determine when predicates need not b e reevaluated app ear

to b e promising lines for future research Similarly separate typechecking of col

lections of predicated metho ds will build up on current work to develop mo dular

and incremental metho ds for typechecking multimethods CL

Acknowledgments

Todd Millstein Vassily Litvinov Wilson Hsieh David Grove and the anonymous

referees made helpful comments on a draft of this pap er This research is sup

p orted in part by an NSF grant number CCR an NSF Young Investi

gator Award number CCR a grant from the Oce of Naval Research

contract number N an IBM graduate fellowship an FCAR

graduate scholarship and gifts from Sun Microsystems IBM Xerox PARC Pure

Software and Edison Design Group

References

AGS Eric Amiel Olivier Grub er and Eric Simon Optimizing multimethod dis

patch using compressed dispatch tables In Proceedings OOPSLA pages

Portland OR Octob er

+

BKK Daniel G Bobrow Ken Kahn Gregor Kiczales Larry Masinter Mark Ste

k and Frank Zdyb el Commonlo ops Merging lisp and ob jectoriented

programming In Proceedings OOPSLA pages November

Published as ACM SIGPLAN Notices volume number

Cha Craig Chambers Ob jectoriented multimethods in Cecil In O Lehrmann

Madsen editor Proceedings ECOOP LNCS pages Utrecht

The Netherlands June SpringerVerlag

Chaa Craig Chambers The Cecil language Sp ecication and rationale Technical

Rep ort UWCSE Department of Computer Science and Engineer

ing University of Washington March

Chab Craig Chambers Predicate classes In O Nierstrasz editor Proceedings

ECOOP LNCS pages Kaiserslautern Germany July

SpringerVerlag

CL Craig Chambers and Gary T Leavens Typechecking and mo dules for

multimethods ACM Transactions on Programming Languages and Sys

tems November

CTK Weimin Chen Volker Turau and Wolfgang Klas Ecient dynamic lo ok

up strategy for multimethods In M Tokoro and R Pareschi editors

Proceedings ECOOP LNCS pages Bologna Italy July

SpringerVerlag

HHMa J Hamer JG Hosking and WB Mugridge A metho d for integrating clas

sication within an ob jectoriented environment Technical Rep ort Auck

land Computer Science Rep ort No Department of Computer Science

University of Auckland Octob er

HHMb JG Hosking J Hamer and WB Mugridge Integrating functional and

ob jectoriented programming In Technology of ObjectOriented Languages

and Systems TOOLS pages Sydney

+

HJW Paul Hudak Simon Peyton Jones Philip Wadler Brian Boutel Jon

Fairbairn Joseph Fasel Maria Guzman Kevin Hammond John Hughes

Thomas Johnsson Dick Kieburtz Rishiyur Nikhil Will Partain and John

Peterson Rep ort on the programming language Haskell version SIG

PLAN Notices May

KM Paris C Kanellakis and John C Mitchell Polymorphic unication and ML

typing In ACMSIGPLAN ACMSIGACT editor Conference Record of

the th Annual ACM Symposium on Principles of Programming Languages

POPL pages Austin TX USA January ACM Press

KR Gregor Kiczales and Luis Ro driguez Ecient metho d dispatch in PCL

Technical Rep ort SSL Xerox PARC Systems Sciences Lab oratory

MHH Warwick B Mugridge John Hamer and John G Hosking Multimetho ds in

a staticallytyped programming language In P America editor Proceedings

ECOOP LNCS pages Geneva Switzerland July

SpringerVerlag

MTH Robin Milner Mads Tofte and Rob ert Harp er The Denition of Standard

ML MIT Press

OW Martin Odersky and Philip Wadler Pizza into Java Translating theory into

practice In Conference Record of the th ACM SIGPLANSIGACT Sym

posium on Principles of Programming Languages pages January

Ste Guy L Steele Jr Common Lisp The Language Digital Press Bedford

MA Second edition

Tai Antero Taivalsaari Ob jectoriented programming with mo des Journal of

ObjectOriented Programming pages June

Wad Philip Wadler Views A way for pattern matching to cohabit with data

abstraction In Proceedings of the Fourteenth Annual ACM Symposium on

Principles of Programming Languages pages Munich Germany

January

Zel John M Zelle Learning searchcontrol heuristics for logic programs Ap

plications tosp eedup learning and languageacquis iti ons Technical Rep ort

AI University of Texas Austin May

A Desugaring rules

The following rewrite rules desugar the highlevel syntax of Fig into the core

abstract syntax of Fig The rules are group ed by their intention such as

providing names for arbitrary expressions or breaking down comp ound predicate

abstractions

For brevity we omit the rewrite rules which introduce defaults for omitted

optional program fragments dummy variables for pattern variables Any sp e

cializers empty eld pattern sets in sp ecializers and when true and return

f g clauses Additional rules may b e introduced to simplify the resulting for

mula such as converting v Any to true and p erforming logical simplica

tion

V

n

For brevity we use fP g to stand for the conjunction of the terms

i

i

V

n

0 0

fP g stands for true Variables v and v P and and P When n

i n

i

i

are new variables which do not app ear elsewhere in the program Ceiling braces

de surround p otentially sugared expressions application of the rewrite rules

eliminates those braces

A Declarations

These rules move sp ecializers from formal lists into when clauses

dmetho d mv S v S when P Body e

1 1 n n

V

n

metho d mv v when f dv S eg and d P e Body

1 n i i

i=1

dpredicate p v S v S when P return ff E f E ge

1 1 n n 1 1 m m

predicate pv v

1 n

V

n

when fdv S eg and dP e dreturn ff E f E g e

i i 1 1 m m

i=1

metho dsig signature metho did h type i type

metho ddecl metho d metho did h formalpattern i

when predexpr metho db o dy

predsig predsignature predid h type i

return f h eldid type i g

preddecl predicate predid h formalpattern i when predexpr

return f h eldid expr i g

classierdecl classify h formalpattern i

h as predid when predexpr return f h eldid expr i g i

as predid otherwise return f h eldid expr i g

P Q predexpr expr sp ecializer succeeds if expr evaluates to a value

that satises sp ecializer

j test expr succeeds if expr evaluates to true

j let varid expr evaluate expr and bind varid

to its value always succeeds

j predid h expr i > f h eldpat i g

test predicate abstraction

j true always succeeds

j false never succeeds

j not predexpr negation

j predexpr and predexpr conjunction shortcircuited

j predexpr or predexpr disjunction shortcircuited

formalpattern varid sp ecializer like varid sp ecializer in predexpr

F eldpat eldid varid sp ecializer

S sp ecializer classsp ec f h eldpat i g

C classsp ec classid expr classid is a class test

j predid expr predid f g is sugar

for predid expr >f g

j not classsp ec succeeds if classsp ec do es not

j classsp ec classsp ec succeeds if b oth classsp ec s do

j classsp ec j classsp ec succeeds if either classsp ec do es

Fig Full extended abstract syntax for predicate dispatching The syntax is as pre

sented incrementally in Sect with the addition of the true and false predicate

expressions and the not and j class sp ecializers Words and symbols in b oldface

represent terminals Angle brackets denote zero or more commaseparated rep etitions

of an item Square brackets contain optional expressions Each predicate may b e dened

only once App B relaxes this restriction and recursive predicates are forbidden

A Naming of nonvariable expressions

The core language p ermits arbitrary expressions only in let bindings and uses

variable references elsewhere These rules introduce let bindings and are intended

to re only once alternately only if one of the E expressions is not a mere

variable reference lest the and predicate application rules cause an innite

lo op in desugaring

0 0

dE S e let v E and v S

0 0

d test E e let v E and test v

dpE E > f F F ge

1 n 1 m

V

n

0 0 0

E g and dp v v > fF F ge flet v

i 1 m

1 n

i

i=1

dreturn ff E f E ge

1 1 m m

V

m

0 0 0

and flet v E g return ff v f v g

i 1 m

m

i 1

i=1

A Comp ound predicate expressions

These rules show how to desugar false and comp ound predicate expressions

dfalsee not true

dnot P e not dP e

dP and P e dP e and dP e

1 2 1 2

dP or P e dP e or dP e

1 2 1 2

A Field bindings

Pattern matching p ermits arbitrarily nested tests and simultaneous matching

on elds of ob jects elds of predicate results and results of arbitrary metho d

invocations These rules separate these varieties of record patterns and atten

tests

We introduce the concept of a class sp ecializer generating a eld A class

name generates the elds in the class a predicate name generates the elds in

the predicates return clause a conjunction generates the elds generated by

either of its conjuncts and a disjunction generates the elds generated by b oth

of its disjuncts

If F is generated by C c for i m n

i

dv C fF F F ge

1 m n

dv C fF F ge and dv Any fF F ge

1 m m+1 n

dv c ff v S f v S ge

1 1 1 n n n

V

n

v c and flet v v f and dv S eg

i i i i

i=1

dv p ff v S f v S ge

1 1 1 n n n

V

n

0

pv > ff v f v g and f dv S eg

1 1 n n i

i=1

A Comp ound predicate abstractions

These rules simplify comp ound predicate abstractions

dv not CfF F ge not dv C fF F ge

1 m 1 m

If F m i n is generated by C rule only

i 2

dv C C fF F F ge dv C fF F ge

1 2 1 m n 1 1 m

and dv C fF F ge

2 m+1 n

dv C j C fF F ge dv C fF F ge

1 2 1 m 1 1 m

or dv C fF F ge

2 1 m

A Classiers

Sequential ordering over classier cases is enforced by creating extra predicates

d such that d is true if any c j i is true Each c is true only if d is not

i i j i i

that is no previous conjunct was true

classifyv S v S

1 1 m m

0 0

v g as c when P return ff v f

1 1 11 1m

1m 11

1

1

0 0

as c when P return ff v f v g

n n n1 nm

nm

n1

n

n

0 0

as c otherwise return ff v v f g

n+1 n+11 n+1m

n+11 n+1m

n+1

n+1

predicate c v S v S when P

1 1 1 m m 1

0 0

v g return ff v f

11 1m

1m 11

1

1

dpredicate d v S v S when P e

1 1 1 m m 1

predicate c v S v S when P and not d v v

2 1 1 m m 2 1 1 m

0 0

return ff v v f g

21 2m

21 2m

2

2

dpredicate d v S v S when d v v or P e

2 1 1 m m 1 1 m 2

predicate c v S v S when P and not d v v

n 1 1 m m n n1 1 m

0 0

return ff v f v g

n1 nm

n1 nm

n

n

dpredicate d v S v S when d v v or P e

n 1 1 m m n1 1 m n

predicate c v S v S when not d v v

n+1 1 1 m m n 1 m

0 0

v g return ff v f

n+11 n+1m

n+1m n+11

n+1

n+1

B Bindings escaping or

In the static and dynamic semantics presented in Sect bindings never escap e

from or predicate expressions Relaxing this constraint provides extra conve

nience to the programmer and p ermits more values to b e reused rather than

recomputed It is also equivalent to p ermitting overloaded predicates or mul

tiple predicate denitions so far we have p ermitted only a single denition

of each predicate With appropriate variable renaming multiple predicate def

initions that rely on a dispatchinglike mechanism to select the most sp ecic

applicable metho d can b e converted into uses of or and vice versa

For example the two ConstantFold metho ds of Sect can b e combined

into a single metho d Eliminating co de duplication is a prime goal of ob ject

oriented programming but the previous version rep eated the b o dy twice Use of

a help er metho d would unnecessarily separate the dispatching conditions from

the co de b eing executed though a help er predicate could reduce co de duplication

in the predicate expression

hand le case of adding zero to a nonconstant

method ConstantFoldeBinopExpr opIntPlus arga arga

when aIntConst valuev and testv

and notaIntConst and let res a

or aIntConst valuev and testv

and notaIntConst and let res a

increment counter or do other common work here

return res

As another example the LoopExit example of Sect can b e extended

to present a view which indicates which branch of the CFGsucc is the lo op

exit and which the backward branch When p erforming iterative dataow this

is the only information of interest and in our current implementation which

uses predicate classes Chab we generally recompute this information after

discovering that an ob ject is a LoopExit Presenting a view which includes this

information directly would improve the co des readability and eciency

predsignature LoopExitCFGnode

return loopCFGloop nextloopCFGedge nextexitCFGedge

predicate LoopExitnCFGsucc nexttrue t nextfalse f

when testtisloopexit and let nl t and let ne f

or testfisloopexit and let nl f and let ne t

return loop nlcontainingloop nextloop nl nextexit ne

Permitting bindings which app ear on b oth sides of or to escap e requires

the following changes to the dynamic semantics of Fig The third rule is

unchanged from Fig but included here for completeness

0

hP K i htrue K i

0

hP or Q K i htrue K i

0 00

hP K i hfalse K i hQ K i htrue K i

00

hP or Q K i htrue K i

0 00

hP K i hfalse K i hQ K i hfalse K i

hP or Q K i hfalse K i

These execution rules do not reect that only the bindings app earing on b oth

sides not all those app earing on the succeeding side should escap e however

the typechecking rules b elow guarantee that only the appropriate variables are

referenced

The static semantics of Fig are mo died to add two help er functions and

replace a typechecking rule

0 00 00

T t T T Least upp er b ound over types T is the least common

0

sup ertype of T and T

0 00

t Pointwise lub over typing environments For each v

env

00 0

dom dom dom if j v T and

0 0 00 0

j v T then j v T t T

0 00 0 00 000

P P t

env

000

P or P

Finally canonicalization must account for the new semantics of or In order

to p ermit replacement of variables by their values we introduce a new compile

timeonly ternary conditional op erator for each variable b ound on b oth sides

of the predicate The rst argument is the predicate expression on the lefthand

side of the or expression the second and third arguments are the variables

values on each side of the or

Canonicalizing this new expression requires ordering the tests canonically

any ordering will do This may necessitate duplication of some expressions such

as transforming b e a e e into a b e e b e e so that those

two expressions are not considered distinct With these two mo dications the

tautology test is once again sound and complete