g d plotkin - people.cs.uchicago.edu

133

Upload: others

Post on 21-Apr-2022

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: G D Plotkin - people.cs.uchicago.edu

A Structural Approach to Operational Semantics

G� D� Plotkin

University of Aarhus� Denmark

Page 2: G D Plotkin - people.cs.uchicago.edu

Contents

� Transition System and Interpreting Automata ���� Introduction � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Transition Systems � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Examples of Transition Systems � � � � � � � � � � � � � � � � � � � � � � � � � � � �

����� Finite Automata � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Three Counter Machines � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Context�Free Grammars � � � � � � � � � � � � � � � � � � � � � � � � � � � �

��� Labelled Transition Systems � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��� Interpreting Automata � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

����� The Language L � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������� The SMC�Machine � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

��� Exercises � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Bibliography � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

� Simple Expressions and Commands ����� Simple Expressions � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

����� L�Expressions � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Boolean Expressions � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

��� Simple Commands � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� L�commands � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� Structural Induction � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Dynamic Errors � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� Simple Type�Checking � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Static Errors � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� Exercises � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��� BIBLIOGRAPHICAL REMARKS � � � � � � � � � � � � � � � � � � � � � � � � � ������ Bibliography � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

� De�nitions and Declarations ����� Introduction � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� Simple De�nitions in Appllcative Languages � � � � � � � � � � � � � � � � � � � � ����� Compound De�nitions � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ����� Type�Checking and De�nitions � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

Page 3: G D Plotkin - people.cs.uchicago.edu

��� Exercises � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��� Remarks � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���� Bibliography � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ��

� Functions� Procedures and Classes ����� Functions in Applicative Languages � � � � � � � � � � � � � � � � � � � � � � � � � ����� Procedures and Functions � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Other Parameter Mechanisms � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Higher Types � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Modules and Classes � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ������ Exercises � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ���

A A GUIDE TO THE NOTATION ���

B NOTES ON SETS ��

Page 4: G D Plotkin - people.cs.uchicago.edu

Chapter �

Transition System and Interpreting

Automata

��� Introduction

It is the purpose of these notes to develop a simple and direct method for specifying the seman�tics of programming languages� Very little is required in the way of mathematical background all that will be involved is �symbol�pushing� of one kind or another of the sort which will al�ready be familiar to readers with experience of either the non�numerical aspects of programminglanguages or else formal deductive systems of the kind employed in mathematical logic�

Apart form a simple kind of mathematics the method is intended to produce concise com�prehensible semantic de�nitions� Indeed the method is even intended as a direct formalisationof �many aspects of� the usual informal natural language descriptions� I should really confesshere that while I have some experience what has been expressed above is rather a pious hopethan a statement of fact� I would therefore be most grateful to readers for their comments andparticularly their criticisms�

I will follow the approach to programming languages taken by such authors a Gordon�Gor� and Tennent �Ten� considering the main syntactic classes � expressions� commands anddeclarations � and the various features found in each� The linguistic approach is that developedby the Scott�Strachey school �together with Landin and McCarthy and others� but within anoperational rather than a denotational framework� These notes should be considered as anattempt at showing the feasibility of such an approach� Apart from various inadequacies of thetreatment as presented many topics of importance are omitted� These include data structuresand data types various forms of control structure from jumps to exceptions and coroutines concurrency including semaphores� monitors and communicating process�

Many thanks are due to the Department of Computer Science at Aarhus University at whoseinvitation I was enabled to spend a very pleasant six months developing this material� Thesenotes partially cover a series of lectures given at the department� I would like also to thank thesta� and students whose advice and criticism had a strong in�uence and also Jette Milwertzwhose typing skills made the work look better than it should�

Page 5: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

��� Transition Systems

The announced �symbol�pushing� nature of our method suggests what is the truth it is anoperational method of specifying semantics based on syntactic transformations of programsand simple operations on discrete data� The idea is that in general one should be interested incomputer systems whether hardware or software and for semantics one thinks of systems whosecon�gurations are a mixture of syntactical objects � the programs and data � such as stores orenvironment� Thus in these notes we have

SYSTEM � PROGRAM � DATA

One wonders if this study could be generalized to other kinds of systems� especially hardwareones�Clearly systems have some behavior and it is that which we wish to describe� In an oper�

ational semantics one focuses on the operations the system can perform � whether internallyor interactively with some suppersystem or the outside world� For in our discrete �digital�computer systems behavior consists of elementary steps which are occurrences of operations�Such elementary steps are called here� �and also in many other situations in Computer Science�transitions �� moves�� Thus a transitions steps from one con�guration to another and as a �rstidea we take it to be a binary relation con�gurations�

De�nition ������ A Transition System �ts� is �just�� a structure h����i where � is a set �ofelements� �� called con�gurations� and �� � � � � is a binary relation �called the transitionrelation�� Read � �� �� as saying that there is a transition from the con�guration � to thecon�guration ��� �Other notations sometimes seen are �� � and ���

���

����

����

����

����

�������

����������

����������

���

������

�����

�����

�����

���

��

���

��������

��������

��������

�����������

��������

��������

�������

������

���

�����

�����

��

������

���������

����������

����

������

������

������

����

����

����

������ ��

��

��

�����

����

����

��

���

���

������

������

�����

������

��������

��������������������������

��������������������������

�����

�������������������������� ��

������������������������

�������������

��������������������������

�������������

���

��������������������������

�������������

��������������������������

��

��������������������������

��������������������������

��������������������������

��������������������������

��������������������������

��������������������������

��

�������������

��������������������������

�������������������������� ��

������������������������ �

�������������������������

��������������������������

��������������������������

��������������������������

��

��������������������������

��������������������������

�������������������������� �������

�������������������

���������������������������������������

����

��������������������������

��������������������������

� ��

Fig� �� A Transition

Of course this idea is hardly new and examples can be found in any book on automata orformal languages� Its application to the de�nition of programming languages can be found inthe work of Landin and the Vienna Group ��Lan���Oll���Weg��

Page 6: G D Plotkin - people.cs.uchicago.edu

���� EXAMPLES OF TRANSITION SYSTEMS �

Structures of the form� h����i are rather simple and later we will consider several moreelaborate variants� tailored to individual circumstances� For example it is often helpful to havean idea of terminal �� �nal � halting� con�gurations�

De�nition ������ A Terminal Transition System �tts� is a structure h����� T i where h����iis a ts� and T � � �the set of �nal con�gurations� satis�es �� � T ��� � � � � ��� ���

A point to watch is to make a distinction between internal and external behavior� Internallya system�s behavior is nothing but the sum of its transitions� �We ignore here the fact thatoften these transitions make sense only at a certain level what counts as one transitions forone purpose may in fact consist of many steps when viewed in more detail� Part of the spiritof our method is to choose steps of the appropriate �size��� However externally many ofthe transitions produce no detectable e�ect� It is a matter of experience to choose the rightde�nition of external behavior� Often two or more de�nitions of behavior �or of having thesame behavior� are possible for a given transition system� Indeed on occasion one must turnthe problem around and look for a transition system which makes it possible to obtain anexpected notion of behavior�

��� Examples of Transition Systems

We recall a few familiar and not so familiar examples from computability and formal languages�

����� Finite Automata

A �nite automaton is a quintuplet �M � hQ��� �� q�� F i� where

Q is a �nite set �of states�

� is a �nite set �the input alphabet�

� � Q� � �� P�Q� �is the state transition relation�

q� � Q �is the initial state�

F � Q �is the set of �nal states�

To obtain a transition system we set

� � Q� ��

So any con�guration� � � hq� wi has a state component� q� and a control component� w� fordata�For the transitions we put whenever q� � ��q� a� �

hq� awi � hq�� wi

Page 7: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

�More formally� � � fhhq� awi� hq�� wii j q� q� � Q� a � �� w � ��� q� � ��q� a�g��The behavior of a �nite automaton is just the set L�M� of strings it accepts�

L�M� � fw � �� j q � F hq�� wi��hq� �ig

Of course we could also de�ne the terminal con�gurations by�

T � fhq� �i j q � Fg

and then

L�M� � fw � �� j � � T hq�� wi���g

In fact we can even get a little more abstract� Let h����� T i be a tts� An input function forit is any mapping in� I �� � and the language it accepts is then L��� � I where�

L��� � fi � I j � � T � in�i�����g

�For �nite automata as above we take I � ��� and in�w� � hq�� wi�� Thus we can easilyformalize at least one general notion of behavior�

Example� The machine�

���

�� ���� ��

���

���

���

���

���

���

� �start

���

p q r

A transition sequence�

hp� �����i� hq� ����i� hp� ���i� hq� ��i � hr� �i� hr� �i

����� Three Counter Machines

We have three counters� C� namely I� J and K� There are instructions� O� of the following fourtypes�

Increment� inc C � m

Decrement� dec C � m

Zero Test� zero C � m�n

Stop� stop

Page 8: G D Plotkin - people.cs.uchicago.edu

���� EXAMPLES OF TRANSITION SYSTEMS

Then program are just sequences P � O�� � � � � Ol of instructions� Now� �xing P � the set ofcon�gurations is�

� � fhm� i� j� ki j � � m � l i� j� k � Ng

Then the transition relation is de�ned in terms of the various possibilities by�

Case II� Om � inc I � m�

hm� i� j� ki � hm�� i � �� j� ki

Case ID� Om � dec I � m�

hm� i� �� j� ki � hm�� i� j� ki

Case IZ� Om � zero I � m��m��

hm� �� j� ki � hm�� �� j� kihm� i� �� j� ki � hm��� i � �� j� ki

and similarly for J and K�

Note � There is no case for the stop instruction�

Note � In case m� or m�� are � or � k the above de�nitions do not �of course�� apply�

Note � The transition relation is deterministic� that is�

��� ��� ��� � � �� �� � �� ��� � �� � ���

or� diagrammatically�

JJJJJJ�

�������

�� ������� ���

�Exercise � prove this��

Now the set of terminal con�gurations is de�ned by�

T � fhm� �� j� �i j Om � stopg

Page 9: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

and the behavior is a partial function f � N ��P

N where�

f�i� � j �def h�� i� �� �i���hm� �� j� �i � T

This can be put a little more abstractly� if we take for any tts h����� T i an input function�in � I �� � as before and also an output function� out � T �� O and de�ne a partial functionf� � I ��

PO by

f��i� � o � � in�i� ��� � � T o � out���

Of course for this to make sense the tts must be deterministic �why��� in the case of a three�counter machine we have���

��I � O � Nin�i� � h�� i� �� �iout�hm� i� j� ki� � j

Example� A program for the successor function� n �� n � �

������HHHHHH����

��HH

HHHH�

inc J

stopzero I

dec I

inc J

yes

no

����� Context�Free Grammars

A context�free grammar is a quadruple� G � hN��� P� Si where

N is a �nite set �of non�terminals�

� is a �nite set �the input alphabet�

Page 10: G D Plotkin - people.cs.uchicago.edu

���� LABELLED TRANSITION SYSTEMS

P � N � �N � ��� �is the set of productions�

S � N �is the start symbol�

Then the con�gurations are given by�

� � �N � ���

and the transition relation � is given by�

wXv � wxv �when X � x is in P �

Now the behaviour is just

L�G� � fw � T j S �� wg �T � ���

Amusingly� this already does not �t into our abstract idea for behaviours as sets �the one whichworked for �nite automata�� The problem is that was intended for acceptance where here wehave to do with generation �by leftmost derivations��

Exercise� Write down an abstract model of generation�

Example� The grammar is�

S �S � �S�S � SS

and a transition sequence could be

S � SS � �S�S � ��S � ���S�� ���SS��� �����S��� ��������

��� Labelled Transition Systems

Transition systems in general do not give the opportunity of saying very much about anyindividual transition� By adding the possibility of such information we arrive at a de�nition�

De�nition ���� A Labeled Transition System �lts� is a structure h�� A���i where � is a set �ofcon�gurations� and A is a set �of actions �� labels� operations�� and

�� � �� A� �

is the transition relation�

Page 11: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

We write a transitions as� �a�� �� where �� �� are con�gurations and a is an action� The

idea is that an action can give information about what went on in the con�guration during thetransition �internal actions� or about the interaction between the system and its environment�external actions� �or both�� The labels are particularly useful for specifying distributed systemswhere the actions may relate to the communications between sub�systems� The idea seems tooriginate with Keller �see �Kel���The idea of Labeled Terminal Transition Systems h�� A���� T i should be clear to the reader

who will also expect the following generalization of re�ective �resp� transitive� closure� For anylts let � and �� be con�gurations and take X � a�� � � � � ak in A

� �resp� A�� then�

X

��� �resp� �� �� �def ��� � � � � �k� �a��� ��� � � � �

ak�� �k � ��

where k � � �resp� k � ���

Example ��� Finite Automata �continued�� This time de�ne an lts by taking

� � Q

A � �

qa�� q� � q� � ��q� a�

T � F

Then we have L�M� � fw � A� j q � Tq�w��

�qg� The example transition sequence given

above now becomes simply�

p��� q

��� p

��� q

��� r

��� r � F

Example ��� Petri Nets� One idea of a Petri Net is just a quadruple N � hB�E� F�miwhere

B is a �nite set �of conditions�

E is a �nite set �of events�

F � �B � E� � �E � B� �is the �ow relation�

m � B �is the initial case�

A con�guration� m� is contact�free if

�e � E� �F���e� � m F �e� �m �� ��

Page 12: G D Plotkin - people.cs.uchicago.edu

���� LABELLED TRANSITION SYSTEMS ��

��

��

��

��

x x

x

QQQs

Q

QQ

QQQs

QQQ

a b

e

a� b�

A contact situation for m � a� a�� b

The point of this de�nition is that the occurence of an event� e� is nothing more than theceasing�to�hold of its precondition � � F���e�� and the starting�to�hold of its postconditions� � F �e�� in any given case� Here a case is a set of conditions �those that hold in the case�� Acontact�situation is one where this idea does not make sense� Often one excludes this possibilityaxiomatically �and imposes also other intuitively acceptable axioms�� We will just �somewhatarbitrarily� regard them as �runtime errors� and take

� � fm � B j m is contact�freeg

If two di�erent events share a precondition in a case� then according to the above intentionsthey cannot both occur at once� Accordingly we de�ne a con�ict relation between events by�

e�e� � �F���e� � F���e�� �� � e �� e��

An event can occur from a given case if all its preconditions hold in the case� What is �much�more� Petri Nets model concurrency in that several events �not in con�ict� can occur togetherin a given case� So we put

A � fX � E j �e� e� � X�e�e�g

and de�ne

mX�� m� � F���X� � m m� � �mnF���X�� � F �X�

Here is a pictorial example of such a transition

Page 13: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

�� �� �� ��

��

��

��

�� �� �� ��

x x x

x

x

x

��

��

��

��

��

���� QQQk

PPPi

� � � � � � �

� � � ����� PPPiQ

QQk��� PPP ��� PPP

� � � � � � � �

�����

Fig� �� A Transition

We give no de�nition of behavior as there does not seem to be any generally accepted one inthe literature� For further information on Petri Nets see ��Bra�� �Pet���

Of course our transitions with their actions must also be thought of as kinds of events evenmore so when we are discussing the semantics of languages for concurrency� We believe thereare very strong links between our ideas and those in Net Theory� but� alas� do not have timehere to pursue them�

Example Readers and Writers� This is a �partial� speci�cation of a Readers and Writersproblem with two agents each of whom can read and write �and do some local processing� butwhere the writes should not overlap�

Page 14: G D Plotkin - people.cs.uchicago.edu

���� INTERPRETING AUTOMATA ��

��

��

��

�� �� ��

��

��

�� xx

x x�

���

���I

� �

� �

���I

���I

���I

���

���

���R

���R

����

����

���

���

���

���

���

���

���

���

���

���

���

���

���

FR�

SR�

LP�

FW�

SW�

FW�

SW�

LP�

FR�

SR�

SWi is Start Writing iFWi is Finish Writing iSRi is Start Reading iFRi is Finish Reading iLRi is Local Processing iwhere � � i � �

��� Interpreting Automata

To �nish Chapter � we give an example of how to de�ne the operational semantics of a languageby an interpreting automaton� The reader should obtain some feeling for what ti possible alongthese lines �see the references given above for more information�� as well as a feeling that themethod is somehow a little too indirect thus paving the way for the approach taken in the nextchapter�

����� The Language L

We begin with the Abstract Syntax of a very simple programming language called L� What isabstract about it will be discussed a little here and later at greater length� For us syntax is acollection of syntactic sets of phrases each set corresponds to a di�erent type of phrase� Someof these sets are very simple and can be taken as given�

Page 15: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

Basic Syntactic Sets

Truthvalues This is the set T � ftt��g and is ranged over by �the metavariable� t �andwe also happily employ for this �and any other� metavariable sub� and super�scriptsto generate other metavariables� t�� t�� t

����k��

Numbers m� n are the metavariables over N � �� �� �� � � ��

Variables v � Var � fa� b� c� � � � � zg

Note how we have progressed to a fairly spare style of speci�cation in the above�

Derived Syntactic Sets

Expressions e � Exp given by

e ��� m j v j e � e� j e� e� j e� e�

Boolean Expressions b � BExp given by

b ��� t j e � e� j b or b� j �b

Commands c � Com given by

c ��� nil j v �� e j c c� j if b then c else c� j while b do c

This speci�cation can be taken� roughly speaking� as a context�free grammar if the reader justignores the use of the in�nite set N and the use of primes� It can also �despite appearances��be taken as unambiguous if the reader just regards the author as having lazily omitted bracketsas in�

b ��� t j e � e� j b or b� j �b

specifying parse trees so that rather than saying ambiguously that �for example��

while b do c c�

is a program what is being said is that both

������JJ

JJJJ

ZZZZZZZZ������

JJJJJJ �

����������� B

BBBBB��

����

������JJ

JJJJ

while b do

c c� while b do c

c�

and are trees�

Page 16: G D Plotkin - people.cs.uchicago.edu

���� INTERPRETING AUTOMATA ��

So we are abstract in not worrying about some lexical matters and just using for exampleintegers rather than numerals and in not worrying bout the exact speci�cation of phrases�What we are really trying to do is abstract away from the problems of parsing the token stringsthat really came into the computer and considering instead the �deep structure� of programs�Thus the syntactic categories we choose are supposed to be those with independent semantic

signi�cance the various program constructs � such as semicolon or while � � � do � � � � are theconstructive operations on phrases that possess semantic signi�cance�For example contrast the following concrete syntax for �some of� our expressions �taken

from �Ten���

hexpressioni ��� htermi j hexpressioni haddopi htermihtermi ��� hfactori j htermi hmultopi hfactorihfactori ��� hvariablei j hliterali j �hexpressioni�haddopi ��� � j �hmultopi ��� �hvariablei ��� a j b j c j � � � j zhliterali ��� � j � j � � � j

Now� however convenient it is for a parser to distinguish between hexpressioni� htermi andhfactori it does not make much semantic sense�Thus we will never give semantics directly to token strings but rather to their real structure�

However� we can always obtain the semantics of token strings via parsers which we regard asessentially just maps�

Parser� Concrete Syntax �� Abstract Syntax

Of course it is not really so well�de�ned what the abstract syntax for a given language is� andwe shall clearly make good use of the freedom of choice available�Returning to our language L we observe the following �dependency diagram��

��

�������R

C

B E

����� The SMC�Machine

Now we de�ne a suitable transition system whose con�gurations are those of the SMC�machine�

Value Stacks is ranged over by S and is the set �T � N � Var � BExp � Com��

Memories is ranged over by M and is Var �� N

Page 17: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

Control Stacks is ranged over by C and is

�Com � BExp � Exp � f�������� or��� ��� if �whileg��

The set of con�gurations is

� � Value Stacks �Memories� Control Stacks

and so a typical con�guration is � � hS�M�Ci� The idea is that we interpret commands andproduce as our interpretation proceeds� stacks C� of control information �initially a commandbut later bits of commands�� Along the way we accumulate partial results �when evaluatingexpressions�� and bits of command text which will be needed later this is all put �for somereason� on the value stack� S� Finally we have a model of the store �� memory� as a functionM � Var �� N which given a variable� v� says what its value M�v� is in the store�

Notation� In order to discuss updating variables� we introduce for a memory� M � integer� m�and variable v the memory M � �M �m�v� where

M ��v�� �

�m �if v� � v�M�v�� �otherwise�

So M �m�v� is the memory resulting from updating M by changing the value of v from M�v�to m�

The transition relation��� is de�ned by cases according to what is on the top of the controlstack�

Expressions

En hS�M� n Ci � hn S�M�CiEv hS�M� v Ci � hM�v� S�M�Ci

E���I hS�M� e

���e� Ci � hS�M� e e�

���Ci

E���E hm� m S�M�

���Ci � hn S�M�Ci

�where n � m���m��

Note� The symbols �� �� �� are being used both as symbols of L and to stand for thefunctions addition� subtraction and multiplication�

Page 18: G D Plotkin - people.cs.uchicago.edu

���� INTERPRETING AUTOMATA �

Boolean Expressions

Bt hS�M� t Ci � ht S�M�CiB�I hS�M� e � e� Ci � hS�M� e e� � CiB�E hm� m S�M�� Ci � ht S�M�Ci

�where t � �m � m���BorI hS�M� b or b� Ci � hS�M� b b� or CiBorE ht� t S�M� or Ci � ht�� S�M�Ci

�where t�� � �t � t���B�I hS�M��b Ci � hS�M� b � CiB�E ht S�M�� Ci � ht� S�M�Ci

�where t� � �t�

Commands

Cnil hS�M�nil Ci � hS�M�CiC��I hS�M� v �� e Ci � hv S�M� e �� CiC��E hm v S�M� �� Ci � hS�M �m�v�� CiC hS�M� c c� Ci � hS�M� c c� CiCifI hS�M� if b then c else c� Ci � hc c� S�M� b if CiCifE ht c c� S�M� if Ci � hS�M� c�� Ci

�where if t � tt then c�� � c else c�� � c��CwhileI hS�M�while b do c Ci � hb c S�M� b while CiCwhileE� htt b c S�M�while Ci � hS�M� c while b do c CiCwhileE� h� b c S�M�while Ci � hS�M�Ci

Now that we have at some length de�ned the transition relation� the terminal con�gurationsare de�ned by�

T � fh��M� �ig

and an input function in � Commands�Memories �� � is de�ned by�

in�C�M� � h��M�Ci

and out � T �� Memories by�

out�h��M� �i� �M

The behavior of the SMC�machine is then a partial function� Eval � Commands�Memories ��P

Memories and clearly�

Eval�C�M� �M � � h��M�Ci �� h��M �� �i

Page 19: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

Example Factorial�

y �� � while ��x � �� do

C �z �� �y �� y � x x �� x� �� �z �C

h�� h�� �i� y �� � Ci� h�� h�� �i� y �� � Ci by C � hy� h�� �i� � �� Ci by C �� I

� h� y� h�� �i� �� Ci by Em� h�� h�� �i� Ci by C��E� h��x � �� C �� h�� �i���x � �� whilei by CwhileI

� h��x � �� C �� h�� �i� �x � �� � whilei by E�I� h��x � �� C �� h�� �i� x � � � whilei by E�I

� h� ��x � �� C �� h�� �i� � � � whilei by Ev� h� � ��x � �� C �� h�� �i�� � whilei by Em

� h� ��x � �� C �� h�� �i�� whilei by E�E� htt ��x � �� C �� h�� �i�whilei by E�E

� h�� h�� �i� C � Ci by CwhileE�� h�� h�� �i� y �� y � x x �� x� � Ci by C �� h�� h�� �i� x �� x� � Ci�� h�� h�� �i� Ci�� h�� h�� �i� Ci�� h�� h�� �i� Ci� h��x � �� C �� h�� �i���x � �� whilei by CwhileI�� h� ��x � �� C �� h�� �i�whilei� h�� h�� �i� ��i by CwhileE�

Many other machines have been proposed along these lines� It is� perhaps� fair to say thatnone of them can be considered as directly formalizing the intuitive operational semantics tobe found in most language de�nitions� Rather they are more or less clearly correct on thebasis of this intuitive understanding� Further� although this is of less importance� they all havea tendency to pull the syntax to pieces or at any rate to wander around the syntax creatingvarious complex symbolic structures which do not seem particularly forced by the demandsof the language itself� Finally� they do not in general have any great claim to begin syntax�

directed in the sense of de�ning the semantics of compound phrases in terms of the semantics oftheir components� although the de�nition of the transition relation does fall into natural casesfollowing the various syntactical possibilities�

��� Exercises

Finite Automata

Let M � hQ��� �� q�� F i be a �nite automaton�

Page 20: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES �

� Rede�ne the behavior ofM so that it accepts in�nite strings a�a� � � � an � � �� that is so thatL�M� � �� �Hint� There are actually two answers� which can with di culty be provedequivalent��

