<<

A Temporal- Approach to Binding- Analysis

Rowan Davies Carnegie Mellon University Department Pittsburgh PA 15213, USA [email protected]

Abstract languages that include binding-time annotations, as for example by Nielson and Nielson [14] and Gomard and The Curry-Howard isomorphism identifies proofs with Jones [9]. However, the motivation for the particular typing

typed -calculus terms, and correspondingly identifies rules that are chosen is often not clear. There has been some propositions with types. We show how this isomorphism work, for example by Palsberg [15], on modular proofs that can be extended to relate constructive temporal logic with binding-time analyses generate annotations that allow large binding-timeanalysis. In particular,we show how to extend classes of partial evaluators to specialize correctly. How-

the Curry-Howard isomorphism to include the (“next”) ever this still does not provide a direct motivation for the

operator from linear-time temporal logic. This yields the particular rules used in binding-time type systems. simply typed -calculus which we prove to be equiva- In this paper we give a logical construction of a binding- lent to a multi-level binding-timeanalysis like those used in time typesystem based on temporal logic. Temporal logicis

partial evaluation for functional programming languages. an extension of logic to include proofs that formulas are valid

Further, we prove that normalization in can be done at particular . The Curry-Howard [11] isomorphism in an order corresponding to the times in the logic, which

relates constructive proofs to typed -terms and formulas to

explains why is relevant to partial evaluation. We then types. Thus, we expect that extending the Curry-Howard

extend to a small functional language, Mini-ML , and isomorphism to constructive temporal logic should yield a give an operational semantics for it. Finally, we prove that

typed -calculus that expresses that a result of a particular this operational semantics correctly reflects the binding- type will be available at a particular time. This is exactly times in the language, a theorem which is the functional what a binding-time type system should capture. programming analog of time-ordered normalization. Many different temporal and many different tem- poral operators have been studied, so we need to determine exactly which are relevant to binding-time analysis. In a 1. Introduction binding-time separated program, one stage in the program can manipulate as data the code of the following stage. At Partial evaluation [12] is a method for specializing a pro- the level of types this suggests that at each stage we should gram given part of the program’s input. The basic technique have a type for code of the next stage. Thus, via the Curry- is to execute those parts of the program that do not depend Howard isomorphism we are led to consider the temporal

on the unknown data, while constructing a residual program logic operator, which denotes truth at the next stage, i.e.

A A from those parts that do. Offline partial evaluation uses a is valid if is valid at the next time. Further, since binding-time analysis to determine those parts of the pro- temporal logics generally allow an unbounded number of gram that will not depend on the unknown (dynamic) data, “times”, they should naturally correspond to a binding-time regardless of the actual value of the known (static) data. analysis with many levels, such as that studied by Gl¨uck and Binding-time analyses are usually described via typed Jørgensen [8]. The more traditional two-level binding-time analyses can then be trivially obtained by restriction. Also,  This work wasmostly completedduring a visit bythe author to BRICS in binding-time analysis we have a simple linear ordering (Basic Research in Computer Science, Centre of the Danish National Re- search Foundation)in the summer of 1995. It was also partly supported by of the binding times, so we consider linear-time temporal a Hackett Studentship from the University of Western Australia logic, in which each time has a unique time immediately following it. Putting this all together naturally suggests that binding-timetypesystems used in partial evaluation, such as

constructive linear-time temporal logic with and a type that of Gomard and Jones [9], allow manipulation of code system for multi-level binding-time analysis should be im- with free variables. Thus, the original motivation for the ages of each other under the Curry-Howard isomorphism. present work was to consider how to extend Mini-ML2 to a This does not seem to have been observed previously, and system that is a conservative extension of the binding-time in this paper we show formally that this is indeed the case. type systems used in partial evaluation. In this paper we The development is relatively straightforward and our main achieve that goal, though find that we also lose the features

interest is in demonstrating the direct logical relationship of Mini-ML2 beyond ordinary binding-time analysis. Our 2

between binding-time analysis and temporal logic. conclusion is that the 2 operator in Mini-ML corresponds

The structure of this paper is then as follows. In the toatypefor closed code, whilethe operatorinMini-ML following section, we start with a formu- corresponds to a type for code with free variables. Thus the

lation of intuitionistic linear-time temporal logic with two operators are suitable for different purposes, and which

and . Our system has a similar style to the modal sys- one is preferred depends on the context. This suggests that

tems of Martini and Masini [13]. We then verify that our a desirable direction for future work would be the design of operator is the same as that considered elsewhere by show- a type system correctly capturing both closed code and code

ing that adding negation and classical reasoning leads to a with free variables within a single framework.

system equivalent to L , an axiomatic formulation due to Stirling [17] for a small classical linear-time temporal logic

including .

We then apply the Curry-Howard isomorphism to the 2. A temporal -calculus

natural-deduction system, yielding the typed -calculus

withthe operator in thetypes. We givereduction rulesfor thiscalculus, and prove that normalizationcan be performed In this section we will show how to extend the Curry- in an order corresponding to the times in the logic. This

Howard isomorphism to include the (“next”) operator theorem gives an abstract explanation for why is relevant from temporal logic. In order to do this, we give a natural-

to partial evaluation. deduction system for an intuitionistic linear-time temporal

m