� Suppose that � were changed so that the labeled transition relation had instead the form�

qa�� q�� q�

and F so that F � Q� �� What is the new type of �� How can binary trees like

����AA

AA����

AAAA

a

bc

d e

now be accepted by M�

� Suppose instead transitions occurred with probability so that we had

qa��pq�

with � � p � � and for any q and a�

�fp j qa��p

q� for some q�g � �

What is a good de�nition of behavior now�

� Finite automata can be turned into transducer by taking � to be a �nite set of transitionsof the form�

qv��w

q�

with v� w � ��� De�ne the relation qv��w

q� and the appropriate notion of behavior� Show

any �nite�state transducer can be turned into an equivalent one� where we have in anytransition that � � jvj � ��

Various Machines

� De�ne k counter machines� Show that any function computable by a k counter machineis computable by a ��counter machine� �Hint� First program elementary functions on the

Page 21: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

��counter machine including pairing� pair � N� �� N� and selection functions� fst� snd �N �� N such that�

fst�pair�m�n�� � msnd�pair�m�n�� � n

Then simulate by coding all the registers of the k counter machine by a big tuple held inone of the registers of the ��counter machine�� Show that any partial�recursive function�� one computable by a Turing Machine� can be computed by some ��counter machine�and vice�versa��

Consider stack machines where the registers hold stacks and operations on a stack ��element of ��� are pusha� pop� ishda �for each a � �� given by�

pusha�w� � awpop�aw� � w

ishda�w� �

�true �if w � aw� for some w��false �otherwise�

Show stack machines compute the same functions as Turing Machines� How many stacksare needed at most�

� De�ne and investigate queue machines�

� See how your favorite machines �Turing Machines� Push�Down Automata� �t into ourframework� For a general view of machines� consult the eminently readable� �Bir� or�Sco�� Look too at �Gre��

Grammars

� For CF grammars our notion of behavior is adapted to generation� De�ne a notion that isgood for acceptance� What about mixed generation!acceptance� Change the de�nitionsso that you get parse trees as behaviors� What is the nicest way you can �nd to handlesyntax�directed translation schemes�

� Show that for LL��� grammars you can obtain deterministic labeled �with �� transitionsof the form

wa�� w�

with w strings of terminals and non�terminals� What can you say about LL�k�� LR�k��

�� Have another look at other kinds of grammar too� e�g� Context�Sensitive� Type � �� arbi�trary� grammars� Discover other ideas for Transition Systems in the literature� Examplesinclude� Tag� Semi�Tue Systems� Markov Algorithms� �Calculus� Post Systems� Tag� L�Systems� Conway�s Game of Life and other forms of Cell Automata� Kleene�s Nerve Nets� � �

Page 22: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ��

Petri Nets

�� Show that if we have

�������

AAAAAAU

m

m� m��

X X �

where F���X� � F���X �� � � �i�e� no con�ict between X and X �� then for some m��� wehave�

JJJJJJ�

�������

JJJJJJ�

��������

m

m� m��

m���

X X �

X � X

Y

where Y � X �X �

This is a so�called Chyrch�Rosser Property�

�� Show that if we have mX�� m� where X � fe�� � � � � ekg then for some m�� � � � � mk we

have�

me��� m�

e��� � � �ek�� mk � m

What happens if we remove the restrictions on �niteness�

�� Write some Petri Nets for a parallel situation you know well �e�g� from something youknew at home or some computational situation��

�� How can nets accept languages �� subsets of ���� Are they always regular�

� Find� for the Readers and Writers net given above� all the cases you can reach by transitionsequences starting at the initial case� Draw �nicely�� the graph of cases and transitions�this is a so�called case graph��

Page 23: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

Interpreting Automata

�� Let G � hN��� P� Si be a context�free grammar� It is strongly unambiguous if thereare no two left most derivations of the same word in ��� even possibly starting fromdi�erent non�terminals� Find suitable conditions on the productions of P which ensurethat G� � hN���� P �� S �i is strongly unambiguous where �� � � � f� � �g where theparentheses are assumed not to be in N or � and where

T �� �w� is in P � if T �� w is in P �

�� See what changes you should make in the de�nition of the interpreting automaton whensome of the following features are added�

e ��� if b then eelse e j begin c result e

c ��� if b then c jcase e of e� � c

���ek � c

end jfor v �� e� e do c jrepeat c until b

�� Can you handle constructions that drastically change the �ow of control such as�

c ��� stop j m � c j goto m

�Here stop just stops everything��

� Can you handle elementary read!write instructions such as�

c ��� read�v� j write�e�

�Hint� Consider an analogy with �nite automata � especially transducers��

�� Can you add facilities to the automaton to handle run�time errors�

�� Can you produce measures of time!space complexity by adding extra components to theautomaton�

�� Can you treat diagnostic �debugging� tracing� facilities�

�� What about real�time� That is suppose we had the awful expression�

e ��� time

which delivers the correct time�

Page 24: G D Plotkin - people.cs.uchicago.edu

���� BIBLIOGRAPHY ��

�� Treat the following PASCAL subset� The basic sets are T� N and x � I � fi� r� bg � theset of typical identi�ers �which is in�nite� and o � O � the set f �� �� � �� �� ����� �� �� �� div� mod� and g of operations� The idea for typical identi�ers is that i� r�b are type symbols for integer� real and boolean respectively and so hFRED� ri is the realidenti�er FRED�

The derived sets are expressions and commands where�

e ��� m j t j v j �e j not e j e o ec ��� nil j v �� e j c c� j if e then c else c� j while e do c

The point of the question is that you must think about compile�time type checking andthe memories used in the hS�M�Ci machine should be �nite �even although there arepotentially in�nitely many identi�ers��

� Can you treat the binding mechanism

s ��� i j r j bc ��� var v � s begin c end

so that you must now incorporate symbol tables�

��� Bibliography

�Bir� Bird� R� ���� Programs and Machines Wiley and Sons

�Bra� Brauer� W� ����� Net Theory and Applications Proceedings �� LNCS Vol� ��

�Gor� Gordon� M�J�C� ��� The Denotational Description of Programming Languages

Berlin� Springer�Verlag

�Gre� Greibach� S�A� ���� Theory of Program Structures Schemes� Semantics� Veri�cation�

LNCS� Vol� ��

�Kel� Keller� R�M� ���� Formal Veri�cation of Parallel Programs CACM �� pages ������

�Lan� Landin� P�J� ����� A Lambda�calculus Approach� Ch� � Advances in Programmingand Non�numerical Computation Pergamon

�Oll� Ollengren� A� ���� De�nition of Programming Languages by Interpreting Automata

Academic Press

�Pet� Peterson� J�L� ��� Petri Nets Computing Surveys� Vol� � pages �������

�Sco� Scott� D� ���� Some De�nitional Suggestions for Automata Theory JCSS � ���� pages������

Page 25: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� TRANSITION SYSTEM AND INTERPRETING AUTOMATA

�Ten� Tennent� R�D� ����� Principles of Programming Languages Prentice�Hall

�Weg� Wegner� P� ���� The Vienna De�nition Language A�C�M Computing Surveys� Vol��� pages ����

Page 26: G D Plotkin - people.cs.uchicago.edu

Chapter �

Simple Expressions and Commands

The hS�M�Ci machine emphasizes the idea of computation as a sequence of transitions involv�ing simple data manipulations further the de�nition of the transitions falls into simple casesaccording to the syntactic structure of the expression or command on top of the control stack�However� many of the transitions are of little intuitive importance� contradiciting our idea ofthe right choice of the �size� of the transitions� Further the de�nition of the transitions is notsyntax�directed so that� for example� the transitions of c c� are not directly de�ned in terms ofthose for c and those for c�� Finally but really the most important� the hS�M�Ci machine isnot a formalization of intuitive operational ideas but is rather� fairly clearly� correct given theseintuitive ideas�

in this chapter we develop a method designed to answer these objections� treating simpleexpressions and commands as illustrated by th language L� We consider run�time errors andsay a little on how to establish properties of transition relations� Finally we take a �rst look atsimple type�checking�

��� Simple Expressions

Let us consider �rst the very simple subset of expressions given by�

e ��� m j e� � e�

��

Page 27: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

and how the hS�M�Ci machine deals with them� For example we have the transition sequencefor the expression �� � �� � ��� � �� � ���

h��M� �� � �� � ��� � �� � ��i �� h��M� �� � �� � ��� �� � �� �i�� h��M� � �� � �� � �� � �� �i�� h��M� �� � �� � �� � �� �i�� h��M� � � � � �� � �� �i�� h� ��M� � � � �� � �� �i�� h� � ��M�� � �� � �� �i ����� h� ��M�� �� � �� �i ����� h��M� �� � �� �i��� h� � ��M�� �i ����� h ��M��i ����� h���M� �i

In these �� transitions only the � additions marked ��� are of any real interest as system events�Further the intermediate structures generated on the stacks are also of little interest� Preferablewould be a sequence of � transitions on the expression itself thus�

�� � ���� ��� � �� � ��� �� ��

�� �� � �� � ��

�� � � ���� ��

�� ���

�� ��

where we are ignoring the memory and we have marked the occurrences of the additions in eachtransition� �These transition sequences of expressions are often called reduction sequences ��derivations� and the occurrences are called redexes this notation originates in the � calculus�see e�g� �Hin����Now consider an informal speci�cation of this kind of expression evaluation� Brie�y one

might just say one evaluates from left�to�right� More pedantically one could say�

Constants Any constant� m� is already evaluated with itself as value�

Sums To evaluate e� � e�

�� Evaluate e� obtaining m�� say� as result�

�� Evaluate e� obtaining m�� say� as result�

�� Add m� to m� obtaining m�� say� as result�

This �nishes the evaluation and m� is the result of the evaluation�

Note that this speci�cation is syntax�directed� and we use it to obtain rules for describing steps�� transitions� of evaluation which we think of as nothing else than a derivation of the form�

e � e� �� e� �� � � � �� en�� �� en � m

Page 28: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE EXPRESSIONS �

�wherem is the result�� Indeed if we just look at the �rst step we see from the above speci�cationthat

�� If e� is not a constant the �rst step of the evaluation of e� � e� is the �rst step of theevaluation of e��

�� If e� is a constant� but e� is not� the �rst step of the evaluation of e� � e� is the �rst stepof the evaluation of e��

�� If e� and e� are constants the �rst �and last�� step of the evaluation of e� � e� is theaddition of e� and e��

Clearly too the �rst step of evaluating an expression� e� can be taken as resulting in an expressione� with the property that the evaluation of e is the �rst step followed by the evaluation of e��We now put all this together to obtain rules for the �rst step� These are rules for establishingbinary relationships of the form�

e �� e� � e� is the result of the �rst step of the evaluation of e�

Rules Sum

��e� �� e��

e� � e� �� e�� � e�

��e� �� e��

m� � e� �� m� � e���� m� �m� �� m� �if m� is the sum of m� and m��

Thus� for example� rule � states what is obvious from the above discussion�

If e�� is the result of the �rst step of the evaluation of e� then e�� � e� is the result of

the �rst step of the evaluation of e� � e��

We now take these rules as a de�nition of what relationships hold � namely exactly these wecan establish from the rules� We take the above discussion as showing why this mathematicalde�nition makes sense form an intuitive view it is the direct formalization referred to above�As an example consider the step�

�� � �� � ��� � �� � �� �� �� � �� � �� � ��

To establish this step we have

�� � � � �� � �By rule ���� � � �� � �� �� � � � �By rule ���� �� � �� � ��� � �� � �� �� �� � �� � �� � �� �By rule ��

Rather than this unnatural �bottom�up� method we usually display these little proofs in the�top�down� way they are actually �discovered�� The arrow is supposed to show the �direction�of discovery�

Page 29: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

� �

���������������Sum��� ������������

� � �����Sum��� � � �

� � �Sum��� �

Thus� while the evaluation takes four steps� the justi�cation �proof� of each step has a certainsize if its own �which need not be displayed�� In this light the hS�M�Ci machine can be viewedas mixing�up the additions with the reasons why they should be performed into one long linearsequence�It could well be argued that our formalization is not really that direct� A more direct

approach would be to give rules for the transition sequences themselves �the evaluations�� Forthe intuitive speci�cation refers to these evaluations rather than any hypothetical atomic actionsfrom which they are composed� However� axiomatizing a step is intuitively simpler� and weprefer to follow a simple approach until it leads us into such di culties that it is better toconsider whole derivations�Another point concerns the lack of formalization of our ideas� The above relies are easily

turned into a formal system of formulae� axioms and rules� What we would want is a su cientlyelastic conception of a range of such formal systems which on the one hand allows the naturalexpression of all the systems of rules we wish� and on the other hand returns some pro�t inthe form of interesting theorems about such systems or interesting computer systems based onsuch systems� However� The present work is too explorating for us to �x our ideas� althoughwe may later try out one or two possibilities� We also fear that introducing such formalitiescould easily lead us into abscurities in the presentation of otherwise natural ideas�Now we try out more expressions� To evaluate variables we need the memory component

of the hS�M�Ci machines � indeed that is the only �natural� component they have� It isconvenient here to change our notation to a more generally accepted one�

OLD NEW

Memory Store

Memories � Var �� N � S

M �

M�m�v� ��m�v�

Page 30: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE EXPRESSIONS �

����� L�Expressions

Now for the expression language of L�

e ��� m j v j �e� e�� j �e� e�� j �e� e��

we introduce the con�gurations

� � fhe� �ig

and the relation

he� �i �� he�� �i

meaning one step of the evaluation of e �with store ��results in the expression e� �with store��� The rules are just those we already have� adapted to take account of stores plus an obviousrule for printing the value of a variable in a store�

Rules Sum

��he�� �i �� he��� �i

he� � e�� �i �� he�� � e�� �i

��he�� �i �� he��� �i

hm� e�� �i �� hm� e��� �i

�� hm �m�� �i �� hn� �i �where n � m �m��

Minus

�� Exercise for the reader�

�� Exercise for the reader�

�� hm�m�� �i �� hn� �i �if m � m� and n � m�m��

Times

�� Exercise for the reader

�� Exercise for the reader

�� Exercise for the reader

Variable

�� hv� �i �� h��v�� �i

Note the two users of the symbol� �� in rules Sum �� One as a syntactic construct and onefor the addition function� We will often overload symbols in this way relying on the contextfor disambiguation� So here� for example� to make sense of n � m �m� we must be meaningaddition as the left�hand�side of the equation denotes an integer�

Page 31: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

Of course the terminal con�gurations are those of the form hm� �i� and m is the result ofthe evaluation� Note that there are con�gurations such as�

� � h� � �� ���� �i

which are not terminal but for which there is no �� with � �� ���

De�nition� Let h�� T���i be a tts� A con�guration � is stuck if � �� T and ��� � � �� ���

In most programming languages these stuck con�gurations result in run�time errors� These willbe considered below�The behavior of expressions is the result of their evaluation and is de�ned by�

eval�e� �� � m � he� �i ��� hm� �i

The reader will see �from ��� below� if needed� that eval is a well�de�ned partial function�One can also de�ne the equivalence of expressions by�

e � e� � ���eval�e� �� � eval�e�� ��

����� Boolean Expressions

Now we turn to the Boolean expressions of the language L given by�

b �� t j b or b� j e � e� j �b

Here we take �fb� �g and consider the rules for the transition relation� There are clearlynone for truthvalues� t� but there are several possibilities for disjunctions� b or b�� Thesepossibilities di�er not only in the order of the transitions� but even on which transitions occur�The con�gurations are pairs hb� �i�

A� Complete Evaluation� This is just the Boolean analogue of our rules for expressionsand corresponds to the method used by our SMC�machine�

��hb�� �i �� hb��� �i

hb� or b�� �i �� hb�� or b�� �i

��hb�� �i �� hb�� �i

ht or b�� �i �� ht or b�� � �i

�� t or t� �� t�� �where t�� � t � t��

B� Left�Sequential Evaluation� This takes advantage of the fact that it is not needed toevaluate b� in tt or b� as the result will be tt independently of the result of evaluating b�

��hb�� �i �� hb��� �i

hb� or � b�� �i �� hb�� or b�� �i

�� htt or b�� �i �� htt� �i

Page 32: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE EXPRESSIONS ��

�� h� or b�� �i �� hb�� �i

C� Right�Sequential Evaluation� Like B but �backwards��

D� Parallel Evaluation This tries to combine the advantages of B and C by evaluatingb� and b� in parallel� in practice that would mean having two processors� one for b�� orusing one but interleaving� somehow the evaluations of b� and b�� This idea is thereforenot found in the usual sequential programming languages �as opposed to these makingexplicit provisions for concurrency�� However� it may be useful for hardware speci�cation�

��hb�� �i �� hb��� �i

hb� or b�� �i �� hb� or b��� �i

��hb�� �i �� hb��� �i

hb� or b�� �i �� hb� or b��� �i

�� htt or b�� �i �� htt� �i

�� hb� or tt� �i �� htt� �i

�� h� or b�� �i �� hb�� �i

�� hb� or �� �i �� hb�� �i

The above evaluation mechanisms are very di�erent when subexpressions can have non�terminating evaluations� when we have the following relationships�

B� �

C A� �C

where X � Y means that if method X terminates with result t� so does method Y � We takemethod A for the semantics of our example language L�For Boolean expressions of the form e � e� our rules depend on those for expressions� but

otherwise are normal �and for brevity we omit the ��s��

EQUALITY

��e� �� e��

e� � e� �� e�� � e�

��e� �� e��

m � e� �� m � e���� m � n �� t �where t is tt if m � n and � otherwise�

For negations �b we have� again omitting the ��s�

NEGATION

Page 33: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

��b �� b�

�b �� �b�

�� �t �� t� �where t� � �t�

The behavior of Boolean expressions is de�ned by�

eval�b� �� � t� hb� �i ��� ht� �i

One can also de�ne equivalence of Boolean expressions by�

b � b� � ���eval�b� �� � eval�b�� ��

��� Simple Commands

Again we begin with a trivial language of commands�

c ��� nil j v �� e j c c�

and see how the SMC�machine behaves on an example�

h�� abc� z �� x �x �� y y �� z�i �� h�� abc� z �� x x �� y y �� zi�� hz� abc� x �� x �� y y �� zi�� ha z� abc� �� x �� y y �� zi ����� h�� aba� x �� y y �� zi�� h�� aba� x �� y y �� zi��� hb x� aba� �� y �� zi ����� h�� bba� y �� zi��� ha y� bba� ��i ����� h�� baa� �i

And we see that of the eleven transitions only three � the assignments � are of interest assystem events�Preferable here would be a sequence of three transitions on con�gurations of the form hc� �i�

thus�

hz��� x �c �� y y �� z�� abdi��h�x

��� y y �� z�� abai

��hy��� z � bbai

�� baa

where we have marked the assignments occurring in transitions�Now informally one can specify such command executions as follows�

Nil� To execute nil from store � take no action and terminate with � as the �nal storeof the execution�

Page 34: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE COMMANDS ��

Assignment� To execute v �� e from store � evaluate e� and if the result is m� change� to ��m�v� �the �nal store of the execution��

Composition� To execute c c� form store �

�� Execute c from store � obtaining a �nal store� ��� say� if this execution terminates�

�� Execute c� from the store ��� The �nal store of this execution is also the �nal storeof the execution of c c�

Sometimes the execution of c c� is pictured in terms of a little �owchart�

� � �c c�

As in the case of expressions one sees that this description is syntax�directed� We formalize itconsidering terminating executions of a command c from a store � to be transition sequencesof the form�

hc� �i � hc�� ��i �� hc�� ��i �� � � � �� hcn��� �n��i �� �n

Here we take the con�gurations to be�

� � fhc� �ig � f�g

and the terminal con�gurations to be

T � f�g

where the transition relation hc� �i �� hc�� ��i �resp� ��� is read as�

One step of execution of the command c from the store � results in the store �� andthe rest of the execution of c is the execution of c� form �� �resp� and the executionterminates��

Thus we choose c� to represent� in as simple a way as is available� the remainder of the executionof c after its �rst step� The rules are

Nil� hnil� �i �� �

Assignment�

��he� �i ��� hm� �i

hv �� e� �i �� ��m�v�

Composition��

��hc�� �i �� hc��� �

�i

hc� c�� �i �� hc�� c�� ��i

Page 35: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

��hc�� �i �� ��

hc� c�� �i �� hc�� ��i

Notes �� In formulating the rule for assignment we have considered the entire evaluation ofthe right�hand�side as part of one execution step� This corresponds to a change in vies of thesize of our step when considering commands� but we could just as well have chosen otherwise�

As an example consider the �rst transition desired above for the execution

hz �� x �x �� y y �� z�� abci

It is presented in the top�down way

hz �� z �z �� y y �� z�� abciComp ��� h�z �� y y �� z�� abaihz �� z� abci

Ass ��� abahz� abci

Var ��� ha� abci

Again we see� as in the case of expressions a �two�dimensional� structure consisting of a �hor�izontal� transition sequence of the events of system signi�cance and for each transition a �ver�tical� explanation of why and how it occurs�

������ A

AAAAA �

����� A

AAAAA

� � �

������ A

AAAAA

�� �� � � � � � � �n

proof proof proof

For terminating executions of c� c� this will have the form�

������ A

AAAAA �

����� A

AAAAA �

����� A

AAAAA �

����� A

AAAAA

� � � � � �

c� c�� � �c��

c�� � ��� � �

c�� c

����

� c�� ����� �

� c����� � ����� �

c�� c�� �

����� �

� ������� �

��������� � �

Again we see that the SMC�machine transition sequences are more�or�less linearisations of thesestructures� Note the appearance of rules for binary relations �with additional data components�such as�

R�c� c�� �� ��� �def hc� �i �� hc�� ��iS�e� e�� �� �def he� �i �� he�� ��i

Later we shall make extensive use of predicates to treat the context�sensitive aspects of syntax��the static aspects of semantics�� As far as we can see there is no particular need for ternaryrelations� although the above discussion on the indirectness of our formalization does suggestthe possibility of needing relation of variable degree for dealing with execution sequences�

Page 36: G D Plotkin - people.cs.uchicago.edu

���� L�COMMANDS ��

��� L�commands

Recalling the syntax of L�commands�

c ��� nil j v �� e j c c� j if b then c else c� j while b c

we see that it remains only to treat conditionals and repetitions�

Conditionals� To execute if b then c else c� from �

�� Evaluate b in �

��� If result was tt execute c from �

��� If result was � execute c� from �

In pictures we have�

bbbb

b���

��bbbbb�����

�QQQs����bbbb

� �

b

c c�

tt ff

And the rules are�

��hb� �i ��� htt� �i

hif b then c else c�� �i �� hc� �i

��hb� �i ��� h�� �i

hif b then c else c�� �i �� hc�� �i

Notes �� Again we are depending on the transition relation of another syntactic class � hereBoolean expressions � and a whole computation from that class becomes one step of the com�putation�

Notes �� No rules for T �if b then c else c�� are given as that predicate never applies Fora conditional is never terminal as one always has at least one action � namely evaluation thecondition�

While� To execute while b do c from �

Page 37: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

�� Evaluate b

��� If the result is tt� execute c from �� If that terminates with �nal state ��� executewhile b do c from ���

��� If the result is � the execute is �nished and the �nal state is ��

In pictures we have the familiar �owchart�

bbbb

b���

��bbbbb�����

��

b

c

The rules are�

��hb� �i ��� htt� �i

hwhile b do c� �i �� hc while b do c� �i

��hb� �i ��� h�� �i

hwhile b do c � �i �� �

Example� Consider the factorial example y �� � w from chapter�� where w � while ��x ��� do c where c � �y �� y � x x �� x� ��� We start from the state h�� �i�

hy �� � w� h�� �iiASS��� hw� h�� �iii

COMP��� hc w� h�� �ii �via WHI�

COMP��� hx �� x� � w� h�� �ii �via COMP� and ASS��

COMP��� hw� h�� �ii

COMP��� hc w� hp�� �ii �WHI�

COMP��� hx �� x� � w� h�� �ii �via COMP� and ASS��

COMP��� hw� h�� �ii�� hc w� h�� �ii�� hx �� x� � w� h�� �ii�� hw� h�� �ii

COMP��� h�� �i �via WHI��

Page 38: G D Plotkin - people.cs.uchicago.edu

���� STRUCTURAL INDUCTION �

A terminating execution sequence of a while�loop w � while bdo c looks like this �omitting��s��

w �� c w �� � � � �� w �� c w �� � � � �� w ������ � � � �� w ��b ��� tt c �� � � � �� � � � b ��� tt c �� � � � �� � � � b������ � � � �� � � � b ��� �

������LLLLLL �

�����LLLLLL������LLLLLL �

�����LLLLLL �

�����LLLLLL������LLLLLL BB�

�����BB

��������������������� L

LLLLL��

������LLLLLL

� � � � �� � � � � �

One can now de�ne the behavior and equivalence of commands by�

exec�c� �� � �� � hc� �i ��� ��

and

c � c� � ���exec�c� �� � exec�c�� ��

��� Structural Induction

Although we have no particular intention of proving very much either about or with our oper�ational semantics� we would like to introduce enough mathematical apparatus to enable us toestablish the truth of such obvious statements as�

if � �� T then for some �� we have � �� ��

The standard tool is the principle of Structural Induction�SI�� It enables us to prove propertiesP �p� of syntactic phrases� and it takes on di�erent forms according to the abstract syntax of thelanguage� For L we have three such principles� one for expressions� one for Boolean expressionsand one for commands�

Structural Induction for Expressions

Let P �e� be a property of expressions� Suppose that�

�� For all m in N it is the case that P �m� holds� and

�� For all v in V it is the case that P �v� holds� and

�� For all e and e� in E if P �e� and P �e�� holds so does P �e� e��� and

�� As � but for �� and

�� As � but for �

Page 39: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

Then for all expressions e� it is the case that P �e� holds�

We take this principle as being intuitively obvious� It can be stated more compactly byusing standard logical notation�

���m � N� P �m�� ��v � V� P �v�� ��e� e� � E� P �e� P �e�� � P �e� e��� ��e� e� � E� P �e� P �e�� � P �e� e��� ��e� e� � E� P �e� P �e�� � P �e � e����� �e � E� P �e�

As an example we prove

Fact� The transition relation for expressions is deterministic

Proof� We proceed by SI on the property P �e� where

P �e� � ��� ��� ����he� �i �� �� he� �i �� ���� � �� � ���

Now there are �ve cases according to the hypotheses necessary to establish the conclusion bySI�

� e � m � N Suppose he� �i �� ��� ��� � But this cannot be the case as hm� �i is stuck�Thus P �e� holds vacuously�

� e � v � N Suppose hv� �i �� ��� ���� Then as there is only one rule for variables� we have�� � h��v�� �i � ����

� e � e� � e� Suppose he� � e�� �i �� ��� ���� There are three subcases according to whyhe� � e�� �i �� ��

�� Rule � For some e�� we have he�� �i �� he��� �i and �� � he���e�� �i� Then e� is not

in N �otherwise he�� �i would be stuck� and so for some e��� we have he�� �i �� he���� �i

and so ��� � he��� � e�� �i� But by the induction hypothesis applied to e� we thereforehave e�� � e��� and so �

� � ����

�� Rule � We have e� � m � N and for some e�� we have he�� �i �� he���� �i and��� � hm � e���� �i� But applying the induction hypothesis to e�� we see that e

�� � e���

and so �� � ����

�� Rule � We have e� � m�� e� � m�� Then clearly �� � ����

� e � e� � e�

� e � e� � e� These cases are similar to the third case and are left to the reader�

Page 40: G D Plotkin - people.cs.uchicago.edu

���� STRUCTURAL INDUCTION �

In the above we did not need such a strong induction hypothesis� Instead we could choosea �xed � and proceed by SI on Q�e� where�

Q�e� � ���� ���� �he� �i �� � he� �i �� ���� � �� � ���

However� this is just a matter of luck �here that the evaluation of expressions does not sidee�ect the state�� Generally it is wise to choose one�s induction hypothesis as strong as possible�The point is that if one�s hypothesis has the form �for example�

P �e� � �� Q�e� ��

then when proving P �e�� e�� given P �e� and P �e�� one �xes � and tries to prove Q�e� ��� Butin this proof one is at liberty to use the facts Q�e�� ��� Q�e�� �

��� Q�e�� ��� Q�e�� ���� for any ��

and ����

SI for Boolean Expressions

We just write down the symbolic version for a desired property P �b� of Boolean expressions�

���t � T� P �t�� ��e� e� � E� P �e � e��� ��b� b� � B��b� P �b�� � P �b or b��� ��b � B� P �b� � P ��b���� �b � B�P �b�

In general when applying this principle one may need further structural inductions on expres�sions� For example�

Fact� If b is not in T and contains no occurrence of an expression of the form m � n� wherem n� then no hb� �i is stuck�

Proof� We �x � and proceed by SI on Boolean expressions on the property�

Q�b� � �b �� T ��m n��m� n�� does not occur in b��� he� �i is not stuck

Case � B � tt This holds vacuously�

Case � B � �e � e�� Here there are three subcases depending on the forms of e and e��

Case �� If e is not in N� then for some e�� we have he� �i �� he��� �i

Lemma For any expression e not in N if e has no subexpressions of the form� m� n�where m n� then no he� �i is stuck�

Proof By SI on expressions and left to the reader���Continuing with case ��� we see that he � e�� �i �� he�� � e�� �i so hb� �i is notstuck�

Page 41: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

Case �� Here e is in N but e� is not the proof is much like case ��� and also uses thelemma�

Case �� Here e� e� are in N and we an use rule EQU �

Case � B � �b� or b�� This is like case � of the proof of fact ��

Case � B � �b� If b� is not in T we can easily apply the induction hypothesis� Otherwiseuse rule Neg��

This concludes all the cases and hence the proof�

SI for Commands

We just write down the symbolic version for a �desired� property P �c� of commands�

�P �nil� �v � V� e � E� P �v �� e� ��c� c� � C�P �c� P �c�� � P �c c��� ��b � B��c� c� � C�P �c� P �c�� � P �if b then c else c��� ��b � B� �c � C�P �c� � P �while b do c��� �c � C� P �c�

For an example we prove�

Fact� If v does not occur on the left�hand�side of an assignment in in c� then the execution ofc cannot a�ect its value� That is if hc� �i ��� �� then ��v� � ���v��

Proof� By SI on commands� The statement of the hypothesis should be apparent from theproof� and is left to the reader�

Case � n � nil Clear�

Case � c � �v �� e�� Here v� �� v and we just use the de�nition of ��m�v���

Case � c � �c� c�� Here if hc� c�� �i ��� �� then for some ��� we have hc�� �i ��� ��� andhc�� ���i ��� ��� �This requires a lemma for proof by the reader��Then by the induction hypothesis applied �rst to c� and then to c� we have�

���v� � ����v� � ��v�

Case � c � if b then c� else c� Here we easily use the induction hypothesis on c� and c��according to the outcome of the evaluation of b��

Case � c � while b do c� Here we argue on the length of the transition sequence hc� �i ��� � � �� ��� This is just an ordinary mathematical induction� In case the sequence haslength �� we have �� � �� Otherwise there are two cases according to the result ofevaluating b� We just look at the harder one�

Page 42: G D Plotkin - people.cs.uchicago.edu

���� DYNAMIC ERRORS ��

Case �� hc� �i �� hc� c� �i �� � � � �� ��� Here we see that hc�� �i ��� �� �andapply the main SI hypothesis� and also that hc� ��i ��� �� and a shorter transitionsequence to which the integer induction hypothesis can there fore be applied�

This particular lemma shows that on occasion we will use other induction principles suchas induction on the length of a derivation sequence�Another possibility is to use induction on some measure of the size of the proof of an

assertion � �� �� �which would� strictly speaking� require a careful de�nition of the sizemeasure�� Anyway we repeat that we will not develop too much �technology� for making theseproofs� but would like the reader to be able� in principle� to check out simple facts�

��� Dynamic Errors

In the de�nition of the operational semantics of L�expressions we allowed con�gurations of thekind h�� � � � ���� ���� �i to stick� Thus� although we did ensure�

� � T � ����� �� ��

we did not ensure the converse� Implementations of real programming languages will ensurethe converse generally by issuing a run�time � � dynamic� error report and forcibly terminatingthe computation� It would therefore be pleasant if we could also specify dynamic errors�As a �rst approximation we add an error con�guration to the possible con�gurations of

each of the syntactic classes of L� Then we add some error rules�

Expressions

� Sum

��he�� �i �� error

he� � e�� �i �� error

��he�� �i �� error

hm � e�� �i �� error

� Minus

��� as for Sum

�� hm�m�� �i �� error �if m m��

� Times

��� as for Sum

Boolean Expressions

� Disjunction

��� as for Sum

� Equality

Page 43: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

��� as for Sum

� Negation

��he� �i �� error

h�e� �i �� error

Commands

� Assignment

��he� �i �� error

hv �� e� �i �� error

� Composition

��hc�� �i �� error

hc� c�� �i �� error

� Conditional

��hb� �i ��� error

hif bthen c elsec�� �i �� error

� Repetition

��hb� �i ��� error

hwhile b do c� �i �� error

So the only possibility of dynamic errors in L arises form the subtraction of greater form asmaller� Of course other languages can provide many other kinds of dynamic errors� Division byzero� over�ow� taking the square root of a negative number� failing dynamic type�checking tests�overstepping array bounds� missing a dangling reference or reaching an uninitialized locationetc� etc� But the above simple example does at least indicate a possibility�

Fact� No L�con�guration sticks �with the above rules added��

Proof� Left to the reader as an exercise�

��� Simple Type�Checking

We consider a variant� L�� of L in which expressions and Boolean expressions are amalgamatedinto one syntactic class and have to be sorted out again by type�checking� Here is the languageL��

Basic Syntactic Sets

� Truthvalues� t � T

� Numbers� m�n � T

� Variables� v � Var � fa� b� x� x�� x�� x�� � � �g

Page 44: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE TYPE�CHECKING ��

� Binary Operations� bop � BOp � f���� ���� org

Derived Syntactic Sets

� Expressions� e � Exp where�

e ��� m j t j v j e� bop e� j �e

� Commands� c � Com where�

c ��� nil j v �� e j c� c� j if e then c� else c� j while e do c

Note� We have taken Var to be in�nite in the above in order to raise a little problem �later�on how to avoid in�nite memories�

Many expressions such as �tt � �� or �� now have no sense to them� and nor do suchcommands as if x or � then c� else c�� To make sense an expression must have a type� and inL� there are exactly two possibilities�

Types� � � Types � fint� boolg

To see which expression have types and what they are we will just give some rules for assertions�

e � � � e has type �

Note �rst that the basic syntactic sets have� in a natural way� associated type information�Clearly we will have truthvalues having type bool�� numbers having type int� variables havingtype int and for each binary operation� bop� we have a partial binary function on Types�

�� �� � bool intbool � �int � int

� bool intbool � �int � bool

or bool intbool bool �int � �

Rules

Truthvalues� t � bool

Numbers� m � int

Variables� v � int

BinaryOperations�e� � �� e� � ��e� bop e� � ��

�where �� � �bop���� ����

Negation�e � bool

�e � bool

Now for commands we need to sort out those commands which are well�formed in the sensethat all subexpressions have a type and are Boolean when they ought to be� The rules forcommands involve assertions�

Wfc�c� � c is a well�formed command�

Page 45: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

Nil� Wfc�nil�

Assignment�e � int

Wfc�v �� e�

Sequencing�Wfc�c�� Wfc�c��

Wfc�c� c��

Conditional�e � bool Wfc�c�� Wfc�c��

Wfc �if e then c� else c��

While�e � bool Wfc�c�

Wfc �while e do c�

Of course all of this is really quite trivial and one could have separated out the Boolean ex�pressions very easily in the �rst place� as was done with L� However� we will see that themethod generalizes to the context�sensitive aspects� also referred to in the literature as thestatic semantics�Turning to the dynamic semantics we want now to avoid con�gurations hc� �i with � �

Var �� N� as such stores are in�nite objects� For we have more or less explicitly indicatedthat we are doing �hopefully nice� �nitary mathematics� The problem is easily overcome bynoting that we only need � to give values for all Consequently for any �nite subset V of Varwe set�

StoresV � V �� N

and take the con�gurations also to be indexed by V

�E�V � fhe� �i j �� e � ��Var�e� � V� � � StoresV g�C�V � fhc� �i j Wfc�c��Var�c� � V� � � StoresV g

where Var�e� is the set of variables occurring in e� The rules are much the same as before�formally speaking� That is they are the same as before but with the variables and metavariablesranging over the appropriate sets and an added index� So for example in the rule

Comp �Nhc�� �i ��V ��

hc� c�� �i ��V hc�� ��i

It is meant that c�� c� �and hence c� c�� are well formed commands with their variables all inV all of the con�gurations mentioned in the rule are in �C�V �Equally in the rule

Sum �he�� �i ��V he��� �i

he� � e�� �i ��V he�� � e�� �i

It is meant that all the expressions e�� e��� e� � e�� e

�� � e� have a type �which must here be

int� and all their variables are in V and all the con�gurations mentioned in the rule are in

Page 46: G D Plotkin - people.cs.uchicago.edu

���� STATIC ERRORS ��

�E�V � Thus the rules de�ne families of transition relations� ��V � �E�V ��E�V for expressions���V� �C�V � �C�V for commands�In the above we have taken the de�nition of Var�e�� the variables occurring in e and also

of Var�c� for granted as it is rather obvious what is meant� However� it is easily given by aso�called de�nition by structural induction�

Var�t� � Var�m� � �Var�v� � fvgVar�e� bop e� � Var�e�� � Var�e��Var��e� � Var�e�

With this kind of syntax�directed de�nition what is meant is that it can easily be shown bySI that the above equations ensure that for any e there is only one V with Var�e� � V � Thede�nition for commands is similar and is left to the reader� the only point of �very slight�interest is the de�nition of Var�v �� e��The de�nition can also be cast in the form of rules for assertions of the form Var�t� � V �

Truthvalues� Var�t� � �

Numbers� Var�m� � �

Variables Var�v� � fvg

Binary Operations�Var�e�� � V� Var�e�� � V�

Var�e� bop e�� � V� � V�

Negation�Var�e� � V

Var��e� � V

Exercise� Give rules for the assertion Var�e� � V �

Finally we have a parametrical form of behavior� For example for commands we have apartial function�

Exec � CV � StoresV �� StoresV

where CV � fc � C j Wfc�c� Var�c� � V g� given by�

Exec�c� �� � �� � hc� �i ��� ��

��� Static Errors

The point here is to specify failures in the type�checking mechanism� Here are some rules for avery crude speci�cation where one just adds a new predicate Error�

Binary Operations

��Error�e��

Error�e� bop e��

Page 47: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

��Error�e��

Error�e� bop e��

��e� � �� e� � ��Error�e� bop e��

�If �bop���� ��� is unde�ned�

Negation

Error�e�

Error��e�

Assignment

��Error�e�

Error�v �� e�

��e � bool

Error�v �� e�

Sequencing

��Error�c��

Error�c� c��

��Error�c��

Error�c� c��

Conditional

��Error�e�

Error�if e then c� else c��

��Error�c��

Error�if e then c� else c��

��Error�c��

Error�if e then c� else c��

��e � int

Error�if e then c� else c��

While

��Error�e�

Error�while e do c�

��Error�c�

Error�while e do c�

��e � int

Error�while e do c�

Page 48: G D Plotkin - people.cs.uchicago.edu

��� EXERCISES �

�� Exercises

Expressions

� Try out a few example evaluations�

� Write down rules for the right�to�left evaluation of expressions� as opposed to the left�to�right evaluation described above�

� Write down rules for the parallel evaluation of expressions� so that the following kind oftransition sequence is possible�

�� � �� � ��� � ��� � �� � �� �� �� � �� � ��� � � � �� �� �� � �� � � � ���� � � � � �� �� � � �� �� ��

Here one transition is one action of imaginary processors situated just above the leavesof the expressions �considered as a tree��

� Note that in the rules if he� �i �� he�� ��i then �� � �� This is the mathematical coun�terpart of the fact that evaluation of L�expressions produces no side�e�ects� Rephrasethe rules for L�expressions in terms of relations � � e �� e� where � � e �� e� �def

he� �i �� he�� �i and can be read as �given �� e reduces to e���

� Give rules for �genuine� parallel evaluation where one or more processors as imagined in� can perform an action during the same transition �Hint � Use the idea of exercise ���

��Try to develop a method of axiomatizing entire derivation sequences� Can you �nd anyadvantages for this idea�

Boolean Expressions

� Can you �nd various kinds of rules analogous to these for or for conjunctions b and b���By the way� the left�sequential construct is often advantageous to avoid array subscriptsgoing out of range as in�

while �i � n� and a�i� � xdo i �� i� � c ��

� Treat the following additions to the syntax

e ��� if b then e� else e�b ��� if b� then b� else b�

Presumably you will have given rules for the usual sequential conditional� Can you �ndand give rules for a parallel conditional analogous to parallel disjunction�

Page 49: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

� Treat the following additions to the syntax which introduce the possibilities of side�e�ectsin the evaluation of expressions�

e ��� begin c result e

�meaning� execute c then evaluate e� and the assignment expression�

e ��� �v �� e�

where the intention is that the value of �v �� e� is the value of e but the assignment alsooccurs� producing a side�e�ect in general�

� Show that the equivalence relations on expressions and boolean expressions are respectedby the program constructs discussed above so that for example�

a� e� � e� e� � e�� � �e� � e�� � �e�� � e���b� e� � e� e� � e�� � �e� � e�� � �e�� � e���c� e� � e� e� � e�� � �e� � e�� � �e

�� � e���

d� b � b� � �b � �b�

Commands

�� Give a semantics for the �desk calculator� command

v� �� e

so that the equivalence

�v� �� e� � �v �� v � e�

holds �and you can prove it��

�� Give a semantics for the ALGOL��� assignment command

v� �� �v� �� � � � �vn �� e� � � ��

so that �see exercise � the equivalence

�v� �� �v� �� � � � �vn �� e� � � ��� � �v� �� e�

where e � �v� �� � � � �vn �� e� � � �� holds� and you can prove it�

�� Treat the simultaneous assignment

v� �� e� and � � � and vn �� en

where the v� must all be di�erent� Execution of this command consists of �rst evaluatingall the expressions and then performing the assignments�

Page 50: G D Plotkin - people.cs.uchicago.edu

��� EXERCISES �

�� Treat the following variations on the conditional command�

if b then c j unlessb then c jif b� thenc�elseif b� then c����elseif bn then cnelse cn��

and show they can all be eliminated �to within equivalence� in favor of the ordinaryconditional�

�� Treat the simple iteration command

do e times c

and the following variations on repetitive commands like while b do c�

repeat c until b j until b repeat c j repeat c unless b jloopc�when b� do c

�� exit

c����when bn do c

�n exit

cn��

repeat

where the last construct has n possible exits from the loop�

� Show that the equivalence is respected by the above consturucts on commands so that�for example

a� e � e� � �v �� e� � �v �� e��b� c� � c�� c� � c�� � c� c� � c�� c

��

c� b � b� c� � c�� c� � c�� � if b then c� elsec� � if b� then c�� else c��

d� b � b� c � c� � while b do c � while b� do c�

�� Rede�ne behavior and equivalence to take account of run�time errors� Do the statementsof exercise �� remain valid�

����Try time and space complexity in the present setting� �Hint � Consider con�gurations ofthe form� say� hc� �� t� si where

t � �the total time used so far�

Page 51: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

s � �the maximum space used so far��

There is lots to do� Try �nding fairly general de�nitions� de�ne behavior and equivalence�approximate equivalence�� and see which program equivalences preserve equivalence�Try looking at measures for the parallel evaluation of expressions� Try to see what isreasonable to incorporate from complexity literature� Can you use the bene�ts of ourstructured languages to make standard simulation results easier!nicer for students�

����Try exercise �� and �� from chapter � again�

� Give an operational semantics for L� but where only � step of the evaluation of an expres�sion or Boolean expression is needed for � step of execution of a command� Which of thetwo possibilities � the �big steps� of the main text or the �little steps� of the exercise �do you prefer and why�

Proof

�� Let c be any command not involving subexpressions of the form �e�e�� or while loops butallowing the simple iteration command of exercise ��� Show that any execution sequencehc� �i ��� � � � terminates�

�� Establish �for L� the following �arithmetic� equivalences�

e� � � � e�e� � e� � e� � e�e� � �e� � e�� � �e� � e�� � e�etc

Which ones fail if side�e�ects are allowed in expressions�

Establish the equivalences�

a� if b then c else c � c

b� if b then if b then c� else c�

else if b then c�elsec��

� if b then c� else c��

c� if b then if b� then c� else c�else if b� then c� else c�

� if b� then if b then c� else c�else if b then c� else c�

Which ones remain true if Boolean expressions have side�e�ects!need not terminate�

�� Establish or refute each of the following suggested equivalences for the language L �andslight extensions� as indicated��

a� nil c � c � c nilb� c if b then c� else c� � if begin c result b then c� else c�c� �if b then c� else c�� c � if b then c� c else c� cd�while b do c � if b then �c while b do c� else nile� repeat c until b � c while �b do c

Page 52: G D Plotkin - people.cs.uchicago.edu

��� BIBLIOGRAPHICAL REMARKS ��

Type Checking

�� Make L� a little more realistic by adding a type real� decimals� variables of all three types�and a variety of operators� Allow int to real conversion� but not vice�versa�

�� Show that if hc� �i �� hc�� ��i and x � Dom���nV ar�c� then ��x� � ���x��

� Show that if hc� �i �� hc�� ��i is a transition within �C�V and hc� �i �� hc�� ��i is atransition within �C�V � where V � V � then� if � � � d V � it follows that �� � �� d V �

�� The static error speci�cation is far too cured� Instead one should have a setM ofmessagesand a relation�

Error�e�m� � m is a report on an error in e

and similarly for commands� Design a suitableM and a speci�cation of Error for L�� Tryto develop a philosophy of what a nice error message should be� See �Hor� for some ideas�

�� How would you treat dynamic type�checking in L�� What would be the new ideas forerror messages �presumably one adds an M �see ex� �� to the con�gurations��

�� BIBLIOGRAPHICAL REMARKS

The idea of reduction sequences originates in the �calculus �Hin� as does the present method ofspecifying steps axiomatically where I was motivated by Barendregt�s thesis �Bar��� I appliedthe idea to �calculus�like programming languages in �Plo��� �Plo�� and Milner saw how toextend it to simple imperative languages in �Mil��� More recently the idea has been applied tolanguages for concurrency and distributed systems �Hen��� �Mil��� �Hen��� The present courseis a systematic attempt to apply the idea as generally as possible� A good deal of progress hasbeen made on other aspects of reduction and the lambda�calculus� a partial survey and furtherreferences can be found in �Ber� and see �Bar���The Butch school has originated related ideas �deB�� �deR�� A direct precursor of our

method can be found in the work by Lauer and Hoaare� �Hoa� con�gurations which have therough form hs�� � � � � sn� �i where the s� are statements �includes commands�� They de�ne anext�con�guration function and the de�nition is to some extent syntax�directed� The idea ofa syntax�directed approach was independently conceived and mentioned all too brie�y in thework of Salwicki �Sal��Somewhat more distantly various grammatical �� symbol�pushing too� approaches have

been tried� For example W�grammars �Cle� and attribute grammars �Mad� although thesede�nitions are not syntax�directed de�nitions of single transitions it should be perfectly possibleto use the formalisms to write de�nitions which are� The question is rather how appropriatethe formalisms would be with regard to such issues as completeness� clarity �� readability��naturalness� realism� modularity �� modi�ability � extensionality�� One good discussion ofsome of these issues can be found in �Mar�� For concern with modularity consult the course notes

Page 53: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� SIMPLE EXPRESSIONS AND COMMANDS

of Petr Mosses� Our method is clearly intended to be complete and natural and realistic� andwe try to be clear the only point is that it is quite informal� begin normal �nite mathematics�There must be many questions on good choices of formalism� As regards modularity we justhope that if we get the other things in a reasonable state� then current ideas for imposingmodularity on speci�cations will prove useful�For examples of good syntax�directed English speci�cations consult the excellent article by

Ledgard on ten mini�languages �Led�� These languages will provide you with mini�projectswhich you should �nd very user full in understanding the course� and which could very wellbe the basic for more extended projects� For a much more extended example see the Algol�� Report �Wij�� Structural induction seems to have been introduced to Computer Science byBurstall in �Bur� for a system which performs automatic proofs by Structural induction on listssee �Boy�� For discussions of what error messages should be see �Hor� and for remarks on howand whether to specify them see �Mar��

���� Bibliography

�Bar�� Barendregt� H� ���� Some Extensional Term Models For Combinatory Logic and

Lambda�Calculi

�Bar�� Barendregt� H� ����� The Lambda Calculus� Studies in Logic Vol� ���� North�Holland

�Ber� Berry� G� and L"evy� j�j� A Survey of Some Syntactic Results in the �calculus�MFCS�ed� J� Becvar LNCS Vol� �� pp� �������

�Boy� Boyer� R�S� and Moore� J�S� ��� A Computational Logic Academic Press

�Bur� Burstall� R�M�B� ���� Proving Properties of Programs by Structural Induction Com�put� J� ����� pp� �����

�Cle� Cleaveldan� J�C� and Uggalis� R�C� ��� Grammars for Programming Languages

Elsevier

�deB� de Bakker

�deR� de Roever

�Hen�� Hennessy � M�C�B� and Plotkin� G�D���� Full Abstraction for a Simple Parallel

Programming Language MFCS� Olomom� LNCS Vol� �� pp� �������

�Hen�� Hennessy � M�C�B�� Li� Weiand Plotkin� G�D� ����� A First Attempt at Translating

CSP into CCS� Proceedings of the Second international Conference on DistributedComputing Systems To appear

�Hin� Hindley� J�R�� Lercher� B� and Seldin� J�P� ���� Introduction to Combinatory Logic

Cambiridge University Press

Page 54: G D Plotkin - people.cs.uchicago.edu

����� BIBLIOGRAPHY ��

�Hoa� Hoare� C�A�R� and Luer� P�G� ���� Consistent and Complete Formal Theories of theSemantics of Programming Languages Acta Infomatica

�Hor� Horning� J�J� ����What the Compiler Should Tell The User� Compiler Construction�

an Advanced Course eds FL� Bauer and J� Eickel LNCS �� pp� �������

�Lau� Luer� P�G� ���� Consistent Formal Theories of The Semantics of Programming Lan�guages IBM Laboratories Vienna TR ������

�Led� Ledgard� H�F� ���� Ten Mini�Languages� A Study of Topical issues in Programming

Languages Comp� Surveys �� pp� �������

�Mad� Madsen� O�L� ����� On De�ning Semantics By Means of Extended Attribute Gram�

mars in Semantics�Directed Compiler Generation ed� N�D� Jones LNCS �� pp� ����

�Mar� Marcotty� M� Ledgard� H�F� and Bochmann� C�V� ���� A Sampler of Formal De��

nitions Comp� Surveys �� pp� �����

�Mil�� Milner� A�J�R�G� ���� Program Semantics and Mechanized Proof in Foundtions of

COmputer Science II eds K�R� Apt and J�W� de Bakker� Mathematical Centre Tracts�� Amsterdam

�Mil�� Milner� A�J�R�G� ����� A Calculus of Communicating Systems LNCS �

�Plo�� Plotkin� G�D� ���� Call�by�name� Call�by�value and The Lambda�Calculus TCS ��pp� ������

�Plo�� Plotkin� G�D� ��� LCF Considered As A Programming Language TCS �� pp� �������

�Sal� Salwicki� A�

�Wij� van Wijngarden� A�� Maiiloux� B�J�� Peck� J�E�� Koster� C�H�A� Sintzo�� M�� Lindsey�C�H�� Meertens� L�G�L�T� and Fishker� R�G� ���� Revised Report ont the AlgorithmicLanguage Algol ��� Acta Informatica �� pp� �����

Page 55: G D Plotkin - people.cs.uchicago.edu

Chapter �

De�nitions and Declarations

��� Introduction

In this chapter we begin the journey towards realistic programming languages by consideringbinding mechanisms which enable the introduction of new names in local contexts� This leads tode�nitions of local variables in applicative languages and declarations of constant and variableidenti�ers in imperative languages� We will distinguish the semantic concepts of environmentsand stores� The former concerns those aspects of identi�ers which do not change throughoutthe evaluation of expressions or the execution of commands and so on the latter concerns thoseaspects which do as in sidee�ects in the evaluation of expressions or the e�ects of the executionof commands� In the static semantics context�free methods no longer su ce� and we show howour rules enable the context�sensitive aspects to be handled in a natural and syntax�directedway�

��� Simple De�nitions in Appllcative Languages

We consider a little applicative �� functional� language with simple local de�nitions of variables�It can be considered as a �rst step towards full�scale languages like ML �Gor��

Syntax Basic Sets

Numbers� m�n � N

Binary Op� bop � Bop � f���� �g

Variables� x� y� z � Var � fx�� x�� � � �g

Derived Sets

Expressions� e � Exp where

e ��� m j x j e� bop e� j let x � e� in e�

��

Page 56: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE DEFINITIONS IN APPLLCATIVE LANGUAGES ��

Note� Sometimes let x � e� in e� is written instead as e� where x � e�� From the point ofview of readability the �rst form is preferable when a bottom�up style is appropriate� and thesecond where a top�down style is appropriate� For in the �rst case one �rst de�nes x and thenuses it� and in the second it is used before being de�ned�

Clearly any expression contains various occurrences of variables� and in our language thereare two kinds of these occurrences� First we have de�ning occurrences where variables are used�For example considering �gure � the de�ning occurrences are �� �� and the others are applied�In some languages � but not ours� � one �nds other occurrences which can fairly be termeduseless�

x� � � let x� � � � y� � x�

in x� � � let y� � ��� x

in y � � let x� � � � x�� � x��

in x�� � y�����

Figure �� Some Variable Occurrences

Now the region of program text over which de�ning occurrences have an in�uence is knownas their it scope� One often says� a little loosely� that for example� the scope of the �rstoccurrence of x in e � let x � e� in e� is the expression e�� But then one considers exampleslike �gure � where occurrence �� is not in the scope of � �as it is instead in the scope of ��this is called a hole in the scope of �� It is more accurate to say that the scope of a de�ningoccurrence is a set of applied occurrences� In the case of let x � e� in e� the scope of x is allthose applied occurrence of x in e�� Thus in the case of �gure � we have the following tableshowing which applied occurrences are in the scope of which de�ning occurrences �equivalentlywhich de�ning occurrences bind which applied occurrences��

De�ning Occurrence Applied Occurrences

� f�� � ��� ��g� f�� ��g f��g

Note that each applied occurrence is in the scope of at most one de�ning occurrence� Thosenot in any scope are termed free�versus bound� for example occurrences �� �� � above are free�One can picture the bindings and the free variables by means of a drawing with arrows suchas�

Page 57: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

�� SSSo

� ��

�let x � � � y

in let y � � � x � y

in x � y � z

From the point of view of semantics it is irrelevant which identi�ers are chosen just so long asthe same set of bindings is generated� �Of course a sensible choice of identi�ers greatly a�ectsreadability� but that is not a semantic matter�� All we really need are the arrows� but it ishard to accommodate then into our one�dimensional languages� In the literature on �calculusone does �nd direct attempts to formalise the arrows and also attempts to eliminate variablesaltogether as in Combinatory Logic �Hin� In Data�ow one sees graphical languages where thegraphs display the arrows �Ack��

Static Semantics

Free VariablesThe following de�nition by structural induction is of FV�e�� the set of free variables ��variables with free occurrences� of e�

m x e� bop e� let x � e� in e�

FV � fxg V� � V� V� � �V�n�x��

Where V� � FV�e�� and V� � FV�e��

Example

FV�let x � � � y in � let y � � � y � z in x � y � z��� FV�� � y� � �FV� let y � � � x � y in x � y � z�nfxg�� fyg � ��fx� yg � �fx� y� zgnfyg��nfxg�� fyg � �fx� y� zgnfxg�� fy� zg

Dynamic Semantics

For the most part applicative languages have no concept of state there is only the evaluationof expressions in di�erent environments �� semantic contexts�� We take�

EnvV � �V �� N�

Page 58: G D Plotkin - people.cs.uchicago.edu

���� SIMPLE DEFINITIONS IN APPLLCATIVE LANGUAGES �

for any �nite subset of V of the set Var of variables and let range over Env �P

V EnvV andwrite �V to mean that is in EnvV � Of course EnvV � StoreV � but we introduce a newnotation in order to emphasize the new idea�The set of con�guration is also parameterized on V and

�V � fe � Exp j FV�e� � V gTV � N

The transition relation is now relative to an environment and for any � V and e� e� in �V wewrite

�V e �� e�

and read that in �� given� environment one step of the evaluation of the expression e resultsin the expression e�� The use of the turnstile is borrowed from formal logic as we wish to thinkof the above as an assertion of e �� e� conditional on which in turn is thought of as anassertion supplied by the environment on the values of the free variables of e and e�� As thisenvironment will not change from step to step of the evaluation of an expression� we will oftenuse� �xing in the transition relation� the transitive re�exive closure �V e �� �e�� It is leftto the reader to de�ne relative transition systems �i�e� to give a general de�nition of �relativetransition system���

Rules�

Variables� �V x �� �x�

Binary Operations� �� �V e� �� e�� � �V e� bop e� �� e�� bop e�

�� �V e� �� e�� � �V m bop e� �� m bop e��

�� �V m bop m� �� n �where n � m bop m��

Note� To save space we are using an evident horizontal lay�out for our rules� That is the rule�

A� � � � � � � Ak

A

can alternatively be written in the form

A�� � � � � � � � Ak � A�

De�nitions� Informally� to evaluate e � let x � e� in e� given

�� Evaluate e� given to get the value m��

�� Change to rho�m��x��

�� Evaluate e� given to get the value m�

Page 59: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

Then m is the value of e given �

The rules for one step of the evaluation are�

�� �V e� �� e��

�V let x � e� in e� �� let x � e�� in e�

�� �m�x� �V �fxg e� �� e��

�V let x � m in e� �� let x � m in e��

�� �V let x � m in n �� n

Of course these rules are just a clearer version of those given in Chapter � for expressions �assuggested in exercise ��� Continuing the logical analogy our rules look like a Gentzen systemof natural deduction �Pra� written in a linear way� Possible de�nitions of behaviour are left tothe reader�

��� Compound De�nitions

In general it is not convenient just to repeat simple de�nitions� and so we consider several waysof putting de�nitions together� The category of expressions is now�

e ��� m j x j e� bop e� j let d in e

where d ranges over the category Def of de�nitions where�

d ��� nil j x � e j d� d� j d� and d� j d� in d�

To understand this it is convenient to think in terms of import and export� An expression� e�imports values for its free variables from its environment �and produces a value�� This can bepictured as�

Q

QQ

QQQ

��xe

An expression

where x is a typical free variable of e� A de�nition� d� imports values for its free variables andexports values for its de�ning variables �those with de�ning occurrences�� This can be picturedas�

� �xd

y

A de�nition

Page 60: G D Plotkin - people.cs.uchicago.edu

���� COMPOUND DEFINITIONS �

These are data�ow diagrams and they also help explain compound expressions and de�nition�For example a de�nition block let d in e imports from its environment into d and then d exportsinto e with any other needed imports of e coming from the block environment� Pictorially

Q

QQ

QQQ

���

� �

a

b

c

d

e

y

x

A de�nition block

Here a is a typical variable imported by d but not e� and b is one imported by d and e� andc is one imported by e and not d again x is a variable exported by d and not imported by e�useless but logically possible�� and y is a variable exported by d and imported by e� Of coursewe later give a precise explanation of all this by formal rules of an operational semantics�

Turning to compound de�nitions we have sequential de�nition� d� d�� and simultaneous

de�nitions� d� and d�� and private de�nitions� d� in d�� What d� d� dose is import from theenvironment into d� and export from d� into d� �with any additional exports needed for d�being taken from the environment� then d� d� exports from both d� and d� with the lattertaking precedence for common exports� Pictorially �and we need a picture���

��

� ��

��d�

d�

a

b

c

Sequential De�nition

Simultaneous de�nition is much simpler d� and d� imports into both d� and d� from theenvironment and then exports form both �and there must be no common de�ning variable��pictorially

Page 61: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

d�

d�

x

y

a

b

c

Simultaneous De�nition

Finally� a private de�nition d� in d� is just like a sequential one� except that the only exportsare from d�� It can be pictured as�

��

d�

a

b

c

d�x

yyz

u

Private De�nition

We may write also d� in d� as let d� in d� or as private do within d�� Private de�nitions provideexamples of blocks where the body is a de�nition�We have already seen blocks with expressionbodies and will see ones with command bodies� Tennent�s Principle of Quali�cation says that inprinciple any semantically meaningful syntactic class can be the body of a block �Ten�� We shalllater encounter other examples of helpful organisational principles� As remarked in �Ten� manyprogramming languages essentially force one construct to do jobs better done by several forinstance it is common to try to get something of the e�ect of both sequential and simultaneousde�nition� A little thought should convince the reader that there are essentially just the threeinteresting way of putting de�nitions together�

Example� Consider the expression

let x � �in let x � � # y � � � x

in x � y

According as # is or and or in� the expression has the values �� � ������� or �� � �������or �� � � � ��� ���

Page 62: G D Plotkin - people.cs.uchicago.edu

���� COMPOUND DEFINITIONS ��

Static Semantics

We will de�ne the set DV�d� of de�ning variables of a de�nition d and also FV�d�e�� the set offree variables of a de�nition d or expression e�

nil x � e d� d� d� and d� d� in d�

DV � x V� � V� V� � V� V� where Vi is DV�di�

FV � FV �e� V� � �V�nDV�d��� V� � V� V� � �V�nDV�d��� where Vi is FV�di�

For expressions the de�nition of free variables is the same as before except for the case

FV�let d in e� � FV�d� � �FV�e�nDV�d��

Because of the restriction on simultaneous de�nitions not all expressions or de�nitions are well�formed � for example consider let x � � and x � � in x� So we also de�ne the well�formedones by means of rules for a predicate W�d�e� on de�nitions and expressions�

Rules�

De�nitions

Nil� W�nil�

Simple� W�e��W�x � e�

Sequential� W�d���W�d���W�d� d��

Simultaneous� W�d���W�d���W�d� and d�� �if DV�d� �DV �d�� � ��

Private� W�d���W�d���W�d� in d��

Expressions

Constants� W�m�

Variables� W�x�

Binary Op� W�c���W�e���W�e� bop e��

De�nitions� W�d��W�e��W�let d in eg�

Page 63: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

Dynamic Semantics

It is convenient to inrtoduce some new notation to handle environments� For purposes ofdisplaying environments consider� for exmaple� � fx� y� zg� where �x� � �� �y� � �� �z� � ��We will also write as fx � �� y � �� z � �g and drop the set btackets when desired thissituation makes it clearer that environments can be thought of as assertions�Next for any V��V� and ��V�� ��V� we de�ne � �� ���V� � V� by�

�x� �

� ��x� �x � V�� ��x� �x � V�nV��

We now have the nice �x � m� to replace the less readable �m!x�� Finally for any ��V�� ��V�

with V��V� � � we write �� � for �� �� Of course this is equale to �� ��� and also to �� ���but the extra notation makes it clear that it is required that V� � V� � ��The expression con�gurations are parameterised on V by�

�V � fe j W�e��FV�e� � V g

and of course

TV � N

And our transition relation� �V e �� e�� is de�ned only for � V � and e� e� in �V �For de�nitions the idea is that just as an expression is evaluate to yield values so is a

de�nition elaborated to yield a �little� environment �for its de�ning variables�� For example�given � fx � �� y � �� z � �g the de�nition x � � � x � z y � x � y � z is elaborated toyield fx � � y � ��g� In order to make this work we add another cluse to the de�nition of Def

d ���

What this means is that the abstract syntax of declaration con�gurations allows environments It does not mean that the abstract syntax of declarations does so�In a sense we slipped a similar trich in under the carpet when we allowed numbers as

expressions� Strictly speaking we should only have allowed literals and then allowed numbers aspart of the con�gurations and given rules for evaluating literals to numbers� Similar statementshold for other kinds of literals� However� there seemed little point in forcing the reader throughthis tedious procedure�Returning to de�nitions we now add clauses for free # de�ning variables�

FV� � � �DV� � � V �if � V �

and also add for any that W� � holds� and for any V that

�V � fd j W�d��FV�d� � V g

Page 64: G D Plotkin - people.cs.uchicago.edu

���� COMPOUND DEFINITIONS ��

and

TV � f g

and consider for V and � V and d� d� � �V the transition relation

�V d �� d��

which means that� given � one step of the elaboration of d yields d��

Example� We shall expect to see that�

x � �� y � �� z � �� x � �� � x� � z y � �x � y� � z��� fx � g y � �x � y� � z ��� fx � ��g�� fx � � y�� ��g

Rules�

Expressions� As before but with a change for de�nitions�

De�nitions� informally� to evaluate e� � let d in e� in the environment

�� Elaborate d in yielding ��

�� Change to � � � ���

�� Evaluate e in � yielding m�

Then the evaluation of e� yield m� Formally we have�

�� �V d �� d�

�V let d in e �� let d� in e

�� � �� �V �V� e �� e�

�V let � in e �� let � in e��where � � V��

�� �V let � in m �� m

The �rst two cases are self�explanatory�

Nil� �V nil �� �

Simple� �� �V e �� e�� � �V x � e �� x � e�

�� �V x � m �� fx � mg

Sequential� informally to elaborate d� d� given �

�� Elaborate d� in yielding �

�� Elaborate d� in � yielding �

Then the elaboration of d� d� yields �� ��� Formally we have�

Page 65: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

�� �V d� �� d��

�V d� d� �� d�� d�

�� � �� �V �V� d� �� d�� �V � d� �� � d��

�where � � V��

�� �V � � �� �� ��

Stimultaneous� informally to elaborate d� and d� given

�� Elaborate d� in yielding ��

�� Elaborate d� in yielding ��

Then the elaboration of d� and d� yields �� � if that is de�ned� For�mally

�� �V d� �� d�� � �V d� and d� �� d�� and d��� �V d� �� d�� � �V d� and d� �� � and d���� �V � and � �� � � �

Private� informally to elaborate d� in d� given

�� Elaborate d� in yielding ��

�� Elaborate d� in yielding ��

Then the elabolation of d� in d� yields �� Formally

�� �V d� �� d�� � �V d� in d� �� d�� in d��� �V �V� d� �� d�� � �V d� in d� �� � in d���where � � V��

�� �V � in � �� �

Example�

x � �� y � �� z � � �x � �� � x� � z y � �x � y� � zSEQ��� x � �� � �� � z y � �x � Y � � z �using SIM��SEQ��� x � y � �x� y� � z �using SIM��SEQ��� fx � g y � �x � y� � z �using SIM��SEQ��� fx � g y � �x � y� � zSEQ��� fx � g fy � ��gSEQ��� fx � � y � ��g�

The reader is encouraged here �and generally too� to work out examples for all the otherconstructs�

��� Type�Checking and De�nitions

New problems arise in static semantics when we consider type�checking and de�nitions� Forexample one cannot tell whether or not such an expression as x or tt or x � x is well�typed

Page 66: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS ��

with out knowing what the type of x is and that depends on the context of its occurrence� WeWill be ables to solve these problems by introducing static environments � to give this typeinformation and giving rules to establish properties of the form

� �V e � �

As usual we work by considering an example language�

Basic Sets

Types� � � Types � fint� boolg

Numbers� m�n � N

Truthvalues� t � T

Variables� x� y� z � Var

Binary Operations� bop � Bop � f���� ���� org�

Derived Sets

Constants� con � Con where con ��� m�t

De�nitions� d � Def where

d ��� nil j x � � � e j d� d� j d� and d� j d� in d�

Expressions� e � Exp where

e ��� con j x j �e j e� bop e� j if e� then e� else e� jlet d ine

Static Semantics

The de�nitions of DV�d� and FV�d� are as before as is FV�e� just adding that

FV�if e� then e� else e�� � FV�e�� � FV�e�� � FV�e��

We now need type environments over V � These form the set

TEnvV � V �� Types

and the set TEnvV �P

V TEnvV is ranged over by � and � and we write � � V for � � TEnvV �Of course all the notation ���� and �� � extends without change from ordinary environmentsto type environments� Now for every V and ��V � � and e with FV�e� � V we give rules for theproperty

� �V e � �

Page 67: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

meaning that given � the expression e is well�formed and has type � � This will involve usin giving similar rules for constants ans also for every V and � � V � � and de�nition d withFV�d� � V � for the property

� �V d � �

meaning that given � the de�nition d is well�formed and yields the type environment ��

Examples� �� y � bool � �letx � int � �in�x � x�ory� � bool

�� y � bool � �x � int � if y then � else � y � int � x � �� � fx � int� y � intg

Rules�

Constants�

Numbers� � �V m � int

Truthvalues� � �V t � bool

Expressions�

Constants� � �V con � � � � �V con � � �this makes sense��

Variables� � �V x � ��x�

Negation� � �V e � bool � � �V �e � bool

Binary Operations�� �V e� � ��� �V e� � ��� �V e� bop e� � �

�if � � �� �bop���

Conditional� � �V e� � bool� � �V e� � �� � �V e� � �� � �V if e� then e� else e� � �

De�nition�� �V d � �� ���� �V �V� e � �

� �V let d in e � ��where � � V��

Note that this allows the type of variables to be rede�ned�

De�nitions�

Nil� � �V nil � �

Simple� � �V e � � � � �V �x � � � e� � fx � �g

Sequential�� �V d� � ��� ����� �V �V� d� � ��

� �V �d� d�� � �������where � � V��

Simultaneous�� �V d� � �� � �V d� � ��� �V �d� and d�� � ��� ��

�if DV�d�� � DV�d�� � ��

Page 68: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS �

Private�� �V d� � ��� ����� �V �V� d� � ��

� �V �d� in d�� � ���where �� � V��

It is hoped that these rules are self�explanatory� It is useful to de�ne for any V and � � Vand e with FV�e� � V the property of being well�formed

WV �e� �� � �� � �V e � �

and also for any V � � � V and d with FV�d� � V the property of being well�formed

WV �d� �� � �� � �V d � ��

Dynamic Semantics

If x has type � in environment � hen in the corresponding it should be the case that �x�also has type � that is if � � int� then we should have �x� � N and otherwise �x� � T� Tothis end for any V and � � V and � V �� N� T we de�ne�

� � � �x � V� ���x� � int � �x� � N� ���x� � bool � �x� � T

and put Env� � f � V �� N �T j � �g� Note that if � � �� and � � �� then �� �� � ������and so too that �if it makes sense� � �� �� � ���� ����

Con�gurations� We separate out the various syntactic categories according to the possibletype environments�

Expressions� form every � � V we put �� � fe j wV �e� ��gandT� � N� T�

De�nitions� we add the production d ��� as before �but with rho ranging over theP� Env�� and then for every � � V we put �� � fd jWV �d� ��g and T� � �

Transition relations�

Expressions� For every � � V we have the relation where � � and e� e� � ���

�� e �� e�

De�nitions� For every � � V we have the relation where � � and d� d� � ���

�� d �� d�

Rules� The rules are much as usual but with the normal constraints that all mentioned ex�pressions and de�nitions be con�gurations and environments be of the right type�environment�here are three examples which should make the others obvious�

Expressions�

Page 69: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

De�nition �� � �� ����� e �� e�

�� let � in e �� let � in e��where � � ���

De�nitions�

Simple �� �� x � con �� fx � cong

Sequential �� � �� ����� d� �� d�� �� � � d� �� � d��

�where � � ���

Example�

fx � tt� y � �g �fx�bool�y�intg let private�x � int � � and y � int � ��with in z � int � x� yin if x then y � z else y

��� let private fx � �� y � �gwith in z � int � x � yin if x then y � z else y

��� let private fx � �� y � �gwith in fz � �gin if x then y � z else y

�� let fz � �g in if x then y � z else y��� let fz � �g in y � z��� ��

Declarations in Imperative Languages

The ideas so far developed transfer to imperative languages where we will speak of declarations�of identi�ers� rather than de�nitions �of variables�� Previously we have used stores for imper�ative languages and environments for applicative ones� although mathematically they are thesame � associations of values to identi�ers!variables� It now seems appropriate� however� to useboth environments ans stores the former shows what does not vary and the latter what doesvary when commands are executed�It is also very convenient to change the de�nitions of stores by introducing an �arbitrary

in�nite set� Loc� of locations �� references � cells� and taking for any L � Loc

StoresL � L �� Values

and

Stores �XL

StoresL � � Loc ���n Values�

and putting

Env � ld ���n �Values � Loc�

Page 70: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS �

The idea is that if in some environment we have an identi�er x whose values should notvary the �x� � that value otherwise �x� is a location� l� and given a store � � L �with lin L� then �l is the value held in the location l �its contents�� In the �rst case we talk ofconstant identi�ers and in the second we talk of variable identi�ers� The former are introducedby constant declatarions like

const x � �

and the latter by variable declarations like

var x � �

In all cases declarations will produce new �little� environments� just as before� The generalform of transitions will be�

�l hd� �i �� hd�� ��i

where is the elaboration environment and �� �� are the stores� So� for example we will have

�l hconst x � �� �i �� hfx � �g� �i

and

�l hvar x � �� �i �� hfx � lg� ��l � ��i ���

where l is a certain �new� location� Locations can be thought of as �abstract addresses�where we do not really want to commit ourselves to any machine architecture� but only tothe needed logical properties� Abetter way to think of a location is as an individual or objectwhich has lifetime ��extent� it is created in a transition such as �$� and its lifetime continueseither throughout the entire computation �execution sequence� or until it is deleted �� disposedof� �the declaration being achieved either through such mechanisms as block exit or throughexplicit storage management primitives in the language�� Throughout its lifetime it has a�varying� contents� generally an ordinary mathematical values �or perhaps other locations��It is generally referred to by some identi�er and is then said to be the L�value �or left�handvalue� of the identi�er and its contents� in some state� is the R�value�right�hand value� of theidenti�er� in that state� The lifetime of the location is related to� but logically distinct fromthe scope of the identi�er� Thus we have a two�level picture