In the second part of the paper we consider , which logic containing only and . We then show that our is essentially the -calculus fragment of the language operator is the same as the one usually considered in linear- used in the multi-level binding-time analysis of Gl¨uck and time temporal logics by adding inference rules for negation

Jørgensen [8]. We then construct a simple isomorphism and classical reasoning, and then proving equivalence to a

m between and that preserves typing, thus showing sound and complete axiomatic system given by Stirling[17]

that these languages are equivalent as type systems. We for the fragment of classical linear-time temporal logic con-

also give a correspondence between -reductions in the two taining only , and . We then add proof terms to our

languages. This gives some explanation for why languages original natural deduction system to yield a simply typed

m

like are relevant to partial evaluation. -calculus with the operator in the types.

Finally, we expand to a small temporal functional language Mini-ML , which is in many ways similar to a realistic binding-time type system. We give an operational semantics for this language, and then give a proof that this 2.1. Intuitionistic Temporal Logic semantics correctly reflects the binding times in the lan-

guage. This theorem is the functional programming analog of the time-ordered normalization theorem for . This subsection presents a simple natural-deduction for-

We conclude by giving example programs in Mini-ML mulation of an intuitionisticlinear-time temporal logic con- and discussing some practical concepts from binding-time taining only and . Our formulation uses a judge-

analysis. ment annotated with a natural number n, representing the

This work is similar to work by Davies and Pfenning [5] “time” of the conclusion, and with each assumption A in 2 which shows that a typed language Mini-ML based on Γ also annotated by a time n. These are just like the “lev- captures a powerful form of staged computa- els” in the modal natural-deduction systems of Martini and tion, including run-time code generation. They also show Masini [13], and in fact our system is exactly the same as that Mini-ML2 is a conservative extension of the two-level their rules for modal K, except that because of linearity we and (linearly ordered) B-level languages studied by Niel- do not need any restriction on the assumptions used in the

son and Nielson [14]. However, they note that this system introduction rule for . Our rules for the non-temporal onlyallows programs that manipulateclosed code, whilethe fragment are completely standard.

2 We are now in a positionto prove equivalence to a previ-

ously presented temporal logic. The following axioms and

n

A Γ

in inference rules, L , for the fragment of classical linear-

V

n

A Γ time temporal logic containing only , and are due to

Stirling[17] (page 516), who shows that they are sound and

n

n

Γ A A

1 2 complete for unravelled models of this logic. We choose I

this system as our starting point because it appears to be

n

A A Γ 1 2

the smallest linear temporal logiccontaining the operator n

n that has been previously considered in the literature.

A A A

Γ 1 2 Γ 1

E

n A

Γ 2 Axioms: L1 Any classical instance

A A

L3

n +

n 1

Γ A

(A A ) (A A ) A

Γ L4 1 2 1 2

E

I

n +

n 1

Γ A

Γ A

A A A

Inference rules: MP if A1 2 and 1 then 2

A RO if A then

In order to give a proof-theoretic semantics to the

operator we also need to consider a proof reduction rule for Note that in the inference rules, we require that there be

I E immediately followed by , which reduces trivially proofs from no assumptions.

to the derivation with both inference steps removed. The following theorem shows that our operator is the same as the one usually considered in linear-time temporal 2.2. Comparison with a previous temporal logic logic.

0 A

We now need to verify that the natural-deduction sys- Theorem 1 We can derive in the extended natural-

tem presented the previous section really does present the deduction system if and only if there is a proof of A in L .

same operator as other linear-time temporal logics. In- formally, it is not difficult to see how these rules correspond Proof: (sketch) In one direction, we construct a derivation

to a with a linear reachability relation. for each axiom and proceed by induction over the inference

However, rather than give a formal proof of soundness and rules in L . For L1we actuallysimplynoticethat removing completeness with respect to such a semantics, we instead the rules for yields a standard natural-deduction system show equivalence to a previously presented temporal logic. for pure classical logic. The other axioms are straightfor- Unfortunately, intuitionistic temporal logics do no seem ward, and the case for the inference rule RO only requires to have been considered previously, nor temporal logics showing that incrementing every time annotation in a deriva- without negation. Thus we add classical reasoning and nega- tion yields a derivation. tion to our natural deduction system to make this compari- We prove the other direction by inductionover the struc- son, even though they are not directly relevant to binding- ture of derivations, strengthening the induction hypothesis time analysis. We thus add the following inference rules to to:

those above:

n n n

1 k

A A if A

1 k

n n n

n n

1 k

A A A

p Γ A k

(p a variable not then 1

p

I

L Γ A is provable in

n occuring in or )

Γ A

n

n

Here means occurrences of . Only the cases n

Γ n A Γ A

for the and rules are non-trivial. They are solved by

E

0

n B

Γ repeated application of L3, L4 and the converse of L4 (which

is derivable using L3, L4 and a classical tautology) along

n

n

A A Γ with a sequence of cuts (which are classical tautologies).

C

I

n For example, in the case for , we have by the induc- Γ

A tion hypothesis that

0 n 0 n n

These rules are relatively standard, except for the addition n

A A A A

1 m 1 2 of the time annotations.

Note that by presenting the operator using only an We can also deduce that

introductionrule and elimination rule in the original system

n n n