� ��

� � �

���������������������HH��HH��

���������������������� ���������������������HH��HH��

����������������������xp

ls

identi�er

environment

location

store

value

v

Page 71: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� DEFINITIONS AND DECLARATIONS

The L!R value terminology comes from considering assignment statements

x �� y

where on the left we think of x as referring to a location and on the right as referring to avalue� Indeed we analyse the e�ect of assignment as changing the contents of the location tothe R�value of y�

� hx �� y� �i �� �� x � �� y��

This is of course a more complicated analysis of assignment than in Chapter�� the L!R ter�minology is a little inappropriate in that some programming languages write their assignmentsin the opposite order and also in that not all occurrences on the left of an assignment arereferences to L�values� The general idea of locations and separation of environments and storescomes from the Scott�Strachey tradition �e�g� �Gor� Ten� Led�� it is also reminiscent of ideasof individuals in modal logic �Hug�� In fact we do not need locations for most of the problemswe encounter in the rest of later concepts such as

Static binding of the same global variables in di�erent procedure bodies �storage sharing��

Call�by�reference �aliasing problems��

Arrays �location expressions��

Reference types �anonymous references��

On the other hand it would be interesting to see how far one can get without locations and towhat extent programming languages would su�er from their excision �see �Don��Rey��� One canargue that it is the concept of location that distinguishes imperative from applicative languages�We now make all this precise by considering a suitable mini�language�

Syntax�

Basic Sets�

Types� � � Types � fbool� intg

Numbers� m�n � N

Truthvalues� t � T

Identi�ers� x� y� z � Id

Binary Operations� bop � Bop

Derived Sets

Constants� con � Con where con ��� m j t

Expressions� e � Exp where

e ��� con j x j �e j e� bop e� j if e� then e� else e�

Page 72: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS �

Declarations� d � Dec where

e ��� nil j const x � � e j var x � � � e j d� d� jd� and d� j d� in d�

Commands� c � Com where

e ��� nil j x �� e j c� c� j if e then c� else c� jwhile e do c j d c

Note� On occasion we write begin c end for �c�� That is begin � � � end act as commandparentheses� and have no particular semantic signi�cance� However� their use can make scopesmore apparent�

The whole of out discussion of de�ning applied and free and bound occurrences caries overto commands and is illustrated by the command in �gure ��

���

���

����

var x � bool � tt

begin

y � � if x then � else z

x � � tt or v

end

const z � bool � if � �x ��� then tt else v

var y � int � if x then � else z

Bindings

Note that left�hand variable occurrences in assignments are applied� not binding�

Static Semantics

Identi�ers� For expressions we need the set� FI�e�� of identi�ers occurring freely in e �de�nedas usual�� For declarations we need the sets FI�d� and DI�d� of identi�ers with free andde�ning occurrences in d they are de�ned just like in the case of de�nitions and of course

FI�const x � � � e� � FI�var x � � � e� � FI�e�DI�const x � � � e� � DI�var x � � � e� � fxg

For commands we only need FI�c� de�ned as usual plus FI�d c� � FI�c�nDI�d��

Page 73: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� DEFINITIONS AND DECLARATIONS

Type Checking� We take

TEnv � Id ���n �Types � Types � flocg��

and write � � I for any � in TEnv with domain I � Id� The idea is that ��x� � � means thatx denotes a value of type � � whereas ��x� � � loc � � h�� loci� means that x denotes a locationwhich holds a value of type � �

Assertions�

Expression� For each l and expression e with FI�e� � I and type�environment � � I wede�ne

� �I e � �

meaning that given � the expression e is well�formed and of type � �

Declarations� Here for each I and declaration d with FI�d� � I and type�environment� � I we de�ne

� �l e � �

meaning that given � the declaration d is well�formed and yield the type�environment ��

Commands� Here for eacg I and command c with FI�C� � I and type�environment� � I we de�ne�

� �I c

meaning that given � the command c is well�formed�

Rules�

Expressions� As usual except for identi�ers where�

Identi�ers� � �l x � � �if ��x� � � or �x � � loc�

Declarations� Just like de�nitions before� except for simple ones�

Constants�� �l e � �

� �l const x � � � e � fx � �g

Variables�� �l e � �

� �l var x � � � e � fx � �g loc

Commands� The rules are similar to those in Chapter �� We give an illustrative sam�ple�

Nil� � �l nil

Page 74: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS �

Assignment�� �l e �

� �l x �� e�if ��x� � � loc�

Sequencing�� �l c� � �l c�

� �l c� c�

Blocks�� �l c� ���� �l�l� c

� �l d c�where � � l��

Dynamic Semantics

Following the ideas on environments and stores we consider suitably typed locations and assumewe have for eacs � in�nite sets

Loc�

which are disjoint and that �in order to create new locations� we have for each l � Loc� alocation New� �l� �� l �the new property��

Note� It is very easy to arrange these matters� Just put Loc� � N � f�g and New� �l� �h�m�hm� �i �� l� �i�

Now putting Loc ���

Loc� we take for

Stores � f� � L � Loc ��fin Con j � j� Locint � L���l� � N � j� Locbool � L���l� � T

�as Con is the set of values�� And we also take

Env � Id ���n Con � Loc

For any � l and � � l we de�ne � � by�

� � � �x � l���x� � bool �x�inT� � ���x� � int �x� � N�� � � �����x� � � loc �x� � Loc�

Transition Relations�

Expressions� For any � � I we set

�� � fhe� �i j ��� �l e � �gT� � fhcon� �ig

and for any � � I we will de�ne transition relations of the form

�� he� �i �� he�� ��i

where � � and he� �i and he�� ��i are in ���

Page 75: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� DEFINITIONS AND DECLARATIONS

Declarations� We extend Dec by adding the production

d ���

and putting FI� � � � and DI� � � I �where � I�� and putting � �I � � �where � ���Now for any � � I we take

�� � fhd� �i j � � � �l d � �g and T� � � � �

and the transition relation has the form

�� hd� �i �� hd�� ��i

where � � and hd� �i and hd�� ��i are in ���

Commands� For any � � l we take

�� � fhc� �i j � �l cg � f�g and T� � f�g

and the transition relation has the form

�� hc� �i �� hc�� ��i �or ���

where � � and hc� �i and hc�� ��i �or ��� are in ���

Rules�

Expressions� These should be fairly obvious and we just give some examples�

Identi�ers� �� �� hx� �i �� hcon� �i �if �x� � con�

�� �� hx� �i �� hcon� �i� �if �x� � l and ��l� � con�

Conditional� �� �� he�� �i �� he��� �

�i

�� hif e� then e� else e�� �i �� hif e�� then e� else e�i

�� hif tt then e� else e�� �i �� he�� �i

�� hif � then e� else e�� �i �� he�� �i

Declarations�

Nil� �� hnil� �i �� h�� �i

Constants� �� �� he�� �i �� he�� ��i

�� hconst x � � � e� �i �� hconst x � � � e�� ��i

�� �� hconst x � � � con� �i �� hfx � cong� �i

Variables� Informally to elaborate var x � � � e from state � given

�� Evaluate e from state � given yielding con�

�� Get a new location l and change � to ��l � con� and yield fx � lg

Page 76: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS �

Formally

�� �� he�� �i �� he�� ��i

�� hvar x � � � e� �i �� hvar x � � e�� ��i

�� �� hvar x � � � con� �i �� hfx � lg� ��l � con�i�where � � L and l � New� �L � Loc� ��

Sequential� �� �� hd�� �i �� hd��� �

�i

�� hd� d�� �i �� hd�� d�� ��i

�� � �� ����� hd�� �i �� hd��� �

�i

�� h � d�� �i �� h � d��� ��i�where � � ���

�� �� h � �� �i �� h �� ��� �i

Private� ��!�� Like Sequential

�� �� h � in �� �i �� h �� �i

Simultaneous� �� Like Sequential

�� �� hd�� �i �� hd��� �

�i

�� h � and d�� �i �� h � and d��� ��i

�� �� h � and �� �i �� h � � ��i

Note� These de�nitions follow those for de�nitions very closely�

Commands� On the whole the rules for commands are much like those we have alreadyseen in Chapter ��

Nil� �� hnil� �i �� �

Assignment� �� he� �i ��

� hcon� ��i

�� hx �� e� �i �� ��l � con�where �x� � l� and if l � L where � � L�

Composition� ��!�� Like Chapter �� but with rho�

Conditional� While� Like Chapter �� but with rho�

Blocks� Informally to execute d c from � given

�� Elaborate d from � given yielding � and a store ���

�� Execute C from � given � �� yielding ���� Then ��� is the result of

the execution�

�� �� hd�� �i �� hd��� �

�i

�� hd� c� �i �� hd�� c� ��i

�� � �� ����� hc� �i �� hc�� ��i

�� h � c� �i �� h � c�� �i�� � � ���

�� � �� ����� hc� �i �� ��

�� h � c� �i �� ��

In the above we have not connected up and �� In principle it could happen either that

Page 77: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� DEFINITIONS AND DECLARATIONS

�� There is an l in the range of but not in the domain of �� This is an example of adangling reference� They are also possible in relation to a con�guration such as hc� �iwhere l occurs in c �via some � but not in the domain of ��

�� There is an l not in the range of but in the domain of �� And similarly wrt c and ��etc� This is an example of an inaccessible reference� However� we easily show that if forexample that the language has no storage insecurities� As easy way to obtain a languagewhich is not secure is to add the command

c ��� dispose�x�

with the dynamic semantics

�� hdispose�x�� �i �� �nl �where l � �x��

�and �nl � �nfhl� ��l�ig� �and obvious static semantics�� One might wish to add an errorrule for attempted assignments to dangling references�

On the other hand according to out semantics we do have inaccessible references� Forexample a block exit

� hvar x � bool � tt�begin nil end� �i �� hfx � lg nil� ��l � tt�i�� ��l � tt�

Another example is provided by sequential or private de�nitions� e�g�

� hvar x � bool � tt varx � bool � tt� �i �� hfx � l�g var x � bool � tt� ��l� � tt�i�� hfx � l�g fx � l�g� ��l� � tt� l� � tt�i�� hfx � l�g� ��l� � tt� l� � tt�i

and again

� hvar x � bool � ttin vary � bool � tt� �i��� hfx � l� in y � l�g� ��l� � tt� l� � tt�i�� hfy � l�g� ��l� � tt� l� � tt�i

It is not clear whether inaccessible references should be allowed� They can easily be avoided�at the cost of complicating the de�nitions� by �pruning� them away as they are created� a kindof logical garbage collection� We prefer here to leave them in� for the sake of simple de�nitions the do not� unlike dangling references� cause any harm�The semantics for expressions is a little more complicated than necessary in that if �

he� �i �� he�� ��i then � � �� that is there are no side�e�ects� However� the extra generalitywill prove useful� For example suppose we had a production�

e ���begin cresult e

Page 78: G D Plotkin - people.cs.uchicago.edu

���� TYPE�CHECKING AND DEFINITIONS

To evaluate begin c result e from � given one �rst executes c from � given yielding �� andthen evaluates e from �� given � The transition rules would� of course� be�

�� hc� �i �� hc�� ��i

�� hbegin c result e� �i �� hbegin c� result e� ��i �� hc� �i �� ��

�� hbegin c result e� �i �� he� ��i

�and the static semantics is obvious��With this construct one also has now the possibility of side�e�ects during the elaboration

of de�nitions previously we had instead that if

�V hd� �i �� hd�� ���i

then �� jL� � where � � L�We note some other important constructs� The principle of quali�cation suggests we include

expression blocks�

e ��� let din e

with evident static semantics and the rules�

�� hd� �i �� hd�� ��i

�� hlet d in �i �� hlet d� in ��i ����� he� �i �� he�� ��i

�� hlet � in e� �i �� hlet � in e�� ��i�where � � ���

�� hlet � in con� �i �� hcon� �i

As another kind of atomic declaration consider

d ��� x �� y

meaning that x should refer to the location referred to by y �in �� The relevant static semanticswill� of course� be�

DI�x �� y� � fxg FI�x �� y� � fyg� �l x �� y � fx � � locg �if ��y� � � loc�

and the dynamic semantics is�

�� hx �� y� �i �� hx � l� �i �if �y� � l�

This construct is an example where it is hard to do without locations more complex versionsallowing the evaluation of expressions to references will be considered in the next chapter�

Page 79: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� DEFINITIONS AND DECLARATIONS

It can be important to allow initialisation commands in declarations such as

d ��� dinitial

cend

and the static semantics is�

DI�d initial c end � � DI�d� FI�d initial c end� � FI�d� � �FI�c�nDI�d��

and

� �l d � � ���� �l�l� c

� �l d initial c end � ��if � � l��

However� we may wish to add other conditions�like the drastic FI�c� � DI�d�� to avoid side�e�ects� The dynamic semantics is�

�� hd� �i ��� hd�� ��i

�� hd initial c end� �i �� hd� initial c end� ��i ����� hc� �i �� hd�� ��i

�� h � initial c end� �i �� h � initial c�� ��i�where � � ���

����� hc� �i �� sigma�

�� h � initial c end� �i �� h �� ��i

In the exercises we consider a dual idea of declaration �nalisation commands which areexecuted after the actions associated with the scope rather than before the scope of the decla�ration�Finally� we stand back a little and look at the various classes of values associated with our

language�

Expressible Values� These are the values of expressions� In our language this set� EVal�is just the set� Con� of constants�

Denotable Values� These are the values of identi�ers in environments� Here the set�DVal� is the set Con � Loc of constants and locations� Note� that Env � Id ���n DVal�

Storeable Values� These are the values of locations in the store� Here� the set� SVal� isthe set Con of constants� Note� that Stores is the set of type�respecting �nite maps fromLoc to SVal�

Thus we can consider the sets EVal� DVal� SVal of expressible� denotable and storeable values languages can di�er greatly in what they are their relationship to each other �Str�� Other classesof values � e�g� writeable ones � may also be of interest�

Page 80: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES

��� Exercises

� It is possible to formalise the notion of occurrence� An occurrence is a sequence l �m� � � � mn�n � �� of nonzero integers� For any expression� e� �say in the �rst languageof Chapter �� and occurrence� l� one has the expression el � Occ�e� l� occurring in e at l�it may not be de�ned�� For example

Occ�e� �� � e

Occ�let x � e� in e�� m � l� �

���������Occ�x� l� �m � ��Occ�e�� l� �m � ��Occ�e�� l� �m � ��unde�ned �otherwise�

De�ne Occ�e� l� in general� De�ne FO�x� e� � the set of free occurrences of x in e and alsothe sets AO�x� e� and BO�x� e� of applied and binding occurrences of x in e� For any l inBO�x� e� de�ne Scope�l� � the set of applied occurrences of x in the scope of l for anybound occurrence� l� of x in e �i�e� l in �AO�x� e� � BO�x� e��nFO�x� e�� de�ne binder�l�the unique occurrence in whose scope l is�

� Repeat exercise � for the other languages in Chapter � �and later chapters���

� Ordinary mathematical language also has binding constructions� Notable are such exam�ples as integration and summation�Z y

Z x

�f�n� dn dx and

Xn��

anxn

De�ne mathematical expression language with these constructs and then de�ne free vari�ables and occurrences etc� just as in exercise ��

� The language of predicate logic also contains binders� Given a syntax for arithmeticexpressions �say� we can de�ne formulae by�

F ��� e � e j e � e j � � � j �F j F � F j F F j F � F j �xF j xF

where ���� mean logical and� or and implies and to assert �xF means that for all xhave F and to assert xF means that we have F for some x� Repeat the work of exercise� for predicate logic� To what extent is it feasible to construct an operational semanticsfor the languages of exercise � and �� How would it help to only consider �nite sums�display

Pa�n�b e and quanti�cations �x � b�F and piecewise approximation�

� Can you specify the location of dynamic errors� Thus starting from c� � suppose wereach c�� �� and the next action is �for example� division by zero then we want to specifyan error occurred as some occurrence in the original command c� �Hint� add a labellingfacility� c ��� L �� c and tradition rules for it� and start not from c bur a labelled versionin which the occurrences are used for labels��

Page 81: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

De�ne the behaviour and equivalence of de�nitions and expressions of th second languageof this chapter prove that the program constructs respect equivalence� Establish of refuteeach of the following suggested equivalences

d� and �d� and d�� � �d� and d�� and d�d� and d� � d� and d�d� and nil � d�d� and nil � nil

and similar ones for private and sequential de�nition�

� Show that the following right�deftributive law

d� in �d� and d�� � �d� in d�� and �d� and d��

holds� What about the left�distributive law� What about other such laws� Show thatd� in �x � e� � x � let d� d� � d� in �d� and dV � where V � DV�d��nDV�d�� and wherefor any V � fx�� � � � � xng we put dV � x� � x� and � � � � � � and xn � xn� Conclude thatany d can be put� to within equivalence� in the form x� � e� and � � � and xn � en�

� Show that let d� d� � e � let d� in �let d� in e�� Under what general conditions do wehave d� d� � d� d�� When do wh have d� d� � d� in d�� When do we have let d� d�in e � let d� in d� in d� e�

� It has been said that in blocks like let d� in e all free variables of e should be bound byd for reasons of programming readibility� Introduce strict blocks let d� in e and d� in d�where it is required that FV�e� �resp� FV�d��� � FV�d��� Show that the non�strict blocksare easily de�ned in terms of the strict ones� �Hint� use simultaneous de�nitions and thedV of exercise �� Investigate Equivalences for the strict constructions�

� Two expressions �of the �rst language of the present chapter� e and e� are � � equivalent �written e �� e� � if they are identical �up to renaming of bound variables�� For example

let x � e in let y � e� in x � y �� let y � e in let x � e� in y � x

but let x � e in x � y ��� let y � e in y � y� De�ne � � equivalence��Hint� fora de�nition by structural induction to show let x � e� in e� �� let y � e�� in e�� itis necessary to show some relation between e� and e��� So de�ne � � e �� e� where� � FV�e� �� FV�e�� is a bijection this relation means e is � � equivalent to e� up to therenaming� �� of the free variables�� Show that e �� e� implies e � e�� Show that forany e there is an e� with e �� e� and no bound variable of e� in some speci�ed �nite setand no variable of e� has more than one binding occurrence�

�� De�ne for the �rst language of the present chapter the substitution of an expression efor a variable x in the expression e� � written �e�x�e� in the substitution process no free

Page 82: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ��

variable of e� should be captured by a binding occurrence in e�� so that some systematicrenaming of bound variables will be needed� For example we could not have

�x�y� let x � e in x � y � let x � �x�y� e in x � x

but could have

�x�y� let x � e in x � y � let z � �x�y� e in z � x

where z �� x� Show the following

let x � e in e� �� let y � e in �y�x�e� �if y �� FV�e����e�x��e��y�e�� �� ��e�x�e

��y��e�x�e�� �if x �� y��e�x��e��y�e�� �� ��e�x�e

��x�e��

�e�x�e� �� e� �if x �� FV�e���FV��e�x�e�� � FV�e� � �FV�e��nfxg��e�x�e� � let x � e in e��

�� By using substitution we could avoid the use of environments in the dynamic semanticsof the �rst language of the present chapter� The transition relation would have the forme �� e� for closed e� e� �no free variables� and the rules would be as usual for binaryoperations� none �needed� for identi�ers� and let x � e� in e� �� �e��x�e�� Show thisgives the same notion of behaviour for closed expressions as the usual semantics�

�� Extend the work of exercises ��� �� and �� to the second language of the present chapter�

�� It is possible to have iterative constructs in applicative languages� Tennent has suggestedthe construct

e � for x � e� to e� op bop on e�

So that for example if e� � � and e� � n op � � and e� � x � x then e �X

��x�n

x � x�

Give the operational semantics of this construct�

�� It is even possible to use de�nitions to obtain analogues of while loops�Consider thede�nition construct

d � while e do d

So that

let privatex � � and y � �within while y �� n

do x � x � y and y � y � �in x

computers n� for n � �� Give this construct a semantics show that the construct ofexercise �� can be de�ned in terms of it� Is the new construct a �good idea��

Page 83: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

� Consider the third language of the present chapter� Show that the type�environmentsgenerated by de�nitions are determined by de�ning by SI a partial function DTE� De��nitions �� TEnv and then proving that for any �� V� d� ��

� �V d � � � DTE�d� is de�ned and equal to ��

�� Give a semantics to a variant of the third language in which the types of variables arenot declared and type�checking is dynamic�

�� Change the fourth language of the present chapter so that the atomic declarations havethe more usual forms�

const x � e and var x � �

Can you type�check the resulting language� To what extent can you impose in thestatic semantics the requirement that variables should be initialised before use� Give anoperational semantics following one of the obvious alternatives regarding initialisation aatdeclaration�

�� The variable is initialised to a conventional value �e�g� �!��� or an unlikely one �e�g�the maximum integer available!���

�� The variable is not initialised at declaration� �Hint� use unde�ned maps for stores or�equivalently� introduce a special UNDEF vallue into the integers �and another fortruthvallues�� In this case show how to specify the error of access before initialisation�Which alternative do you prefer�

�� In PL!I identi�ers canbe declared to be �EXTERNAL� as such they take their valuefrom an external environment � and so the declaration is an applied occurrence � butthey have local scope � and so the declaration is also a binding occurrence� For exampleconsider the following fragment in an extension of our fourth minilanguage �not PL!II��where we allow d ��� external x � ���

externalx � int begin

x �� � var x � int

beginx �� � external x � int begin

y �� xend

endend

this sets y equal to �� Give a semantics to external declarations�

Page 84: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ��

� In PL!I variables can be declared without storage allocation begin make until explicitlyrequested� Thus a program fragment like

var x � intbegin

x �� � allocate�x�end

would result in a dynamic error under that interpretation of variable declaration� Give asemantics to this idea�

�� In the programming language EUCLID it is possible to declare identi�ers as pervasive�meaning that no holes are allowed in their scope � they cannot be redeclared within theirscope� Formulate an extension of the imperative language of this chapter which allowspervasive declarations and give it a static semantics� Are they any problems with itsdynamic semantics�

�� Formalise Dijkstra�s ideas on scope as presented in section �� of his book� A Discipline ofProgramming �Prentice�Hall� ���� To do this de�ne and give a semantics to a variantof the fourth minilanguage which incorporates his ideas in as elegant a way as you canmanage�

�� Suppose we have two �avoours of variable declaration

local var x � � and heap var x � �

�cf PL!I� Algol ���� From an implementation point of view local variables are allocatedspace on the stack and heap ones on the heap from a semantical point of view thelocations are disposed of on block exit �i�e� they live until the end of the variable�s scopeis reached� or never �unless explicitly disposed of�� Formalise the semantics for theseideas� Does replacing local by heap make any di�erence to a program�s behaviour� Ifnot� �nd some language extensions for which it does�

�� Add to the considerations of exercise �� the possibility

static var x � �

Here� the locations are allocated as part of the static semantics �of FORTRAN ! COBOL! PLI��

�� Consider the �nalisation construct d � d��nal c� Informally to elaborate this from anenvironment one elaborates d� obtaining � but then after the actions �whether elabora�tion� execution or evaluation� involved in the scope of d one executes c in the environment � � � ���equivalently� one executes

� c�� Give an operational semantics for an exten�sion of the imperative language of the present chapter by a �nalisation construct� �Hint�the elaboration of declarations should result in an environment and a command �with nofree identi�ers��� Justify your treatment of the interaction of �nalisation and the variouscompound de�nition forms�

Page 85: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

� How far can you go in treating the constructs of the imperative language of this chapter�or later ones� without using locations� One idea would be for declarations to producecouples � � � of environments and stores �in the sense of Chapter ��� where � l�� � �l� and l� � l� � �� What problems arise with the declaration x �� y�

�� Formalise the notion of accessibility of a location and of a dangling location by de�ningwhen given an environment and a con�guration hc� �i �or hd� �i or he� �i� a location�l� is accessible� De�ne the notion of lifetime with respect to the imperative language ofthe present chapter� Would it be best to de�ne it so that the lifetime of a location endedexactly when it was no longer accessible or dangling� Using your de�nition formulate andprove a theorem� for the immmmperative language� relating scope and lifetime�

�� Locations can be considered as �dynamic place holders� �in the execution sequence� justas we considered identi�ers as �static place holders��in program text�� Draw some arrowdiagrams for locations in execution sequences to show their creation occurrences analogousto those drawn in this chapter to show binding occurrences�

�� De�ne ��equivalence for the imperative programming language of the present chapter�see exercise ���� One can consider c �� c� as saying that c and c� are equivalent up tochoice of static place holders� De�ne a relation of location equivalence between couplesof environments and con�gurations� written � � �l �� �� �where � is an expression�command or declaration con�guration� It should mean that the couples are equivalentuup to choice of locations �dynamic place holders�� For example

fx � l�g� hfy � l�g x �� x � y� fl� � �� l� � �gi �l

fx � l�g� hfy � l�g x �� x � y� fl� � �� l� � �gi

holds�

� De�ne the behaviour of commands� expressions and declarations and de�ne an equivalencerelation �l between behaviours which should re�ect equality of behaviours up to choiceof dynamic place holders� Prove� for example� that

�var x � int � � var y � int � �� �l �var y � int � � var x � int � ��

even although the two sides do not have identical behaviours� Investigate the issues ofexercises ��� ��� and �� using �l�

��� Remarks

The idea of structuring de�nitions and declarations seem to go back to Landin �Lan� and Milneand Strachey �Mil�� The idea of separating environments and stores� via locations� can alsobe found in �Mil�� The concepts of scope� extent� environments� stores and their mathematicalformulations seem to be due to Burstall� Landin� McCarthy� Scott and Strachey� �I do not want

Page 86: G D Plotkin - people.cs.uchicago.edu

���� BIBLIOGRAPHY ��

to risk exact credits� or exclude others � � � � For another account of these matters see �Sto�� Theideas of ��� on static semantics where the constraints are clearly con�text�sensitive in generalwere formulated in line with the general ideas on dynamic semantics� In fact� they are simpleras it is only needed to establish properties of phrases rather than having relations between them�lt is hoped that the method is easy to read and in line with one�s intuition� There are manyother methods for the purpose and for a survey with references� see �Wil�� It is also possibleto use the techiques of denotational semantics for this purpose �Gor� Sto�� Our method seemsparticularly close to the production systems of Ledgard and the extended attribute grammarsused by Watt one can view� in such formulae as � �V d � �� the turnstile symbols � and Vas inherited attributes and � as a synthesized attribute of the de�nition d obviously too thetype�environments � and � are nothing but symbol tables� It would be interesting to comparethe methods on a formal basis� As pointed out in exercise �� one can go quite far withoutusing locations� Donahue also try to avoid them in �Don�� In a �rst version of our ideas we alsoavoided them� but ran into unpleasantly complicated systems when considering shared globalvariables of function bodies� As pointed out in exercise �� one can try to avoid environmentsby using substitutions it is not clear how far one can go in this direction �which is the usualone in syntactic studies of the �calculus�� However� we have made a de�nite decision in thesenotes to stick to the Scott�Strachey tradition of environments� Note that in such rules as

let x � e� in e� �� �e��x�e�

there is no o�ense against the idea of syntax�directed operational semantics� It is just thatsubstitution is a rather �heavy� primitive and one can argue that the use of environments iscloser to the intuitions normally used for understanding programming languages� �One awfulexception is the Algol��� call�by�name mechanism��

��� Bibliography

�Ack� W�B� Ackerman ��� Data Flow languages Proc� �� AFIPS

�Don� J�E� Donahue ��� Locations Considered Unnecessary Acta Inf� �� pp��������

�Gor�� M� Gordon� R� Milner and C� Wadsworth ��� Edinburgh LCF� Vol� �� SLNCS

�Gor�� M� Gordon ��� The Denotational description of Programming Languages Springer�Verlag

�Hin� J�R� Hindley� B� Lercher and J�P� Seldin ���� introduction to Combinatry Logic CUP

�Hug� G�E� Hughes and M�J� Cresswell ��� An introduction to Modal Logic

�Lan�� P�J� Landin ����� The Mechanical Evalution of Expressions Computer Journal Vol��� pp� �������

�Lan�� P�J� Landin ����� A Correspondence between Algol �� and Churchs Lamdba�Notation

CACM� Vol� �

Page 87: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� DEFINITIONS AND DECLARATIONS

�Led� H� Ledgard and M� Marcotty ����� The Programming Language Landscape Science

Research Associates

�Mil� R�E� Milne and C� Strachey ���� A Theory of Programming Language Semantics

Chapman and Hall

�Pra� D� Prawitz ���� Ideas and Results in Proof Theory Proc� �nd Scand� Logic Congress�North Holland

�Rey� J�C� Reynolds ���� Syntactic Control of Interference �th POPL� ACM� pp� ����

�Str� C� Strachey ���� The Varieties of Programming Languages PRG���� Prog� Res�Group� University of Oxford

�Sto� J�E� Stoy ��� Denotational Semantics MIT Press

�Wil� M�H� Williams ����� Methods for Specifying Static Semantics Computer Languages

Vol��� pp� �� �

Page 88: G D Plotkin - people.cs.uchicago.edu

Chapter �

Functions� Procedures and Classes

In this chapter we consider various mechanisms allowing various degrees of abbreviation andabstraction in programming languages� The idea of abbreviating the repeated use of someexpressions by using de�nitions or declarations of identi�ers was considered in chapter three ifwe apply the same choice to commands we arrive at �parameterless� procedures �� subroutines��It is very much more useful to abstract many similar computations together� di�erent ones beingobtained by varying the values of parameters� In this way we obtain functions from expressionsand procedures from commands�Tennent�s Principle of Abstraction declares that the same thing can be done with any

semantically meaningful category of phrases� Applying the idea to de�nitions of declarationswe obtain a version of the class concept� introduced by SIMULA and recently taken up inmany modern programming languages� �If we just use identi�ers to stand for de�nitions ordeclarations we obtain the simpler but still most useful idea of module��

Calling �� invoking� abstractions with actual parameters �their arguments� for the formalones appearing in their de�nition results in appropriate computations whether evaluations�executions or elaborations of the bodies of their de�nitions� We will explain this by allowingabstraction identi�ers to denote closures which record their formal parameters and bodies�Invocations will be explained in terms of computations of blocks chosen in terms of Tennent�sPrinciple of Correspondence which declares that in principle to every parameter mechanismthere corresponds an appropriate de�nition or declaration mechanism� For example if we de�ne

f�x � int� � in � x � �

then the elaboration results in the environment

f � x � int� x � � � int

To invoke f in an expression� say f���� we just evaluate the expression block

letx � int � �in x� �

Note that his block exists by virtue of Tennent�s Principle of Quali�cation�

Page 89: G D Plotkin - people.cs.uchicago.edu

�� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Below we use these ideas to consider an applicative programming language with �possiblyrecursive� de�nitions of functions of several arguments� We then consider an imperative lan�guage where we consider both functions and procedures and use the Principle of Correspondenceto obtain the parameter mechanisms of call�by�constant and call�by�value� Other parametermechanisms are easily handled using the same ideas �some explicitly in the text and othersin exercises� let us mention call�by�reference� call�by�result� call�by�value�result� call�by�nameand call�by�text� Next we consider higher order functions and procedures� Finally we use thePrinciples of Abstraction and Correspondence to handle modules and classes this needs nonew ideas although some of the type�checking issues are interesting�

��� Functions in Applicative Languages

We begin with the simplest case where it is possible to de�ne functions of one argument �unary�functions� Let us consider throughout extensions of the second applicative language of Chapter�� Add the following kind of function de�nitions�

d ��� f�x � ��� � �� � e

and function calls

e ��� f�e�

where f is another letter we will use to range over variables �but reserving its use to contextswhere functions are expected��

Static Semantics

This is just as before as regards free and de�ning variables with the extensions

FV�f�x � ��� � �� � e� � FV�e�nfxgDV�f�x � ��� � �� � e� � ffgFV�f�e�� � ffg � FV�e�

It is convenient to consider types a little more systematically than before� Just as we haveexpressive and denotable value �EVal and DVal� we now introduce the sets of ETypes andDtypes� expressible and denotable types �ranged over by et and dt respectively� where

et ��� �de ��� � j �� � ��

More complex expressible types will be needed later denotable types of the form �� � �� willbe used for functions which take arguments of type �� and deliver results of type ��� Later wewill want also sets of storeable types and other such sets� Now we take

Tenv � Var ���n DTypes

Page 90: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES �

ranged over� as before� by � and � and give rules for the predicates

� �V e � et

where � � V and FV�e� � V � and

� �V d � �

where � � V and FV�d� � V � These rules are just as before with the evident extensions forfunction calls and de�nitions�

Function Call�� �V e � et�

� �V f�e� � et��if ��f� � et� � et��

Function De�nitions�� �V e � ��

� �V f�x � ��� � �� � e � f�� � ��g

Dynamic Semantics

We introduce the set� Closures� of closures �ranged over by d�

Closures � fx � et��e � et� j fx � et�g �fxg e � et�g

and de�ne the set of denotable values by

DVal � Con � Closures

and then we de�ne� as usual�

Env � Var ���n DVal

and add the following production to the de�nition for the category of de�nitions

d ���

�and put for � V � DV� � � V and FV� � � ���It is important to note that what is meant here is that the sets Dec� Exp� Closures� DVal and

Env are begin de�ned mutually recursively� For example the following is an integer expression

let f � x � int�letfy � �� g � y � bool� �y � boolgin if g�ff� then x else y� � int

andw � �in f��� � w

There is no more harm in such recursions than in those found in context�free grammars adetailed discussions is left to elsewhere�

Page 91: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Note to that closures have in an obvious sense on free variables� This raises the puzzle ofwhat we intend to do about the free variable in function de�nitions� In fact in elaborating suchde�nitions we will bind the free variables to their values in the elaboration environment� Thisis known as static binding �� binding of free variables determined by their textual occurrence��and will be followed throughout these ones� The alternative of delaying binding until thefunction is called� and then using the calling environment� is known as dynamic binding� andis considered in the exercises�To extend the static semantics we type denotable values de�ning the predicate for dval in

DVal ad dt in DType

dval � dt

and for � V in Env and � � V in TEnv de�ne

� �

by the rules

Constants� m � int t � bool

Closures� �x � et�� e � et�� � et� � et�

Environments��x � V� �x� � ��x�

� ��where � V � � � V �

and add the rule for environments considered as de�nitions

Environments� � �

� �V � �

With all this we now easily extend the old dynamic semantics with the usual transitionrelations

�� e �� e�

�� d �� d�

by rules for function calls and de�nition�

Function Calls�

�� f�e�� �� let x � et� � e� in e �if �f� � x � et�� e � et� �

This rule is just a formal version of the Principle of Correspondence for the languageunder consideration�

Function De�nition�

�� f�x � ��� � �� � e �� ff � x � ��� �let dV ine� � ��g �where V � FV�e�nfxg�

Page 92: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES �

Example� We write f�x � ��� � �� � e for the less readable f � x � ��� e � �� �and miss out��and�or�� when they are obvious�� Consider the expression

edef� letdouble�x � int� � int � � � xin double�double����

we have

� �� e �� let � double�double����

where def� fdouble�x� � � � xg and now note the computation

� double�double���� �� let x � int � double��� in double����� �� let x � int � �let x int � � in � � x�

in� � x��� let x � int � � in � � x��� �

and so

� � e ��� �

Our function calls are call�by�value in the sense that the argument is evaluated before the bodyof the function� On the other hand it is evaluated just after the function call a slight variante�ects the evaluation before�

Function Call �Amended�

�� � e �� e�

�V f�e� �� f�e��

�� � f�con� �� let x � �� � con in e �if f�x � ��� � e is in �

This variant has no e�ect on the result of our computations �prove this�� although it is nothard to de�ne imperative languages where there could be a di�erence �because of side�e�ects��Another important possibility � call�by�name � is considered below and in the exercises�We now consider how to extend the above to de�nitions of functions of several arguments

such as

max�x � int� y � int� � int � if x � y then x else y

Intending to use the Principle of Correspondence to account for function calls we expect suchtransitions as

� max��� �� ��letx � int� y � int � �� �in if x � y then x else y

and there fore simultaneous simple de�nitions� To this end we adopt a �minimalist� approachadding two syntactic classes to the applicative language of the last chapter�

Page 93: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Formals� This is the set Forms ranged over by form and given by

form ��� � j x � �� form

Actual Expressions� This is the set AcExp ranged over by ae where

ae ��� � j e� ae

Then we extend the category of de�nitions allowing more simple de�nitions and functionde�nitions

d ��� form � ae j f�form� � � � e

and adding function calls to the stock of expressions

e ��� f�ae�

To obtain a conventional notation x � � � � and e� � are written x � � and e respectively and f��replaces f���� In a �maximalist� solution we could include actual expressions as expressions andallow corresponding �tuple� types and as types of identi�ers and function results see exercise��

Static Semantics

Formals give rise to de�ning variable occurrences

DV��� � � DV�x � �� form� � fxg �DV�form�

Then we have free variables in actual expressions

FV��� � � FV�e� ad� � FV�e� � FV�ae�

and for the new kinds of de�nitions

FV�form � ae� � FV�ae� DV�form � ae� � DV�form�FV�f�form� � � � e� � FV�e�nDV�form�DV �f�form� � � � e� � ffg

and for function calls� FV�f�ae�� � ffg � FV�ae��Turning to types we now have ETypes� AcETypes �ranged over by aet� and DTypes where

et ��� � aet ��� � j �� aet dt ��� et j aet� et

Then with TEnv � Var ���n DTypes as always we have the evident predicates

� �V e � et � �V ae � aet � �V d � �

Formals give positional information and type environments� So we de�ne T � Formals ��AcETypes by

T��� � � T�x � �� form� � ��T�form�

and give rules for the predicate form � �

Page 94: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES �

�� � � �

�� form � � � �x � �� form� � fx � �g� ��ifx �� DV�form��

Note that it is here the natural restriction of no variable occurring twice in a formal is made�Here are the rules for the other predicates�

Function Calls�� �V ae � aet

� �V f�ae� � et�if ��f� � aet� et�

De�nitions�form � � � �V ae � aet

� �V �form � ae� � ��where aet � T �form��

form � � ���� �V �V� e � t

� �V �f�form� � � � e� � ff � aet �� �g�where � � V�andaet � T �form��

Actual Expr� � �V � � �� �V e � et � �V ae � aet

� �V e� ae � et� aet

Dynamic Semantics

We proceed much as before as regards closures� denotable values and environments

Closures � fform� e � et j �V� form � � and � � V and � �V e � etgDVal � Con � ClosuresEnv � Var ���n DVald ���

with the free and de�ning variables of as usual and extend the static semantics by de�ningthe predicates dval � dt and � � much as before�As regards transition rules we will naturally de�ne �V e �� e� and �V d �� d� and� for

actuals� �V ae �� ae�� The terminal actual con�gurations are the �actual constants��tuplesof constants given by the rules

acon ��� � j con� acon

As for formals they give rise to environments in the content of a value for the correspondingactuals and so we begin with rules for the predicate

acon � form �

�� � � � � �

��acon � form �

con� acon � �x � �� form� � � fx � cong

While this is formally adequate enough it does seem odd to use values rather than environmentsas dynamic contexts�The other rules should now be easy to understand�

Page 95: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Function Calls� �� f�ae� �� let form � ae in e �if �f� � form� e � et�

De�nitions Simple� �� ae �� ae�

� form � ae �� form � ae�

acon � form � � � form � acon �� �

Function� �� f�form� � � � e �� ff � form let dV in e � �g�where V � FV�e�nDV�form��

Actual Expr� �� e �� e� � �� e� ae �� e�� ae �� ae �� ae� � �� con� ae �� con� ae�

Example� We calculate the maximum of ��� and �� �� Let � � fmax�x � int� y � int� � in �let � in ifx � ythenxelseyg� Then we have

� � flet max�x � int� y � int� � int � if x � y then x else yg in max�� � �� � � ���� let � in max�� � �� � � ���� let � in let x � int� y � int � � � �� �� � in let � in �if x � y then x else y���� let � in let fx � �� y � �g in let � in �if x � y then x else y��� let � in let fx � �� y � �g in let � in ���� ��

as one sees that

� � x � int� y � int � � � �� �� � ��� fx � �� y � �g

Recursion

It will not have escaped the readers attention that no matter how interesting our applicativelanguage maybe it is useless as there is no ability to prescribe interesting computations� Forexample we do not succeed in de�ning the factorial function by

dfact� fact�n � int� � int � if n � � then � else n� fact�n� ��

as the �fact� on the right will be taken from the environment of dfact and not understoodrecursively� �Of course the imperative languages are interesting owing to the possibility ofloops note too exercise �� ��� ���Clearly we need to introduce recursion� Syntactical we just postulate a unary operator on

de�nitions �and later on declarations�

d ��� recd

Thus recdfact will de�ne the factorial function� In terms of imports and exports recd importsall imports of d other than exports which provide the rest of the imports to d the exports of recdare those of d� In other words letX � FV�d�nDV�d�andY � DV�d�andR � FV�d� � DV�d��Then X is the set of imports of recd and Y is the set of its exports with R begin de�nedrecursively� Diagrammatically we have

Page 96: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES �

� �

x yd

A Recursive Declaration� rec d

The unary recursion operator gives a very �exible way to make recursive de�nitions since thed in recd can take many forms other than simple function de�nitions like f�x � �� � � �� � � � e�Simultaneous recursive de�nitions are written

rec f�� � �� � � � � f � � � g � � �and � � �andg�� � �� � � � � f � � � g � � �

A narrow scope form of sequential recursive de�nitions is

rec f�� � �� � � � � f � � � g � � � � � � rec g�� � �� � � � � f � � � g � � �

where the g in the de�nition of f is taken from the environment but the f in the de�nition ofg is the recursively de�ned one� A wide scope form is obtained by writing

rec f�� � �� � � � � f � � � g � � � � � � g�� � �� � � � � f � � � g � � �

which is equivalent to the simultaneous de�nition unless f � g for example�

Static Semantics

For free and de�ning variables we note that

FV�recd� � FV�d�nDV�d�DV�recd� � DV�d�

We keep TEnv and DTypes� ETypes and AcETypes as before� The natural rule for recursivedeclarations is

���dV�� �V �V� d � �

� �V recd � ��where V� � FV�d� � DV�d��

However� this is not easy to use in a top�down fashion as given recd and � one would have toguess �� But� as covered by exercise ��� it would work� It is more convenient to use the factthat in � �V d � � the elaborated � does not depend on � but is uniquely determined by d� the� only begin used to check the validity of �� We make this explicit by de�ning two predicatesfor de�nitions� First for any V and d with FV�d� � V and � we de�ne

� V d � �

Page 97: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

and secondly for any � � V and d with FV�d� � V we de�ne

� �V d

The �rst predicate can be read as saying that if d is a valid de�nition then it will have type � the second says that given � then d is valid� The other predicates will be as before

� �V e � et � �V ae � aet form � �

Rules�

De�nitions�

Nil� �� �V nil � �

�� � �V nil

Simple� ��form � �

�V form � ae � �

��form � � � �V ae � T �form�

� �V form � ae

Function� �� �V f�form� � � � e � T �form� �� �

��form � � ���� �V �V� e � �

� �V f�form� � � � e�where � � V��

Sequential� ���V d� � �� �V d� � ���V d� d� � ������

��� �V d� �V d� � � ���� �V �V� d�

� �V d� d��where � � V��

Simultaneous� ���V d� � �� �V d� � ���V d� and d� � ��� ��

��� �V d� � �V d�� �V d� and d�

�if DV�d�� �DV�d�� � ��

Private� ���V d� � ��

�V d�ind� � ��

��� �V d� �V d� � �� ����� �V �V� d�

� �V d�ind��where �� � V��

Recursion� ���V d � �

�V recd � �

���V �V� d � � ���dV�� �V �V� d

� �V recd�where V� � FV�d� �DV�d��

The other rules are as before except for expression blocks�

�V d � � � �V d���� �V �V� e � et

� �V letdine � et�where � � V��

Page 98: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES

Example� Consider the de�nition

d � rec f�x � int� � int � g�x�andg�x � in� � int � f�x�

Here as �f�g f�x � int� � int � g�x� � ff � int� intg� etc� we have

�� d � ff � int� int� g � int �� intg�

Then to see that � �� d one just shows that ff � int � int� g � int � intg �f�g d� �Whererecd� � d�� This example also shows why it is needed to explicitly mention the result ��output� of functions�

Dynamic Semantics

Before discussing our speci�c proposal we should admit that this seems� owing to a certainclumsiness and its somewhat unnatural approach� to be a possible weak point in our treatmentof operational semantics�At �rst sight one wants to get something of the following e�ect with recursive de�nitions

� �dV�� ����� d ��� �

�� recd ��� ��where � � DV�d� and for suitable �� � V��

Taken literally this is not possible� For example put d � f�x � int� � int � f�x� and suppose ��f� � d� Then for V � � and �� � we would have

� �ffg f�x � int� � int � f�x� �� ff � x � int�let �inf�x�� � intg

and so we would have d � x � int� �let �inf�x�� � int which is clearly impossible as d cannotoccur in itself �via ��� Of course it is just in �nding solutions to suitable analogues of thisequation that the Scott�Strachey approach �nds one of its major achievements�Let us try to overcome the problem by not trying to guess � but trying to elaborate d

without any knowledge of the values of the recursively de�ned identi�ers� Thus in our examplewe �rst elaborate the body

� �� f�x � int� � int � f�x� �� ff � x � int� �let�f�x�� � intg

and let � be the resulting �environment�� Note that we no longer have closures as there canbe free variables in the abstractions� So we know that for any imported value of f that � givesthe corresponding export� But in recd the imports and the exports must be the same� that is

f � �f� in some recursive sense and we can take fdef� rec �� To get a closure we now take

the all important step of binding f to rec � in � and take the elaboration of recd to be

� � ff�x � int� � int � let red � in �let � inf�x�� � intg

Page 99: G D Plotkin - people.cs.uchicago.edu

� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

What we have done is unwound the recursive de�nition by one step and bound into thebody instructions for further unwinding� Indeed it will be the case that

� rec � �� �

and so when we call f�e� we will arrive at the expression

let x � int � ein let rec �

in let �in f�x� � int

Then we will evaluate the argument e� then we will unwind the de�nition once more �inpreparation for the next call��� then we will evaluate the body� This is perhaps not too bad inthe usual operational semantics of recursive de�nitions �see exercise � one �rst evaluates theargument� then unwinds the de�nition for the present call and then evaluates the body� Thuswe have simply performed in advance one step of the needed unwindings during the elaboration�Some further comments on this are given in exerciseLet us now turn our attention to the formal details� the changes form previously mostly

concern allowing free variables in closures� and we de�ne

Abstracts � fform� e � etg

and put

DVal � Con � Abstracts

and

Env � Var ���n DVal

and add

d ���

To extend the static semantics we de�ne FV�dval� by

FV�con� � � FV�form� e � et� � FV�e�nDV�form�

and then for � V

DV� � � V and FV� � ��xV

FV� �x��

Now we de�ne predicates �V dval � dt and � �V dval by

Constants� �� �V m � int

Page 100: G D Plotkin - people.cs.uchicago.edu

���� FUNCTIONS IN APPLICATIVE LANGUAGES

�� � �V m

�� �V t � bool

�� � �V t

Abstracts� �� �V form�e � et � T �form�� et

��form � � ���� �V �V� e � et

� �V form� e � et�where � � V��

Then the rules for environments � V

���x � V� �W �x� � ��x�

�W � �

���x � V� �W �x�

� �W

Turing to the transition relations we de�ne for � � V and � � W � with W � V and � �dW �and e� e�� in �� �as before�

�� e �� e�

and keep the same set �� of terminal expressions� Similarly we de�ne �� ae �� ae� and �� d �� d��The rules are formally the same as before except that for � W conditions of the form

�f� � � � � are understood to mean that f � W and �f� � � � � and similarly for �x� � � � ��this a�ects looking up the values of variables and function calls��We need rules for recursion�

�� jV� ����� d �� d�

�� recd �� recd�

�where V� � DV�D� � FV�d� and taking � from the requirement that � d � � we have�� � �nV��

�� � rec � �� fx � con j x � conin �g� ff�form� � � � let rec �nDV�form�in e j f�form� � � � e in �g

In other words we �rst elaborate d without knowing anything about the variables and thenfrom the resulting � we yield � altered to bind its free variables by rec �� Here are a coupleof examples� More can be found in the exercises�

Example �� Consider the traditional de�nition of factorial

d � fact�x � int� � int � if x � � then a else x� fact�x� ��

Then for any suitable and � we have

nffactg ����� fact�x � int� � int � � � � �� � �with �� as given above�

Page 101: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

where � � ffact�x � int� � int � let�in � � �g �and from now on we omit the tedious �let � in���Then we have

�� recd �� rec � �� �

where � � ffact�x� � let rec �in � � �gTo compute fact��� we look at the derivation

� �� let rec d in fact��� ��� let � in fact���

�� let � in let x � int � �in let rec �

in � � �

��� let � in let fx � �g inlet �in if x � � then � else � � �

��� �

Equally for fact��� we have

� �� let rec d in fact��� ��� let fx � �g in let �inif x � � then � else x� fact�x� ��

��� let fx � �g in let � in x� fact�x� ����� let fx � �g in let � in �� �let x � int � x� � in rec � in � � ����� let fx � �g in let � in �� �let x � � in rec � in � � ���� �

Example �� It is allowed to de�ne integers or truth�values recursively� For example considerd � �redx � x � ��� To elaborate d given � fx � �g we must elaborate x � x � � from nfxg � � and that elaboration sticks as we must evaluate x� � in the empty environment� Itcould be helpful to specify a dynamic error in this case� Again the elaboration of

d � rec x � fact��� and fact�x � int� � int � � � �

does not succeeds� intuitively� we need to know the value of fact before the elaboration � whichproduces this value � has �nished� On the other hand simple things like the elaboration ofrecx � � do succeed� If desired we could have speci�ed in the static semantics that onlyrecursive function de�nitions were allowed�

��� Procedures and Functions

We now consider abstractions in imperative languages� Abstract of expressions give rise tofunctions� as before� but now with the possibility of side�e�ects as in�

function f�var x � int� � int �

Page 102: G D Plotkin - people.cs.uchicago.edu

���� PROCEDURES AND FUNCTIONS ���

beginy �� y � �

result x � y

In several programming languages the bodies of functions are commands� but are treated� viaspecial syntactic devices� as expressions � see exercise ��� We take a straightforward view wherethe bodies are �clearly� expressions� Abstracts of commands give rise to procedures as in�

function f�var x � int�begin

y �� x� yend

which may also have side�e�ects and indeed are often executed for their side�e�ects� To see whywe write var in the formal parameter let us see how the Principle of Correspondence allows usto treat a procedure call� First the above declaration� d� will be elaborated thus

�� hd� �i �� hfp�var x � int� � fy � lg y �� x� yg� �i

where l � �y�� Then the procedure call p�e� in the resulting environment � will look like this

� �� hp�e�� �i �� hvar x � int � e beginfy � �g y �� x� y end� �i

And we see the reason for writing var � � � is to get an easy correspondence with our previousdeclaration mechanism� The computation now proceeds by evaluation e� �nding a new locationl�� making l� refer to the value of e in the state and then executing the body of the procedurewith x bound to l�� This is very clearly nothing else but the classical call�by�value� Constantdeclarations will give rise to a call�by�constant parameter mechanism�We begin by working these ideas out in the evident extension of the imperative language of

Chapter �� Then we proceed to other parameter mechanisms by considering the correspondingdeclaration mechanisms� �Many real languages will not possess such a convenient correspon�dence one way to deal with their parameter mechanisms would be to add the correspondingdeclaration mechanisms when de�ning the set of possible con�gurations��For the extension we drop the const x � � � e and varx � � � e productions and add�

Expressions� e ��� let d in e j f�ae� j begin c result e

Actual Expr� ae ��� � j e� ae

Declarations� d ��� form � ae j function f�form� � � � e j procedure p�form� c jrec d

Formals� form ��� � j const x � �� form j var x � �� form

Commands� c ��� p�ae�

Page 103: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Static Semantics

We have the following sets of identi�ers with the evident de�nitions and meanings� FI�e��FI�ae�� FI�d�� DI�d�� DI�form�� FI�c�� For example

FI�procedure p�form�c� � FI�c�nDI�form�DI�procedure p�form�c� � fpgFI�p�ae�� � fpg � FI�ae�

Turning to types we de�ne ETypes� AcETypes and DTypes these are as before except thatboth locations and procedures are denotable� causing a change in DTypes�

et ��� �aet ��� � j �� aetdt ��� et j et loc j aet �� et j aet proc

and of course TEnv � Id ���n DTypes� We also need T�form� � AcETypes with the evidentde�nition

� const x � �� form var x � �� form

T � �� aet �� aet

Then we de�ne the expected predicates

� �I e � et � �I ae � aet �I d � � � �I d form � � � �I c

We give some representative rules�

ProcedureDeclarations�

�� �I procedure p�form�c fp � T �form�procg

��form � � ���� �I�I� c

� �I procedure p�form�c�where � � I��

Formals� �� � j �

��form � �

constx � �� form � fx � �g � ��if x �� I� where � � I��

��form � �

varx � �� form � fx � � locg � ��if x �� I� where � � I��

Procedure Calls� ��� �I ae � aet

� �I p�ae��if ��p� � aet proc�

Page 104: G D Plotkin - people.cs.uchicago.edu

���� PROCEDURES AND FUNCTIONS ���

Dynamic Semantics

We begin with environments� abstracts and denotable values� First the set� Abstracts �rangedover by abs�� is

Abstracts � fform� e � etg � fform� cg

then

DVal � Con � Loc � Abstracts

Where Loc is the set Locint � Locbool of Chapter � and

Env � Id ��fin DVal

and we add the production

d ���

and all the above is to be interpreted recursively as usual�Then DI� � and FI� � are de�ned� Next we de�ne the evident predicates

�I dval � dt � �I dval �I � � � �I � �

as expected for example

ProcedureAbstracts�

�� �I form�c � T �form�proc

��form � � ���� �I�I� c

� �I form� c�where � � I��

Transition Relations� Turning to the transition relations we �rst need the set of stores

Stores � f� � L � Loc ���n Con j � respects typesg

� the same as in Chapter ��

Expressions� We have

�� � fhe� �i j et� � �I e � etg �for � � I�

and

T� � fhcon� �ig

and the evident relation

�� he� �i �� he�� ��i

Page 105: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Actual Expressions� we have

�� � fhae� �i j aet� � �I ae � aetg �for � � I�

and

T� � fhacon� �ig

where acon is in AeCon� as before� And we have the relation

�� hae� �i �� hae�� ��i

Declarations� We have

�� � fhd� �i j � �I dg �for � � I�

and

T� � fh � �i j h � �i � ��g

and the relation

�� hd� �i �� hd�� ��i

Formals� We de�ne

acon� L � from � � �

meaning that in the context of an actual expression constant acon and given an existingset� L� of locations the formal �part of a declaration� form yields a new �little� environment and store ��

Commands� We have

���T�

and

�� hc� �i �� hc�� ��i �or ���

as usual�

Rules� The rules are generally just those we already know and only the new points are cov�ered�

DeclarationsSimple�

�� �� hae� �i �� hae�� ��i

�� hform � ae� �i �� hform � ae�� ��i

Page 106: G D Plotkin - people.cs.uchicago.edu

���� PROCEDURES AND FUNCTIONS ���

��acon� L � form � �� ��

�� hform � ae� �i �� h �� � � ��i�where � � L�

Procedures� �� hprocedure p�form�c� �i �� hfp � form nI cg� �i�where I � FI�c�nDI�form��

Recursive� �� nR ����� �d �� d�

�� rec d �� rec c�where if �FI�d� d � � then R � FI�d� �DI�d� and � � �jR�

�� �� rec � �� �where � � fx � con j x � con in �g �

fx � l loc j x � l loc in �g �ff�form� � et � let rec �nI in e j

f�form� � et � e in � and I � DI�form�g �fp�form�� rec �nI c j

p�form�c in � and I � DI�form�g

FormalsEmpty�

�� L � � � �� �

DeclarationsEmpty�

acon� L � form � �� ���con� acon�� L � const x � �� form � � � fx � cong� ��

Variable�acon� L � fIg � form � �� ��

�con� acon�� L � var x � �� form � fx � Ig � �� fl � cong � ���where l � New� �L � Loc� �

Example� The following program demonstrates the use of private variables shared betweenseveral procedures� This provides a nice version of Algol�s own variables and anticipates thefacilities provided by classes and abstract data types� Consider the command

c �private var x � int � �withinprocedure inc�� x �� x � �

procedure dec�� if x � � then x � x� � else nil begininc�� dec��

end

First look at the declaration part� d�

� hd� �i �� hprivate fx � �g within procedure inc�� � � � procedure dec�� � � � � ��I � ��i�� hprivate fx � �g withinfinc�� � fx � �g �g procedure dec�� � � � � ��I � ��i��� hprivate fx � �g withinfinc�� � fx � �g �� dec��fx � �g � � � � ��I � ��i�� hfinc��fx � �g �� dec��fx � �g � � � � ��I � ��i

� h � ��I � ��i� say

Page 107: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

So we see that

� hc� �i ��� h � �inc�� dec���� ��I � ��i

and so we should examine the computation�

� �� � hinc�� dec��� ��I � ��i�� h�fx � �g x �� x � �� dec��� ��I � ��i��� hdec��� ��I � ��i�� hfx � �g if x � � then x �� x� � else nil� ��I � ��i��� h��I � ��i�

��� Other Parameter Mechanisms

Other parameter mechanisms can be considered in the same manner� The general principleis to admit more ways to declare identi�ers �as discussed above� and to admit more waysof evaluating expressions �and!or actual expressions�� The latter is needed because actualexpressions can be evaluated to various degrees when abstracts are called� One extreme isabsolutely no evaluation �see exercise for this call�by�text mechanism�� We shall �rst considercall�by�name in the context of our applicative language which we regard as evaluating theargument to the extent of binding the call�time environment to it this well�known idea di�ersfrom the o cial ALGOL��� de�nition and is discussed further in exercise ���Then we consider call�by�reference in the context of our imperative language where the

argument is evaluated to produce a reference� Other mechanisms are considered in the exercises�Note that in call�by�name for example the actual parameter may be further evaluated duringcomputation of the body of the abstract� It is even possible to have mechanisms �e�g� variantsof call�by�result� where some or all of the evaluation is delayed until after the computation ofthe body of the abstract�

Call�by�Name

Syntactically it is only necessary to add another possibility for the formal parameters to thesyntax of our applicative language

form ��� name x � �� form

Static Semantics

The sets of de�ning variables of name x � � � form is clearly fxg�DV�form�� Regarding typeswe add

aet ��� � name� aetdt ��� et j � name j aet� et

Page 108: G D Plotkin - people.cs.uchicago.edu

���� OTHER PARAMETER MECHANISMS ��

The de�nition of the type T�form� of a formal needs the new clause

T�name x � �� form� � � name� T�form�

Here are the new predicate rules

Formals� form � � �� �namex � �� form� � fx � �nameg � ��if x �� DV�form��

ExpressionsVariables�

� �V x � � �if ��x� � � name�

This rule expresses the fact that if x is a call�by�name formal parameter as in name x � � thenin the calling environment its denotation can be evaluated to a value of type � �

Actual Expr�� �V e � et � �V ae � aet

� �V e� ae � etname� aet

It is important to note that this rule is in addition to the previous rule� So given � an ac�tual expression can have several di�erent types these are needed as the same expressions cancorrespond to formals of di�erent types� and that will require di�erent kinds of evaluation�

Example� Consider these two expressions

let function fred �x � int�name y � int� � int � x � yin fred�u� v� u� v�

and

let function fred �name x � int� y � int� � int � x � yin fred�u� v� u� v�

in the �rst case we need the fact that � � u � v� u� v � int� intname and in the second that� � u� v� u� v � int name� int �where � � fu � int� v � intg��

Dynamic Semantics

Clearly we must add a new component to the set of denotable values� corresponding to the newdenotable types � name

DVal � Con � NExp � Abstracts

where we need NExp � fe � name �g to allow free variables in the expressions because of thepossibility of recursive de�nitions� For example consider

rec name x � int � f��� andf�x � int� � � � � f � � �

The extension to the de�nition of FV�dval� is� of course� clear

FV�e � name �� � FV�e�

For the predicates �V dval � dt and � �V dval we add the rules

�V �e � name � �� � � name� � e � �

� � e � name �

Page 109: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Transition Relations� For expressions and de�nition we re�ne the usual �� e �� e� and �� d �� d� a little� parameterizing also on the set of variables where de�nition is currentlyavailable in the environment �the others will be in the process of begin recursively de�ned�� Sofor � � V and W � V we will de�ne the relations

���W e �� e� and ���W d �� d�

where � �jW and e� e� � �exp��W and d� d� � �def��W where

�exp��W � fe j et� � �V e � etg

�def��W � fd j � �V dg

We also have the evident Texp��W and Tdef

��W �For formals we have the predicate

ae ���W form � �

where ae � T��W and � � M�T�form����For actual expressions the result desired will depend on the context and we introduce an

apparatus of di�erent evaluation modes� The set Modes of modes is ranged over by � given by

� ��� � j value� � j name� �

Each actual expression type� aet� has a mode� M�aet� where

M��� � �M��� aet� � value�M�aet�M���name� aet� � name�M�aet�

We de�ne transition relations ���W�� ae �� ae� which are also parameterized on modes� Theset of con�gurations is� for � � V � W � V and mode �

���W�� � fae j aet� � �V ae � aetandM�aet� � �g

and we de�ne the set T��W�� of terminal actual expressions by some rules of the form ���W T�ae�

�� ��W T ���

�����W T �ae�

��value����W T �con� ae�

�����W T �ae�

��name����WT �e� ae� �if FV�e� �W � ��

It is rule � which introduces the need for W �� insisting that all variables are bound� except�possibly� for those begin recursively de�ne�

Page 110: G D Plotkin - people.cs.uchicago.edu

���� OTHER PARAMETER MECHANISMS ��

The transition relation is de�ned for � �dW and ae� ae� � ���W�� and has the form ���W��

ae �� ae� � The apparatus of modes gives types what might also be called metatypes and thismay be a useful general idea� The reader should not be confused with one normal usage of theterm mode as synonymous with type�

Transition Rules�

Expressions� These are the same as before except for identi�ers�

Identi�ers� �� � x �� con �if �x� � con�

�� � x �� x �� e �if �x� � e � name ��

Actual ExprValue Mode�

�� ���W e �� e�

� ����value����W e� ae �� e�� ae

��� �����W ae �� ae�

� ����value�mu��W con� ae �� con� ae�

Name Mode� �� ����name����W e� ae �� �let �dFV�e� in e�� ae

�� �����W ae �� %�

����name����W e� ae �� e� ae��if FV�e� �W � ��

De�nitions� Here we need a rule which ensures that the actual expressions are evaluatedin the right mode� Otherwise the rules are as before�

Simple� �� ���mu�W ae �� ae�

���W form � ae �� form � ae�

�where � � M�T�form���

��ae � form � �

���W form � ae �� ��if ae � T����W where � � M�T�form��

Formals� �� � ��W � � �

��ae ���W form �

con� ae ��value����W �x � �� form� � fx � cong �

��ae ���W form �

e� ae ��name����W �name x � �� form� � fx � e � name �g �

Example� The main di�erence between call�by�name and call�by�value in applicative languagesis that call�by�name may terminate where call�by�value need not� For example consider theexpression

e � let f�name x � int� � int � � andrec g�x � int� � int � g�x�

in f�g����

Then

� e ��� let � in f�g����

Page 111: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

where � � ff�name x � int��int � �� g�x � int� � int � � � �gSo we look at

� � f�g���� �� let name x � int � g���in �

��� let fx � let g�x � int� � int � � � �gin �

�� �

On the other hand if we change the formal parameter of f to be call�by�value instead� then� asthe reader may care to check� the evaluation does not terminate�

Call�by�Reference

We consider a variant �the simplest one�� where the actual parameter must be a variable �identi��er denoting a location�� In other languages the actual parameter could be any of a wide varietyof expressions which are evaluated to produce a location these might include conditionals andfunction calls� This would require a number of design decisions on the permitted expressionsand on how the type�checking should work� For lack of time rather than any intrinsic di cultywe leave such variants to exercise �� Just note that it will certainly be necessary to rethinkexpression evaluation this should either be changed so that evaluation yields a natural value�be it location or primitive value� or else di�erent evaluation modes should be introduced�Syntactically we consider an extension to our imperative language

form ��� loc x � �� form�

Static Semantics

Clearly we have DI�locx � �� form� � fxg � DI�form�� For types we add another actualexpression type

aet ��� � loc� aet

and

T �loc x � �� form� � � loc� aet

and we have the rule

form � �

locx � �� form � fx � � loc� �g�if x �� I where � � I�

Actual Expressions� These are as before with the addition

� �V ae � aet

� �V x� et � � jbfloc� aet�if alpha�x� � � loc�

It is here that we insist that actual reference parameters must be variables� As in the case ofcall�by�name the type of an actual expression is not determined by its environment alone� but byits context as well� �A more honest notation might be �� aet �V ae rather than � �V ae � aet��

Page 112: G D Plotkin - people.cs.uchicago.edu

���� OTHER PARAMETER MECHANISMS ���

Dynamic Semantics

It is not necessary to change the de�nitions of DVal �or Env or Dec� as locations are alreadyinclude� However� we allow locations in AcExp and AeCon

ae ��� I� aeacon ��� I� acon

and clearly FV�I� ae� � FV�ae� and we have the rule

� �I ae � aet

� �I I� ae � � loc� aet�I � Loc� �

Transition Rules� We have relations �� he� �i �� he�� ��i� �� hd� �i �� hd�� ��i and �� hc� �i �� hc�� ��i �or ��� and a predicate acon� L � form � � � as before� For actualexpressions we proceed as with call�by�name and introduce a set� Mode� of evaluation modes

� ��� � j val� � j loc� �

with the evident de�nition of M�aet� �Mode and put for � � I and ��

���� � fhae� �i j aet� � �I ae � aetand� � M�aet�gT��� � fhacon� �i � ����g

and will de�ne the transition relation for � � and �

���� hae� �i �� hae�� ��i

Rules�

Expressions� Actual Expressions

Vaule Mode� �� �� he� �i �� he���i

����val��� h�con� ae�� �i �� h�e�� ae�� ��i

�� �� hae� �i �� hae�� ��i

����val��� h�con� ae�� �i �� h�con� ae��� ��i

Ref Mode� �� ����loc�� h�x� ae�� �i �� h�I� ae�� �i �if �x� � I�

�� ���� hae� �i �� hae�� ��i

����loc��� h�I� ae�� �i �� h�I� ae��� ��i

De�nitions�

Simple� �� ���� hae� �i �� hae�� ��i

�� hform � ae� �i �� hform � ae�� ��i�if � � M�T�form���

��acon� L � form � �� ��

rho �� hform � acon� �i �� h �� � � ��i�where � � L�

Page 113: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Formals� We Just add a rule for declaration�by�reference �� location�acon� L � form � �� ��

�I� acon�� L � �locx � �� form� � fx � Ig � �� ��

Note� All we have done is to include the construct x �� y of Chapter � in our simpledeclarations�

Commands� No new rules are needed�

Clearly our discussion of binding mechanisms is only a start� even granting the ground coveredin the exercises� I hope the reader will have been lead to believe that a more extensive coverageis feasible� What is missing is a good guiding framework to permit a systematic coverage�

��� Higher Types

Since we can de�ne or declare abstractions� such s functions and procedures� Tennents Principleof Correspondence tells us that we can allow abstractions themselves as parameters of �other�abstractions� The resulting abstractions are said to be of higher types �the resulting functionsare often called functionals� For example the following recursive de�nition is of a function toapply a given function� f � to a given argument� x� a given number� t� of times�

rec Apply�f � int �� in� x � int� t � int� � int �if t � � then x else Apply�f� f�x�� t� ��

We will illustrate this idea by considering a suitable extension of the imperative languageof this chapter �but neglecting call�by�reference�� Another principle would be to allow anydenotable type to be an expressible type this principle would allow locations or functionsand procedures as expressions and� in particular� as results of functions �by the Principle ofAbstraction�� For example we could de�ne an expression �naturally� called an abstraction�

form�e

that would be an abbreviation for the expression let f�form� � � � ein f � For a suitable� � depending on the context� it might� more naturally� be written as� function form� e suchfunctions �and other similar abstractions� are often termed anonymous� Then the followingfunction would output the composition of two given functions

Compose�f � int� int� g � int� int� � int� int� x � int� f�g�x��

In this way we obtain �many� versions of the typed �calculus� A number of problems arisein imperative languages where functions are not denotable� but only references to them� In thede�nition of Compose one will have locally declared references to functions as the denotationsof f and g if these are disposed of upon termination of the function call one will have a

Page 114: G D Plotkin - people.cs.uchicago.edu

���� HIGHER TYPES ���

dangling reference� Just the same thing happens� but in an even more bare�faced way� if weallow locations as outputs

function f�� � int loc � var x � int � � in x

At any rate we will leave these issues to exercises� begin moderately con�dent they can behandled along the lines we have developed�Now� let us turn to our language with higher types� We extend the syntax by including the

category AcETypes of actual expression types�

aet ��� � j �� aet j �aet �� ��� aet j aet proc� aet

and then add to the stock of formals

form ��� function f � aet� �� form j procedure p � aet� form

It is clear how this allows functions and procedures of higher type to be de�ned they are passedas arguments via identi�ers that denote them�

Static Semantics

Clearly

DI�functionf � aet �� �� form� � ffg � DI�form� andDI�proceduref � aet� form� � fpg � DI�form�

The de�nition of T�form� in AcETypes is also evident and we note

T�function f � aet� �� form� � �aet� ��� T �form�T�procedure p � aet� form� � aet proc�T�form�

As for the predicate form � � we �rst note the de�nition of the set� DTypes� of denotabletypes�

dt ��� et j et loc j aet �� et j aet proc

The rules are fairly clear and we just note the procedure case�

form � �

procedure p � aet� form � fp � aet proc � �g�if p �� I where � � I�

Turning to the other predicates we only need to add a rule for actuals�

� �I ae � aet

� �I x� ae � dt� aet

�where dt � ��x� is either of the form aet� et or aet proc�

Page 115: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Example� Try type�checking the following imperative version of Apply in the environmentfx � intg

function double�x � int� � int � �� xrec function apply�functionf � int� int� x � int� t � int� � int �

let var result � int � x inbegin while t � � do x �� f�x� t �� t� �result result

x �� apply�double� x� x�

Dynamic Semantics

Once more there is no need to change �the form of� the de�nitions of DVal or Env or Dec� Wemust now allow abstracts within actual expressions and also AcCon

ae ��� �form� e � ��� ae j �form� c�� aeacon ��� �form� e � ��� acon j �form� c�� acon

with the evident extensions to the de�nitions of FI�ae� and � �I ae � aet�

Transition Relations� In the following � � I and j � I�

Expressions� We de�ne con�gurations and terminal con�gurations and terminal con�g�urations as usual for the transition relation we de�ne for � �jJ

���J he� �i �� he�� ��i

Actual Expressions� We take

���J � fhae� �i j FI�ae� � Ig

and

T��J � fhacon� �i j FI�acon� � J � �g

and for � �jJ the relation

���J hae� �i �� hae�� ��i

Declarations� We de�ne ���J � T��J in the evident way� and the transition relation ���J hd� �i �� hd�� ��i

Commands� Again the con�gurations� the terminal con�gurations and the transitionrelation are of the evident forms�

Formals� We will de�ne the predicate acon� L �J form � �� �� where FI�acon�� J � ��

Page 116: G D Plotkin - people.cs.uchicago.edu

���� MODULES AND CLASSES ���

Rules� Expressions� Declarations� Commands as before�

Actual Expressions� As before� plus

���J h�x� ae�� �i �� h�abs� ae�� �i �if �x� � abs � Abstracts�

���J hae� �i �� hae�� ��i

���J h�abs� ze�� �i �� h�abs� ae��� ��i

Formals� We just need two more rules

acon� L �J form � � �

��form� e � ��� acon�� L �J function f � aet� �� form � ff � forme � �g � � �

acon� L �J form � � �

��form� c�� acon�� L �J procedure p � aet� form � fp � form�cg � � �

As a matter of fact the J �s are not needed� but we obtain �ner control over the allow�able actual expression con�gurations� This can be useful in extensions of our language whereabstractions are allowed�

��� Modules and Classes

There is a certain confusion of terminology in the area of modules and classes� Rather thanenumerate the possibilities let me say what I mean here� First these is a Principle of Denotationwhich says that one can in principle use an identi�er to denote the value of any syntactic phrase� where �value� is dellbertely ambiguous and may indicate various degrees of �evaluation��For expressions this says we can declare constants �in imperative languages� but also allowsdeclaration by name or by text and so on for commands it means we can have parameterlesssubroutines� For declarations we take it as meaning one can declare identi�ers as modules� andthey will denote the environment resulting from the elaboration� �There is a correspondingPrinciple of Storeability which the reader will spot for himself it is anything but clear howuseful these principles are��Applying the principle of abstraction to declarations on the other hand we obtain what

we call classes� Applying a class to actual arguments gives a declaration which can be usedto supply a denotation to a module identi�er then we say the module is an instance of theclass� �Of course everything we say here applies just as well to applicative languages by now�however� it is enough just to consider one case��A typical example is providing a random integer facility� Let drand be the declaration