A A ) (A A ) we have separated it from negation and classical reasoning. ( 1 2 1 2

3 by repeated application of the converse of L4. We also have the following for elimination followed by

Now, by using the cut-formula (which is a classical tau- introduction, analogous to -reduction:

tology)

M ) M

next(prev

n 0 n 0 n n

( A A A A )

1 m 1 2

n n n

(( A A ) (A A ))

1 2 1 2 2.3.4 Time-ordered normalization

n 0 n 0 n

( A A (A A ))

1 m 1 2

Γ n M A

Suppose we have : . Then we say that thetyping

0 0

M M and MP twice, we get the required result. derivation associates a time n with the subterm of

if the corresponding sub-derivation of the typing derivation

0

n

0 0

Γ0 M A

has the form : . Note that reduction preserves 2.3. A temporal -calculus the time of subterms. Also, since -redices are sub-terms, this definition associates a time with each one, and this time

We now add proof terms to the original intuitionistic will be the same as that associated with both the body of the

temporal-logic natural-deduction system. This yields , and the argument.

a simply typed -calculus with the operator in the types, Now, a fundamental property of is that we can reduce

by the natural extension of the Curry-Howard isomorphism. -redices in the order of their associated time, provided

we reduce all temporal redices between -reductions. In

2.3.1 Syntax doing so, each reduction cannot lead to -redices with an earlier time. We refer to this property as “time-ordered

normalization”, and prove it below.

= b j A A j A

Types A :: 1 2

This propertyexplains why is relevant to partial eval-

= x j x A M j M M

Terms M :: : 0 1

uation. If we have a term in , then we know that -

M j M j next prev

n reduction can be done in stages corresponding to the times

j Γ x A Contexts Γ ::= : inthetemporal logic. Thisisvery closelyrelated tobinding- time correctness in a functional language, which we will 2.3.2 Typing rules

discuss in the next section.

M A

Γ n Expression has type M A

: Theorem 2 (Time-ordered normalization) Suppose we

n Γ

at time in context . Γ n M A M

have : , where has no temporal redices and no

0

n

-redices with time less than . Then reducing a -redex 0

with time n and then reducing all temporal redices leads a

n

x A Γ

: in 0 n

term which also has no -redices with time less than .

V

n

x A

Γ :

0

[M ]

In theproof we make use of the standard notation C

0

n

n C

to indicate the term where M appears in the context .

Γ x A M A

: 1 : 2

I

n

C [(x A M )M ]

Proof: We have M : 0 1

x A M A A

Γ : : 0

1 1 2 0

0

n n

n 0

0 Γ A M A M A

with Γ x: 0 : 0 and 1 : 1.

0

n n

M C [fM xgM ]

M A A M A

Γ 0 : 1 2 Γ 1 : 1 We reduce to 1 0 and then reduce all

E

n temporal redices.

Γ M A M

0 1 : 2 0 n Suppose there is a -redex with time less than in the

n result. Then we have one of two cases: +

n 1

M A

Γ Γ : M A

0 00 00

: 0

M C [C [fM xgM ]M ] C [fM xgM ]

E I

1. 1 0 2 with 1 0

n

n+

1 0

Γ M A

y A M

Γ M A

next : prev : reducing to : 0 by temporal reductions. But then

00

C cannot be the identity since then the resulting -redex

0 has time n . Nor can it begin with a , since then there is

2.3.3 Reduction rules 0

n M

-redex with time less than in . Also, by the typing, 00

C cannot begin with next. Hence, it must begin with prev.

We have the standard -reduction rule as well as the fol-

00 i

lowing temporal reduction rules. The first comes from the Continuing this argument, we see that C prev . But,

i 0

M x]M (t A M )

natural-deduction proof-reduction rule, analogously to the then [ 1 0 next : 0 , and the resulting

0 0

+ i n redex has level n , which is not less than .

correspondence between -reduction and the proof reduc-

0 00 00

M x]M C [C [M ]M ] C [M ] 2. [ 1 0 1 2 with 1 reducing

tion rule for :

0 A M

to y : 1 by temporal reductions. By an almost identical

M ) M prev (next argument to the above, this is impossible.

4

3. Equivalence to a binding-time type system 3.3. Equivalence translation

We now demonstrate the relationship between and We now give simple translations between well typed

m

binding-time type systems considered by other authors. To terms in and . The translation from maps terms

m

do this we consider , a simply typed -calculus which is which are in the same equivalence class with respect to m

essentially the core of standard binding-time analyzes used temporal reductions to the same term. In the other di-

m

in offline partial evaluation (see e.g. Gomard and Jones [9]). rection, we always translate terms to a terms with m

additionally allows more than two binding times in the no temporal redices, these being unique representatives of

same way as the multi-level binding-time analysis of Gl¨uck the equivalence classes. Note that we can always reduce all

m and Jørgensen [8]. Our formulation of is basically the - temporal redices, since the number of reductionsis bounded calculus fragment of Gl¨uck and Jørgensen’s system, though by thenumber of next and prev constructors. We then show

it has some important differences. We use separate syntactic that the two translations preserve typing and are inverses of

categories for the types of each level, thus avoiding side each other when restricted to terms with no temporal

m conditions regarding well-formedness of types. Further, we redices. This shows that is isomorphic to modulo

do not treat the final level as dynamically typed, but consider the temporal reductions.

n n k k the whole program to be statically typed. Finally, we do not The translationsare given by the functions j j and include “lifting” from one binding time to a later one, but defined as follows:

instead demonstrate later how this can be easily added.

m We then give a simple translation between and . Type Translations

This translation is a bijection on terms and types that pre-

n n

b j = b

serves typing, modulo reduction of temporal redices. Thus j

n n n n n n n n

m j j = j j j j

and are equivalent as type systems, modulo these 1 2 1 2

+ n n+ n+

n 1 1 1

j = j j

trivial reductions. j

n n

bk = b

3.1. Syntax k

n n n n

A k = kA k kA k A

k 1 2 1 2

n+

n 1

k Ak = kAk n

We use the separate syntactic categories to indicate

the type of results which will be available at time n or later.

n Term Translations

The time annotations on base types b and function types

n n n

n

1 2 indicate the time at which the corresponding n

jx j = x

n n n n n n

values are available. The time annotations on terms indicate n

x E j = x j j jE j

j : :

n n n

the time at which the or @ (application) are reduced, and n

jE j = jE j jE j

0@ E1 0 1

n m n+

the corresponding variable substituted for. See Gl¨uck and m 1

m n) jE j = jE j

( next

n+ m n

Jørgensen [8] for a semantics of evaluation of multi-level m 1

m n + ) jE j = jE j ( 1 prev

terms in multiple stages.

n n

n

kxk = x

n n n n+

n 1

= b j j

Types ::

n n n n

1 2 n

kx A M k = x kA k kM k

n n n n

n : :

E = x j x E j E

Terms :: : 0 @ E1

n n n n

kM M k = kM k kM k n

n 0 1 0 @ 1

j Ψ x

Contexts Ψ ::= :

n+

n 1

M k = kM k

knext

+ n

n 1

M k = kM k

3.2. Typing rules kprev m

Here we use E as convenient syntax matching all ex-

pressions which have the top constructor annotated with m.

n n

Ψ

x : in n

tpm var n

j j k k

m Lemma 3 and are inverses on the fragment of

n n

Ψ x

:

with no next-prev redices.

m

n n n

Ψ x E : 1 : 2

tpm lam Proof: By a straightforward induction.

n

m

n n n n n

Ψ x E : :

1 2 Theorem 4 The two translations preserve typing, namely:

n

m m

n n n

Ψ E Ψ E

0 : 1 2 1 : 1 m 0 0 0 0 0

E jM j j j

tpm app if : then :

m

n n

E E Ψ @ :

0 1 2 0 m 0 0

M A kM k kAk if : then :

5 Proof: By a straightforward structural induction, strength- that the operational semantics is fundamental in that it gives ening appropriately to: meaning to the binding-times. We claim that other methods for interpreting the binding-times can generally be formu-

lated as binding-time preserving transformations in a lan-

m n

n n n

Ψ E jΨj jM j j j if : then : guage like Mini-ML . For example, the generation of spe-

cialization points in a partial evaluator like Similix (see [1]

n m

n n

Γ M A kΓk kM k kAk if : then : or [12]) can be expressed as adding memoizing functions to the binding-time separated program. The semantics of the binding-time analyzed program is then the composition of these binding-time preserving transformations with a se-

mantics like the one we give.

n n

kM k = E M jE j

Lemma 5 If then using only m We could similarly extend instead of to get temporal reductions. a functional language syntactically very similar to other

binding-time type systems. We choose instead to start with

Proof: By induction on M. because we wouldlike to have a language which is syn-

tactically suitable for manually programming with binding- m

times. A language based on would require the pro-

m

We can now define -reduction in as the image of grammer to annotate every construct in a program with a

-reduction in under the translation, namely: time, which would be very tedious and make programs hard to read. Normally binding-time type systems are only used

an output language for a binding-time analysis, so ease of

n n n n n

( x E ) [E x ]E E : 0 @ 1 1 0 programming isn’t an issue. Mini-ML issuitable for man-

ually programming with binding-times, as the examples at

n

M k = E

Then, using the above lemma, if k and the end of this section demonstrate. It is interesting to

0 note that next and prev are very similar to the quasi-quoting

E M M E then 1 using only temporal reductions,

mechanism in the popular programming languageLisp, thus

0 0 n 0

M kM k = E

and M1 with . Informally, this means furthersupportingthe claim that they are natural way for the

m

that reductions correspond exactly between and . programmer to provide binding-time information.

m

At this stage, we can consider and to be equiv-

alent except for the temporal reductions in which are The motivation for supporting manual programming is

m

hidden by the syntax in . Thus expresses binding- to avoid an almost universal problem in automatic partial

m m times in the same way as . Conversely, can be evaluation, namely that generation of code is not guaranteed considered as proof terms for our temporal logic, with an to terminate. By allowing the programmer to have direct alternative, equivalent syntax for formulas. This justifies control over binding-times in a language with a well de- our claim that the core of binding-time type systems are fined semantics, we can place the responsibility of ensuring the image of a temporal logic under the the Curry-Howard termination on the programmer. Welinder [18] has demon- isomorphism. strated that this style of programming, called hand-writing generating extensions, can be very fruitful. Some of the benefits of automatic binding-time analysis might then be 4. A temporal functional language regained by allowing the temporal term constructors to be implicit coercions in a system of sub-typing, in the style of

Breazu-Tannen et.al. [2], leading to a refinement type sys-

We now show how to extend to obtain Mini-ML , a tem [6] where each refinement of a type is obtained by some small functional language in the style of [3], which includes

insertions of . The practicality of this idea has yet to be next, prev and to allow expression of binding-times. properly investigated. We give an operational semantics for this language, and then prove type preservation and value soundness. We also Our language Mini-ML includes pairs, natural num- demonstrate that this operational semantics correctly reflects bers, and fixed-points. We omit polymorphism, but claim the binding-times. that it can be added with some minor complications to the Often in partial evaluation the binding-time type system proofs that follow. Mini-ML is explicitly typed, since is only used to generate binding-time information which we do not treat type inference here, although note that type guides a specializer, and no operational semantics is given inference for next and prev can be handled easily using directly to the binding-time language. Here we consider unification.

6 4.1. Syntax 4.3. Operational Semantics

We now present the operational semantics of Mini-ML .

= j A A j A A j A Types A :: nat

1 2 1 2 The intuitionfor this semantics is that parts of the term with

= x j x A e j e e Terms e :: :

1 2 time 0, the current time, should be evaluated now, while

x A e j fix :

those at later times should be delayed until then. This leads

e e i j e j e j h fst snd

1 2 to tworulesforeach non-temporalconstructin thelanguage.

j e z j s 0

The values, v , are the standard ones for a Mini-ML like

( e e x e ) j |

case 1 of z 2 s 3 1 1 v

language, with the addition of next v , where includes

e j e j next prev all expressions with no sub-term at time 0. The operational

n semantics allows for manipulationof expressions containing

j Γ x A Contexts Γ ::= : free variables, provided the variables have time greater than 4.2. Typing Rules 0, and we thus depend on the fact that substitution avoids

variable capture.

In this section we present typing rules for Mini-ML . The operational semantics for is similar to the spe- cialization logic presented by Hatcliff [10] for a two-level The typing judgement has the form:

binding-time language, and our binding-time correctness

e A n

Γ n Term has type at time theorem is also somewhat similar to Hatcliff’s. e A : in context Γ. Values

0 0 0 0 1

= x A e j hv v i j j v j v

v :: : 1 2 z s next

n+ n+

+ n+

n 1 1 1 1

= x j x A v j v v

v :: : 1 2 +

n 1

x A v

-calculus Fragment j fix :

n+ n+

+ n+

1 1 n 1 1

v v i j v j v

j h fst snd

n n

n 1 2

Γ x A e B

x A Γ +

: in : : n 1

j v

tpt var tpt lam j z s

n

n

+ n+ n+

n 1 1 1

Γ x A

Γ x A e A B

( v v x v )

: : : j case 1 of z 2 | s 3 +

n 2 v

j next

n n

e A B Γ e A n

Γ 0 : 1 :

v (n )

tpt app j prev 0

n

e e B

Γ 0 1 :

n n

Expression e with time

e v

Mini-ML Fragment evaluates to value v .

n n

A e A Γ x: :

-calculus Fragment, time 0

x tpt

n

x A e A Γ fix : :

ev lam n

n Γ 0 e A e A

Γ 1 : 1 2 : 2

A e x A e

x: :

tpt pair

n

Γ he e i A A

1 2 : 1 2 0 0 0

0 0

e x e e v [v x]e v

1 1 2 2 2 1 n

Γ n Γ ev app e A A e A A

: 1 2 : 1 2 0

tpt fst tpt snd

e v

e1 2

n n

e A Γ e A

Γ fst : 1 snd : 2

n

e Γ

: nat -calculus Fragment, time n+1

tpt z tpt s

n n

Γ e Γ z : nat s : nat

ev var0

n n n n +

n 1

e e e A Γ x A

Γ 1 : nat Γ 2 : :nat 3 :

x x

case tpt

n

Γ ( e e x e ) A +

case 1 of z 2 | s 3 : n 1

e v

ev lam0 +

n 1

A e x A v

Temporal Fragment x: :

n+ n+

n 1 1 +

n 1

Γ e A

e v e v

:

e A Γ : 1 1 2 2

tpt next tpt prev ev app0

n +

n 1 +

n 1

Γ e A

e A

next : Γ prev :

e v v e1 2 1 2

7

Mini-ML Fragment, time 0 Temporal Fragment +

n 1

v

e ev next

n

v next e next 0

0

x ex]e v