privatevar a � seed mod d

withinfunction draw�� � int

Page 117: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

begin a �� a�mmod dresult a�dend

This would declare a function� draw� providing a random integer with its own private variable� insuccessible from the outside� If one wanted to declare and use two random integers� justdeclare two modules

module X � draw � � � int � drandmodule Y � draw � � � int � drandbegin

� � �X�draw�� � � � Y�draw��

Thus draw is an attribute of both X and Y and the syntax X� draw selects the attribute �ingeneral there is more than one��When one wnts some parameterization and!or desires to avoid writing out drand several

times� one can declare and use a class

class random�const seed � int� const d � int� � draw � � � int drandbegin

���module X � draw � � � int � random��� �� module Y � draw � � � int � random��� �� begin � � �X�draw�� � � �Y�draw�� � � � end���

end

Finally we note that it is possible to use the compound forms of declarations to producesimilar e�ects on classes� For example a version of the SIMULA classpre�xing idea is available�

class CLASS��form�� � � � � � � class CLASS��form��& & class PREFIXCLASS�form�� form�� � � �&

CLASS��form�� CLASS��form��

Naturally we will also be able to use simultaneous and private and recursive class declara�tions �can you tell me some good examples of the use of these��� One can also easily envisageclasses of higher types �classicals��� but we do not investigate this idea�Here is our extension of the syntax of the imperative language of the present chapter �but

no call�by�reference� or higher types��

Types� We need the categories DTSpecs� AcETypes and DecTSpecs of denotable typespeci�cations� actual expression types and declaration type speci�cations

dts ��� � j � loc j aet� � j aet proc j dects j aet� dects

Page 118: G D Plotkin - people.cs.uchicago.edu

���� MODULES AND CLASSES ��

aet ��� � j �� aetdects ��� x � dts j x � dts� dexcts

Clearly dect will be the type of a module identi�er and aet � dect will be the type of aclass identi�er�

Expressions� We add �ve���� new categories of expressions� funcion� procedure� variable�module and class expressions� called FExp� PExp� VExp� MExp� CExp and ranged overby fe� pe� ve� me� cle� and given by the following productions �where we also allow f � p�v� m� cl� as metavariables over the set� Id� of identi�ers�

fe ��� f j me�fpe ��� p j me�pve ��� v j me�vme ��� m j me�m j cle�ae�cle ��� cl j me�cl

The de�nition of the set of expressions is extended by

e ��� me�x j fe�ae�

�and the second possibility generalizes expressions of the form f�ae��� The set of actualexpressions is de�ned as before�

Commands� We generalize commands of the forms p�ae� and x �� e �i�e� procedure callsand assignment statements� by

c ��� pe�ae� j ve �� e

Declarations� We add the following productions to the de�nition

d ���module m � dects � d j class cl�form� � dects d

Note that declaration types are used here to specify the types of the attributes of modulesand classes� If we except recursive declarations this information is redundant� but it couldbe argued that it increases readability as the attribute types may be buried deep insidethe declarations�

Formals� The de�nition of these remains the same as we do not want class or moduleparameters�

Note� In this chapter we have essentially been following a philosophy of di�erent expressionsfor di�erent uses� This is somewhat inconsistent with previous chapters where we have mergeddi�erent kinds of expressions �e�g� integer and boolean� and been context to separate them outagain via the static semantics� By now the policy of this chapter looks a little ridiculous and itcould well be better to merge everything together� However� the reader may have appreciatedthe variation�

Page 119: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Static Semantics

For the de�nitions of FI�fe�� � � � �FI�cle� we do not regard the attribute identi�ers as free �butrather as a di�erent use of identi�ers from all previous identi�ers their occurrences are the sameas constant occurrences and they are thought of as standing for themselves�� So for exampleFI�me� is given by the table

m me�m cle�ae�

FI fmg FI�me� FI�cle� � FI�ae�

For the de�nions f of FI�e�� FI�c� we put

FI�me�x� � FI�me�FI�fe�ae�� � FI�fe� � FI�ae�FI�pe�ae�� � FI�pe� � FI�ae�FI�ve �� e� � FI�ve� � FI�e�

and for FI�d� and DI�d� we have

module m � dect � d class cl�for� � dect d

FI FI�d� FI�d�nDI�for�

DI fmg fdg

�We are really cheating somewhere here� For example the above scheme would not work if weadded the reasonable production

d ��� me

as then with� for example� a command m begin � � � x � � � end the x can be in the scope of them if the command is in the scope of a declaration of the form module m � dect � var xint �� � � � � �Thus it is nolonger possible tode�ne the free identi�ers of a phrase in a context�free way�

Let us agree to ignore the problem��

Types� We de�ne �mutually recursively� the sets ETypes� FETypes� � � �� CIETypes�DTYpes� TEnv of expression types� function expression types� � � �� class expression types�denotable types and type environments by

et ��� �

Page 120: G D Plotkin - people.cs.uchicago.edu

���� MODULES AND CLASSES ��

fet ��� aet� �pet ��� aet procvet ��� � locmet ��� �clet ��� aet �� �dt ��� et j vet j fet j pet j met j cletTEnv � Id ���n DTypes �with � ranging over TEnv�

To see how the sets DTSpecs and DecTSpecs of denotable and declaration type speci��cations specify denotable and declaration types respectively� we de�ne predicates

dts � dt and dects � �

by the formulae

DTSpecs�

�� � � �

�� � loc � � loc

�� aet� � � aet� �

�� aet proc � aet proc

��dects � �

dects � ��where the premise means proved from the rules for DecTSpecs�

��dects � �

aet� dects � aet� �

DecTSpecs�

��dts � �

�x � dts� � fx � �g

��dts � � dects � �

�x � dts� dets� � fx � �g � ��if x �� I for � � I�

Next T�form� � AcETypes is de�ned as before� Now we must de�ne the predicates

��I e � et � �I fe � fet� � � � � � �I cle � clet� � �I c��I d � � � �I d form � �

The old rules are retained and we add new ones as indicated by the following examples�

Expressions�

��� �I me � �

� �I me�x � dt�if ��x� � dt�

��� �I fe � aet� et� � �I ae � aet

� �I fe�ae� � et

Page 121: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

Function Expressions�

�� � �I f � ft �if ��f� � ft � FTypes�

��� �I me � �

� �I me�f � ft�if ��f� � ft � FTypes�

Class Expressions�

�� � �I cle � clet �if ��cl� � clet � CIETypes�

��� �I me � �

� �I me�cl � clet�if ��cl� � clet � CIETypes�

Commands�

��� �I pe � aet proc � �I ae � clet

� �I pe�ae�

��� �I vet � � loc � �I e � �

� �I �vet �� e�

Declarations�Modules

��dects � �

�module m � dects � d� � fm � �g

��dects � � � �I d � �

� �I module m � dects � d

Classes�

��dects � �

�class cl�form� � dects d� � fcl � T �form� �� �g�

��dects � � form � �� ����� �I�I� d � �

� �I class cl�form� � dects � d�where �� � I��

Dynamic Semantics

First we de�ne the sets FECon� � � �� CIECon of function expression constants� � � �� class expres�sion constants by

fecon ��� form� e � etpecon ��� form� cvecon ��� Imecon ��� clecon ��� form� d � �

and also add the productions

fe ��� fecon� � � � � cle ��� clean j d

Page 122: G D Plotkin - people.cs.uchicago.edu

���� MODULES AND CLASSES ���

and de�ne the sets DVal and Env of denotable values and environments by

dval ��� con j vecon j fefon j pecon j clecon j meconEnv � Id ���n DVal

and extend the de�nition of declarations by the production

d ���

These are mutually recursive de�nitions of a harmless kind� The extensions to the de�ntionof FI�fe�� � � � �FI�de��FI�d��DI�d� are evident for example FI�form� d � � � FI�d�nDI�from��We must also extend the de�nitions of � �I fe � fet� � � � � � �I cle � clet and �I d � � and

� �I d �the latter tow in the case d � �� The former extensions are obvious for example

Class Abstracst�

form � �� ����� �I�I� d � �

� �I �form� d � ���where �� � I��

For the latter we have to de�ne �I decon � dt and this also presents little di culty for example

Class Abstracts�

�I �form� d � �� � T�form�� �

Then we have the two rules

���x � I� �I �x� � ��x�

�I � ��where � I��

���x � I� � �I �x� � ��x�

� �I

Transition Relations� The set Stores� is as before�The con�gurations� �nal con�gurations and the transition relations for expressions� actual

expressions and declarations are as before for formals we have the same predicate as before�Now fix � � I and � �jJ �for some J � I��

Function Expressions� We take �� � fhfe� �i mid fet� � �I fe � fetg� T� �fhfecon� �i j fet� � �I fecon � fetg and the transition relation has the form �I� �� ��

The de�nitions for PExp� � � �� CExp are the analogues of that for function expressions

Rules � Class Expressions�

�� �� hcl� �i �� hclecon� �i �if �cl� � clecon�

Page 123: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

�� �� hme� �i �� hme�� ��i

�� hme�cl� �i �� hme��cl� �i

�� �� h ��cl� �i �� hclecon� �i �if ��cl� � clecon�

The rules for FExp� � � �� MExp are similar except that in the last case we need also

�� �� hcle� �i �� hcle�� ��i

�� hcle�ae�� �i �� hcle��ae�� ��i

�� �� h�from� d � ���ae�� �i �� hprivate from � ae within d� �i

�� �� hd� �i �� hd�� ��i

�� hd� �i �� hd�� ��i�where in the top line we mean a transition of decl��

The new rules for expressions and commands should be clear for example

Assignment�

�� �� hve� �i �� hve�� sigma�i

�� hve �� e� �i �� hve� �� e� ��i

�� �� he� �i �� he�� ��i

�� hI �� e� �i �� hI �� e�� ��i

�� �� hI �� con� �i �� ��I � con�

For declarations the new rules are

Modules�

�� �� hd� �i �� hd�� ��i

�� hmodule m � dects � d� �i �� hmodule m � dects � d�� ��i

�� �� hmodule m � dects � �� �i �� hfm � �g� �i

Classes�

displaystyle �� class cl�form� � dects d �� fcl � form� � nI� in dg�where I � DI�form��

��� Exercises

� Consider dynamic binding in the context of a simple applicative language so that� forexample�

let x � � f�y� � x � yin let x � � in f���

has value �� What issues arise with type checking� Can you program iterations �e�g�factorial� without using recursive function de�nitions�

Page 124: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ���

� In a maximalist solution to the problem �in the applicative language� of neatly specifyingfunctions of several arguments one could de�ne the class of formal parameters by

form ��� � j x � � j form� form

and merge expressions and actual expressions� putting

e ��� � j e� e j f�e�

and amending the de�nition of de�nitions

d ��� form � e j f�form� � � � e

a� Do this� but e�ectively restrict the extension to the minimalist case by suitable choiceof static semantics�

b� Allow the full extension�

c� Go further and extend the types available in the language by putting

� ��� int j bool j �� � j �

thus allowing tuples to be denotable�

� Consider the maximalist position in a simple imperative programming language�

� Consider in a simple imperative language how to allow expressions on the left�hand ofassignments�

e� �� e�

and even the boolean expression e� � e� which is true precisely when e� and e� evaluateto the same reference� As well as discussing typechecking issues� try the two followingapproaches to expression evaluation�

a� Expressions are evaluated to their natural values which will be either locations orbasic values�

b� Modes of evaluation are introduced� as in the text�

Extend the work to the maximalist position where actual expressions and expressions aremerged� thus allowing simultaneous assignments�

� Just as expressions are evaluated� and so on� formals are matched �to given actual values�to produce environments �� matchings�� The semantics given above can be criticized asnot being dynamic enough as the matching process is not displayed� Provide an answerto this you may �nd con�gurations of the form

hform� con� i

Page 125: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

useful where form is the formal begin matched� con is the actual value and is thematching produced so far� A typical rule could be

hx � �� con i �� � fx � cong

This is all for the applicative case what about the imperative one� Investigate dynamicerrors� allowing constants and repeated variables in the formals �dynamic error � match�ing failure��

In the phrase rec d all identi�ers in R � FV�d� � DV�d� are taken to be recursivelyde�ned� Investigate the alternative rec x�� � � � � xn � d where fx�� � � � xn � Rg�

� In some treatments of recursion to evaluate an expression of the form

let rec �f�x� � � � � f � � � g � � � and g�x� � & f & g &�in f���

one evaluates f��� in the environment

� ff�x� � � � � f � � � g � � � � g�x� � & f & g &g

�ignoring free variables� and uses the simple transition�

� f��� �� let x � � in � � � f � � � g � � �

I could not see how to make this simple and nice idea �leave the recursively de�nedvariables free� work in the present setting where one has nested de�nitions and binaryoperations on declarations� Can you make it work�

� Try some examples of the form

let rec �f�x� � � � � f � � � g � � �#g�x� � fg�in e

where # is any of � and or in

� Consider the following recursive de�nitions of constants�

a� rec x � int � �b� rec �y � int � �and x � int � y�c� rec �x � int � yand y � int � ��d� rec �x � int � x�e� rec �x � int � yand y � int � x�

How are these treated using the above static and dynamic semantics� What do youthink should happen� Specify suitable static and dynamic semantics with any needederror rules� Justify your decisions� considering how your ideas will extend to imperativelanguages with side�e�ects �which might result in non�determinism��

Page 126: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ���

� Find de�nitions d� and d� to make di�erent as many as possible of the following de�nitions�

a� �rec d� d���b� �rec� �rec d� d��c� �rec� �d� rec d��d� �rec� �rec d� rec d��

where �rec�d indicates the two possibilities with and without rec�

�� Check that the �rst alternative for type�checking recursive de�nitions would work in thesense that

� �V d � � ��v d � � and � �V d

�� Programming languages like PASCAL often adopt the following idea for function de�ni�tion�

function f�form� � �begin

cend

where within c the identi�er f as well as possibly denoting a function also denotes alocation� created on function entry and destroyed on exit the result of a function call isthe �nal value of this location on exit� For example the following is an obscure de�nitionof the identity function�

rec function f�x � int� � intbegin

f �� � if x � � then f �� �else f �� f � f�x� ��

end

Give this idea a semantics�

�� Call�by�need� In applicative languages this is a �delayed evaluation� version of call�by�name� As in call��by�name the formal is bound to the unevaluated actual� with the localenvironment bound in� However� when it is necessary for the �rst time to evaluate theactual� the formal is then bound to the result of the evaluation� Give this idea a semantics�One possibility is to put �some of� th environment into the con�gurations� treating it likea store� Another is to bind the actual to a new location and make the actual the value ofthat location in a store� Prove call�by�need equivalent to call�by�name� Consider delayedevaluation variants of parameter mechanisms found in imperative languages�

Page 127: G D Plotkin - people.cs.uchicago.edu

��� CHAPTER �� FUNCTIONS� PROCEDURES AND CLASSES

�� Call�by�name� Consider �minimalist # maximalist� versions of call�by�name in imperativeprogramming languages� Look out for the dangers inherent in

procedure f�x � intname� �begin

��x ������

end

�� Discover the o cial ALGOL �� de�nition of call�by�name �it works via a substitutionprocess� give a semantics following the idea and prove it equivalent to one following theidea in these notes �substitution � binding a closure��

� Call�by�text� Give a semantics for call�by�text where the formal is bound to the actual�not binding in the current environment� when a value is desired the actual is evaluatedin the then current environment� Consider also more �concrete� languages in which theabstract syntax �of the text� is available to the programmer� or even the concrete syntax�does the latter possibility lead to any alteration of the current framework�

�� Call�by�reference�Give a maximalist discussion of call�by�reference� still only allowing ac�tual reference parameters to be variables� Extend this to allow a wider class of expressionswhich �must� evaluate to a reference� Extend that in turn to allow any expression as anactual if ti does not evaluate to a reference the formal should be bound to a new referenceand that should have the value of the actual�

�� Call�by�result�Discuss this mechanism where �rst the actual is evaluated to a reference� I second the formal is bound to a new reference I � �not initialized�� third� after computationof the body of the abstract� the value of I is set to the value of I � in the then currentstore� Discuss too a variant where the actual is not evaluated at all until after the bodyfor the abstract �Hint� user declaration �nalization��

�� Call�by�value�result�Discuss this mechanism where �rst the actual is evaluated to a refer�ence I second the formal is bound to a new reference I � which is initialized to the currentvalue of I third� after the computation of the abstract of the body� the value of I is setto the value of I � in the then current store�

� Discuss selectors which are really just functions returning references� A suitable syntaxmight be

selector f�form� � � � e

which means that f returns a reference to a � value� First consider the case where alllifetimes are semi�in�nite �extending beyond block execution�� Second consider the casewhere lifetimes do not persist beyond the block where they were created in this caseinteresting questions arise in the static semantics�

Page 128: G D Plotkin - people.cs.uchicago.edu

���� EXERCISES ��

�� Consider higher�order functions in programming languages which may return abstractssuch as functions or procedures� Thus we add the syntax�

e ��� form� e j form� c

The issues that arise include those of lifetime addressed in exercise ���

�� Here is a version of the typed �calculus

� ��� int mid bool mid � �� �e ���m mid t mid x mid e bop mid if ethen eelse e mid

let x � � � ein e mid �e� mid x � �� e

Give a static semantics and two dynamic semantics where the �rst one is a standardone using environments and where the second one is for closed expressions only and usessubstitutions as discussed in the exercises of Chapter �� Prove these equivalent� Add arecursion operator expression

e ��� Y

with the static semantics � �V Y � �� �� �� �� ��� �� int� bool� and a rule somethinglike � Y e� �� e��Y e��� What does this imply about formals which are of functionaltype and their evaluation� and why is that important�

Page 129: G D Plotkin - people.cs.uchicago.edu

Appendix A

A GUIDE TO THE NOTATION

Syntactic CategoriesTruthvalues t � TNumbers m�n � NConstants con � ConActual Constants acon � AConUnary Operations upop � UopBinary Operations bop � Bop

Variables v� f � Var V ��n VarIdenti�ers x� f� p�m� ci � IdI ��n Id

Expressions e � ExpBoolean b � BExpActual ae � AExpVariable ve � VExpFunction fe � FExpProcedure pe � PExpModule me � MExpClass cle � CExp

Commands��Statements� c � Com

De�nitions�Declarations d � Def�Dec

Formals form � FormsTypes � � Types

Expression et � ETypesActual Expr aet � AETyes

���

Page 130: G D Plotkin - people.cs.uchicago.edu

��

DenotableType Spec dts � DTSpecsDeclarationType Spec dects � Dec TSpecs

Static SemanticsFree Variables�Identi�ers FV�I�e��FI�c��FV�I�d� etc�De�ning Variables�Identi�ers EV�I�d� DV�I�form�Denotable Types dt � DTypesType Environments �� � � TEnv �e�g� � Id ���n DTypes�Example Formulae � �V e � et � �I c � �I d � �

form � � T�form� � aet

Dynamic SemanticsDenotable Values dval � DValEnvironments � Env �e�g � Id ���n DVal�Storeable Types st � STypesLocations I � Loc �

Pst Locst L ��n Loc

Storeable Values sval � SVal �P

stValst

Stores � � Stores �e�g� � f� � Loc ��fin SVal j�st � STypes� ��Locst�� � SValstg�

Evaluation Modes � � ModesTransition Systems h�� T��i � � �

where � is the set of con�gurationsT � � is the set of �nal con�gurations� �� �� is the transition relation

ExampleCon�guration he� �i hc� �i� � hd� �iExample FinalCon�guration hCon� �i � h � �iExample TransitionRelations �I�� he� �i �� he�� ��i

�I hc� �i �� hc�� ��i���

�I hd� �i �� hd�� ��i

Page 131: G D Plotkin - people.cs.uchicago.edu

Appendix B

NOTES ON SETS

We use several relations over and operations on sets as well as the �very� standard ones� Forexample X ��n Y means X is �nite and a subset of Y �

De�nition� Let Op�X�� � � � � Xn� be an operation on sets� It is monotonic if whenever X� �X �

�� � � � � Xn � X �n we have Op�X�� � � � � Xn � Op�X �

�� � � � � X�n�� It is continuous if whenever

X�� � X�

� � � � � Xn� � � � � is an increasing sequence and � � � and X�

n � X�n � � � � � Xm

n � � � � isan increasing sequence then

��� Op��m

Xm� � � � � �

�m

Xmn � �

�m

Op�Xm� � � � � � X

mn �

Note C� ontinuity implies monotonicity� Conversely to prove continuity� �rst prove mono�tonicity� This establishes the �� ��� half of ��� then prove the � ��� half�

Example�

Cartesian Product�

X� � � � ��Xn � fhx�� � � � � xni j x� � X� and � � � and xn � Xng

is monotonic and continuous� Prove this yourself�

Disjoint Sum�

X� � � � ��Xndef� �f�g �X�� � � � � � �fng �Xn�P

iAXidef�SiAfig �Xi

Show that the �nite sum operation is continuous� �Finite Sum is just union� but forcedto be disjoint��

Finite Functions� The Class of �nite functions form X to Y is

X �fin Y �X

A�finX

A� Y

Note that the union is necessarily disjoint� Show that �fin iscontinuous�

���

Page 132: G D Plotkin - people.cs.uchicago.edu

���

For A ��n X if f � A � Y � X ��n Y �we identify f with hA� fi� we write f � A� Thisis used for environments �including type environments� and stores� There are two other usefuloperations�For f � A g � B in X �fin Y we de�ne f �g� � A � B by

f �g��c� �

�g�c� �c � B�f�c� �c � AnB�

and in case A � B � � we de�ne f� g � A �B �also written f � g by�

f� g�c� �

�f�c� �c � A�g�c� �c � B�

Note this is a special case of the �rst de�nition� but it is very useful and worth separate mention�

The Importance of Continuity

Suppose Op�X� is continuous and we want to �nd an X solving the equation

X � Op�X�

Put XO � � and Xm�� � Op�Xm�� Then �by induction on m� we have for all m Xm � Xm��

and putting X �Um Xm

Op�X��Op�SXm�

�SOp�Xm� �by continuity�

�SmXm��

�Xm

And one can show �do so�� that X is the least solution � that is if Y is any other than X � Y �Indeed X is even the least set such that Op�X� � X�This can be generalized� suppose Op��X�� � � � � Xn�� � � � � Opn�X�� � � � � Xn� are all continuous

and we want to solve the n equations

X� �Op��X�� � � � � Xn����

Xn�Opn�X�� � � � � Xn�

Put XO� � � for i � �� n and de�ne

Xm��i � Opi�X

m� � � � � � X

mn �

Then for all m and i Xmi � Xm��

i �prove this � and putting

Xi ��m

Xmi

we obtain the least solutions to the equations � if Yi are also solutions then for all i� Xi � Yi�Indeed the Xi are even the least sets such that Opi�Xi� � � � � Xn� � Xi�i � �� n�� This is used inthe example below� Prove this�

Page 133: G D Plotkin - people.cs.uchicago.edu

��� APPENDIX B� NOTES ON SETS

Example� Suppose we are given sets Num� Id� Bop and wish to de�ne sets Exp and Com bythe abstract syntax

e ��� m j x j e� bop e�e ��� x �� e j c� c� j j if e� � e�then c�else c� j while e� � e�do c

Then we regard this de�nition as giving us set equations

Exp � Num� Id � �Exp� BOp� Exp�Com � �Id� Exp� � Com� Com� �Exp� Exp� Com� Com� � �Exp� Exp� Com�

and also giving us a notation for working with the solution to the equations� Firstm is identi�edwith h�� mi � Exp and x is identi�ed with h�� xi in Exp Next

e� bop e� � h�� he�� bop e�iix �� e � h�� hx� eiic� c� � h�� hc�� c�iiif e� � e� then c� else c�� h�� he�� e�� c�� c�iiwhile e� � e� do c� � h�� hie�� e�� c�i

Now the set equations are easily solved using the above techniques as they are in the form

Exp �Op��Exp�Com�Com�Op��Exp�Com�

where Op��Exp�Com� � Num� Id� �Exp�BOp�Exp� and Op� is de�ned similarly� ClearlyOp� and Op� are continuous as they are built up out of �conmposed from� the continuousdisjoint sum and product operations �prove they are continuous�� Therefore we can apply theabove techiniques to �nd a least solution Exp� Com� Note that Exp and Com are therefore theleast sets such that

�� Num � Exp and Id � Exp �using the above identi�cations���� if e�� e� are in Exp and bop is in Bop then e� bop e� is in Exp��� if x is in Id and e is in Exp then x �� e is in Com�

�� � � ����

�� � � ����

�� if e�� e� are in Exp and c is in Com then while e� � e� do c is in Com

At some points in the text environments �and similar things� were mutually recursively de�nedwith commands and so on� This is justi�ed using our apparatus of continuous set operatorsemploying� in particular� the �nite function operator