[fix

v e next ev fix ev prev

0 1

x e v

v fix prev e

0 0 +

n 1

e v e v

1 1 2 2

e v ev pair ev prev0

0 +

n 2

he e i hv v i

v 1 2 1 2 prev e prev

0 0

e hv v i e hv v i 1 2 1 2 ev fst ev snd Theorem 6 (Determinacy)

0 0

v e v

fst e 1 snd 2

n

n

v v v

0 1. If e then has the form .

e v n

ev z ev s n

0 0

e e v = v v v

0 0 2. If and then (modulo renaming

e v z z s s of bound variables).

0 0

e v e1 z 2 ev case z Proof: By straightforward inductions over the structure of

0 n

e e x e ) v

( | v case 1 of z 2 s 3 the derivation of e .

0 0

0 0

e v [v x]e v 1 s 1 1 3 Theorem 7 (Type and Time Preservation) ev case s

0

n

n

e e x e ) v

(case 1 of z 2 | s 3

v Γ e A Γ

1. If e and : with not containing any

n

v A

bindings of variables at time 0, then Γ : .

0 n 2. Further, if a term constructor in e has time as- sociated with it by the original typing proof and it

gives rise to a term constructor in v (via substitution,

Mini-ML Fragment, time n+1 the rule ev lam, or a rule for time m+1) then that 0

term constructor has time n associated with it by the

typing proof for v .

Proof: By a straightforward induction over the structure of

n +

n 1

e v

v e the derivation of , using an appropriate substitution

ev fix0 lemma. +

n 1

x v

fix x e fix

n+ +

1 n 1

Γ v A Γ

+ n+

n 1 1 Lemma 8 If : with not containing any

e v e v n n 1 1 2 2 0

0 Γ v A

ev pair bindings of variables at time 0, then : , where

0 +

n 1 Γ is obtained from Γ by reducing the time on each variable

e e i hv v i h 1 2 1 2

binding by one.

n+ +

1 n 1

e v v e 0

ev fst0 ev snd Proof: By induction on the structure of the typing deriva-

+ n+

n 1 1

v e v

fst e fst snd snd tion. +

n 1

v

e 0

0 0

e A

ev z ev s Theorem 9 (Binding-time correctness) If :

n+ +

1 n 1 0 0

0 0

e v v v v A

e v

z z s s and then has the form next and : .

+ n+ n+

n 1 1 1 0

e v e v e v

v A

1 1 2 2 3 3 Proof: By type preservation, : . But then 0

ev case 0

v v +

n 1 next is the only form that the value could take in this

e e x e ) ( |

case 1 of z 2 s 3 typing derivation. Then, applying the above lemma gives

v v x v ) (case of z | s

1 2 3 0 0

v A : .

8

Binding-time correctness in Mini-ML is very closely the variable for variable redices in the result of applying

related to time-ordered normalization in . The binding- to the first argument. This program has no counterpart in

time correctness theorem means that we can evaluate a pro- Mini-ML2 , since it requires evaluation with code contain-

2

n

A n + gram in Mini-ML with type in 1 stages cor- ing free variables, which Mini-ML allows but Mini-ML

responding to the times in the typing derivation, and if all does not. This illustratesthe main reason why Mini-ML is 2

stages terminate the result will have type A. Each stage interesting compared to Mini-ML . However, note that the except the last involves evaluating the term to a value of the Mini-ML2 has other features not supported by Mini-ML ,

1 1 v form next v and then continuing the next stage with . namely an operator expressing immediate evaluation of

Now, by the time preservation property, at stage i the code, and sharing of code between stages. As an exam-

constructors with time 0 (under the associated typing proof) ple of this, the staged inner product example in [5] has no

are images of those with time i in the original term, and counterpart in Mini-ML . these are the ones for which real evaluation occurs during Abstractly, the reason for these differences is that the stage. Further, the result of each step except the last has Mini-ML2 only allows manipulation of closed code, thus

1 the form next v , which cannot contain any constructors disallowing some programs, while Mini-ML allows ma- with time 0 and so all evaluation corresponding to sub-terms nipulation of code with free variables, thus making imme-

with time i has been done. Thus, our operational semantics diate evaluation of code and sharing of code between stages correctly captures binding-times. unsafe. Even more abstractly, the reason for these differ- ences is that the Kripke semantics of the modal logic S4 4.4 Examples on which Mini-ML2 is based is reflexive and transitive,

while the Kripke semantics of the temporal logic on which

We now give some examples of programs in Mini-ML . Mini-ML is based is linear. The first is a very common toy example from partial evalua- As another example program in Mini-ML , we note tion, namely the power function where the exponent has an that realistic binding-time analyses include the automatic earlier binding-time than the index. We give two different insertionof a “lift” operator at least at base types. The “lift”

versions and compare them. In both we assume a function operator is essentially a coercion from one time to a later

times : nat nat nat which multiplies two numbers. one. We now show how to define a function in with

type nat nat which performs this coercion, exactly

p ( )

power fix :nat nat nat following [5]:

n

n:nat case

(x )

f

of z next :nat s z liftnat fix :nat nat

m (x x

x

| s next :nat times x:nat case

( (p m) x))

prev of z next z

0 0

( ( (f x )))

| s x next s prev

(x )

power z next :nat s z

A

A similar term of type A that returns a next’ed

) (x x ((x )x))

power (s z next :nat times :nat s z copy of its argument will generally exist for each base type,

( )) (x x

power (s s z next :nat times and inductively for pairs. This justifies the inclusion of the

x x ((x )x))x)) (( :nat times :nat s z lift primitive for base types in binding-time type systems such as that of Gomard and Jones [9] and, in a more real-

0 istic version of our language, we would also include it as a

n (x ( power :nat next :nat prev

primitive. Note that we also have the following term with

p

(fix :nat nat

(A B ) (A B ) 0

0 type which allows a form of

n n :nat case

lift on functions:

( )

of z next s z

( x

| s m next times

A B (x A (f ( x)))

f : next : prev next

(p m)))) n)) (prev Formorediscussiononliftcoercionsinpartialevaluation,

0 including sum types, see Danvy [4].

(x ) power z next :nat s z

0 As an example of a more realistic program in an exten-

) (x x ( )) power (s z next :nat times s z

0 sion of Standard ML with temporal operators, we show the

( )) (x x ( x ( ))) power s (s z next :nat times times s z regular expression matcher example from [5]. The first version corresponds exactly to the one given Figure 1 shows a version of the regular expression by Davies and Pfenning [5] for the functional language matcher without temporal operators. It makes use of a con- Mini-ML2 based on the modal logic S4. The second avoids tinuation function that is called with the remaining input

9 if the current matching succeeds. The code assumes the following datatype declaration: (* val acc : regexp -> (string list -> bool) -> datatype regexp (string list -> bool) *) = Empty fun acc (Empty) k s = k s | acc (Plus(r1,r2)) k s = acc r1 k s orelse | Plus of regexp * regexp acc r2 k s | Times of regexp * regexp | acc (Times(r1,r2)) k s = | Star of regexp acc r1 (fn ss => acc r2 k ss) s | Const of string | acc (Star(r)) k s = k s orelse acc r (fn ss => if s = ss then false As in [5], we introduce a local function definition in else acc (Star(r)) k ss) s the case for acc (Star (r)) so that we can generate | acc (Const(str)) k (x::s) = specialized code by applying to the first argument. (x = str) andalso k s | acc (Const(str)) k (nil) = false Then, we can add in temporal constructors to get the staged program in Figure 2 with the following types (using (* val accept : regexp -> (string list -> bool) *)

O here to represent ) fun accept r s = acc r (fn nil => true | (x::l) => false) s val acc2 : regexp -> O((string list -> bool) -> (string list -> bool)) Figure 1. Unstaged regular expression val accept2 : regexp -> matcher O(string list -> bool)

This program is in fact identical to that in [5], except that

here we use ‘ for next and ˆ for prev. We can actually do

better than this in , by making the continuations static, and avoiding variable for variable redices, as shown in figure (* val acc2 : regexp -> O((string list -> bool) -> 3. This code effectively inlines continuations and applies (string list -> bool)) *) them to code representing the (dynamic) strings, which will fun acc2 (Empty) = ‘ fn k => fn s => k s | acc2 (Plus(r1,r2)) = ‘ fn k => fn s => contain free variables. ˆ(acc2 r1) k s orelse ˆ(acc2 r2) k s | acc2 (Times(r1,r2)) = ‘ fn k => fn s => 5. Conclusion ˆ(acc2 r1) (fn ss => ˆ(acc2 r2) k ss) s | acc2 (Star(r)) = ‘ fn k => fn s => We have demonstrated that the image of a small temporal let fun acc2Star k s =

k s orelse logic under the Curry-Howard isomorphism, , provides ˆ(acc2 r) a logical construction of a binding-time type system that is (fn ss => if s = ss then false equivalent to the core of those used in partial evaluation. else acc2Star k ss)

s

We have shown that normalization in can be done inthe in

order of the times in the logic, thus giving an explanation acc2Star k s

for why is relevant to partial evaluation. end

| acc2 (Const(str)) = ‘ fn k => Further, we have shown how to extend to get a small temporal functionallanguage Mini-ML which is very sim- (fn (x::ss) => (x = ˆ(lift_string str)) ilar to a realistic binding-time type system. In particular, andalso k ss Mini-ML allows programs that manipulate code with free | nil => false) variables, and we give an operational semantics which re- (* val accept2 : regexp -> flects this. This is in contrast to work by Davies and Pfen- O(string list -> bool) *) ning [5] on Mini-ML2 , a typed language based on modal fun accept2 r = ‘ fn s => logic that also expresses a form of binding-times, though ˆ(acc2 r) (fn nil => true | (x::l) => false) s only allows programs that manipulate closed code. However, the manipulation of code with free variables comes at a price. Since Mini-ML does not express closed Figure 2. Temporally staged regular expres- code, it can not be directly extended with a construct like sion matcher that in Mini-ML2 that expresses immediate evaluation of generated code. Such a construct is essential in a language

10 that supports general forms of staged computation, and is the main novel feature of Mini-ML2 , so in future work we will consider how to construct a type system that captures both closed code and code with free variables. One possible direction for this work is based on the ob-

servation that manipulation of code with free variables is

allowed in because there is only a single successor stage

from any stage, which corresponds to the fact that is based on a linear-time temporal logic. In Mini-ML2 we allow each stage to have several successor stages in order to allow more general forms of staged computation, in partic- (* val acc3 : regexp -> ular run-time code generation and sharing of code between (O(string list) -> O bool) -> O(string list) -> O bool stages (see [5] for details). This means that when con- *) structing code in an arbitrary successor stage we cannot use fun acc3 (Empty) k s = k s variables that are bound further out in a possibly different | acc3 (Plus(r1,r2)) k s = successor stage. ‘(ˆ(acc3 r1 k s) orelse ˆ(acc3 r2 k s)) This suggests that to design a language which expresses | acc3 (Times(r1,r2)) k s = both closed code and code with free variables we could acc3 r1 (fn ss => acc3 r2 k ss) s explicitlyname stages and providean explicitquantifierover | acc3 (Star(r)) k s = them, rather than using next and prev to move between ‘let fun acc3Star s = ˆ(k ‘s) orelse stages. This is similar to the systems of labelled natural ˆ(acc3 r deduction of Gabbay and de Queiroz [7], which allow many (fn ss => ‘if s = ˆss then false different logics to be formulated including modal logics, else ˆ(acc3Star k ss)) s) thoughthisis stilla speculative directionfor futureresearch. in We have implemented type checkers for the languages

m acc3Star s and in the logic programming language Elf (see end Pfenning [16]). Using logic programming variables, the | acc3 (Const(str)) k s = ‘(case ˆs same programs will also perform type inference. We have of (x::ss) => also implemented the translations and proof of equivalence (x = ˆ(lift_string str)) between these languages in Elf. andalso ˆ(k ‘ss) | nil => false) 6. Acknowledgements (* val accept3 : regexp -> O(string list -> bool) *) fun accept3 r = The author gratefully acknowledges discussions with An- ‘ fn s => drzej Filinski, Flemming Nielson, Jens Palsberg, and Frank ˆ(acc3 r Pfenning regarding the subject of this paper. The author (fn s1 => ‘case ˆs1 of nil => true would also like to give special thanks to Olivier Danvy for | (x::l) => false) ‘s) motivating and inspiring this work. Finally, I would like to thank BRICS for offering a very stimulating and pleasant environment during my visit in the Figure 3. Better temporally staged regular ex- summer of 1995. pression matcher References

[1] A. Bondorf and O. Danvy. Automatic autoprojection of recursive equations with global variables and abstract types. Science of Computer Programming, 16:151–195, 1991. [2] V. Breazu-Tannen, T. Coquand, C. Gunter, and A. Scedrov. Inheritance as implicit coercion. Information and Computa- tion, 93:172–221, 1991. [3] D. Cl´ement, J. Despeyroux, T. Despeyroux,and G. Kahn. A simple applicative language: Mini-ML. In Proceedings of the 1986 Conferenceon LISP and Functional Programming, pages 13–27. ACM Press, 1986.

11 [4] O. Danvy. Type-directed partial evaluation. In Proceed- ings of the 23rd Annual ACM Symposium on Principles of Programming Languages, pages 242–257, Jan. 1996. [5] R. Davies and F. Pfenning. A modal analysis of stagedcom- putation. In Proceedingsofthe23rdAnnualACMSymposium on Principles of Programming Languages, pages 258–270, Jan. 1996. [6] T. Freeman and F. Pfenning. Refinement types for ML. In Proceedings of the SIGPLAN ’91 Symposium on Language Design and Implementation, Toronto, Ontario, pages 268– 277. ACM Press, June 1991. [7] D. M. Gabbay and R. J. de Queiroz. Extending the Curry- Howard interpretation to linear, relevant and other resource logics. Journal of Symbolic Logic, 57:1319–1365, 1992. [8] R. Gl¨uck and J. Jørgensen. Efficient multi-level generating extensions for program specialization. In S. Swierstra and M. Hermenegildo, editors, Programming Languages, Im- plementations, Logics and Programs (PLILP’95), volume 982 of Lecture Notes in Computer Science, pages 259–278. Springer-Verlag, Sept. 1995. [9] C. Gomard and N. D. Jones. A partial evaluator for the un- typed lambda-calculus. Journal of Functional Programming, 1(1):21–69, January 1991. [10] J. Hatcliff. Mechanically verifying the correctness of an of- fline partial evaluator. In S. Swierstra and M. Hermenegildo, editors, Programming Languages, Implementations, Logics and Programs (PLILP’95), volume 982 of Lecture Notes in Computer Science. Springer-Verlag, Sept. 1995. [11] W. A. Howard. The formulae-as-types notion of construc- tion. In J. P. Seldin and J. R. Hindley, editors, To H. B. Curry: Essays on Combinatory Logic, Lambda Calculus and For- malism, 1980, pages 479–490.Academic Press, 1980. Hith- erto unpublished note of 1969, rearranged, corrected, and annotated by Howard, 1979. [12] N. D. Jones,C. K. Gomard, and P.Sestoft. Partial Evaluation and Automatic Program Generation. Prentice Hall Interna- tional Series in Computer Science. Prentice-Hall, 1993. [13] S. Martini and A. Masini. A computational interpretation of modal proofs. In H. Wansing, editor, Proof Theoryof Modal Logics. Kluwer, 1996. To appear. [14] F. Nielson and H. R. Nielson. Two-Level Functional Lan- guages. Cambridge University Press, 1992. [15] J. Palsberg. Correctness of binding time analysis. Journalof Functional Programming, 3(3):347–363, July 1993. [16] F. Pfenning. Logic programming in the LF logical frame- work. In G. Huet and G. Plotkin, editors, Logical Frame- works, pages 149–181. Cambridge University Press, 1991. [17] C. Stirling. Modal and temporal logics. In S. Abramsky, D. M. Gabby, and T. S. E. Maibaum, editors, Handbook of Logicin ComputerScience,Vol. 2, chapter5, pages477–563. Oxford University Press, Oxford, 1992. [18] M. Welinder. Very efficient conversions. In E. T. Schubert, P. J. Windley, and J. Alves-Foss, editors, The 8th Interna- tional Workshop on Higher Order Logic Theorem Proving and Its Applications,AspenGrove,Utah, volume 971 of Lec- ture Notes in Computer Science, pages 340–352. Springer Verlag, September 1995.

12