Download as pdf or txt
Download as pdf or txt
You are on page 1of 253

tf ø/rt

COROUTINES: A PROGRAIÍMING METIIODOLOGY' A LANGUAGE DESIGN'

AND AIÛ IMPLEMENTATION

by

Chrtstopher Davld Marlln, B.Sc. (Hons.)

Department of Conputlng Science


The Unlverslty of Adelalde

À thesfe submf.tted for the degree of Doctor of Phllosophy

l6th Novenber 1979

\,: \'i:L )
TABLE OF CONTENTS

Page

LISÎ OF TABLES vl

LIST OF FIGIIRES vfl

SI]MMARY x

DECLARATION x1

ACKTIO!ÍLEDGH"fENTS x11

Chapter

I a INTRODUCTION I
1.1 Coroutines I
1.2 Past Appllcatlons for Coroutines 6

t-

1.3 Coroutines 1n Progranmfng Languages


I

I
I
2. PROGRAI'IMING I^¡ITH COROUTINES 9

2.1 Aspeets of Program Deslgn 9


I

2.2 Pxogtam StrucËure 10

2.3 A, Methodology for Programming wfth CoroutLnes 11

2.4 Ln Exanple: Ttre Telegrams Problem 14

3. A PROGRA},IMING LANGUÀGE WITH COROUTINES 2L

3. I Introductlon 2T

3.2 The Design Goals 22

3.3 Programmlng Language Deslgn 24

ii
Chapter Page

3.4 The Cholce of Pascal as the Base Language 27

4. TIIE DESIGN OF THE SEMANTICS OF TITE LANGUAGE 29

4. I The Semantlcs of the DaÈa Structures Aspect 29

4.2 frte Semantics of the Sequence Control Aspect 32


4.2.1 Introductlon 32
4.2.2 The Sequence Control Model 33
4.2.3 Sequence Control Ín Previous Coroutine Facllitles 36
. Slmula 36
. Gentleman's Portable Coroutlne System 45
. CorouÈlne PASCAL 46
. 2.PÀK 50
. sL5 52
. Krieg's CooperaËlons of Coproeedures 53
. Prftchardts Pools of CorouÈlnes s4
. SaJanl-eml's Cogroups 55
. Alphard and CLU 56
. TELOS 57

4.2.4 Sequence Control in ACL 5B

4.2,4.1 IntroducËion 58
4.2.4.2 Extenslons to the Sequence Control Model 60
4.2.4.3 The Sequence Control Operatlons 65

4.3 The Semantlcs of the Data Control- Aspect 75

4.3.1 Data Cont.rol ln Prograrnnlng Languages 75

4.3. 1. I IntroducËlon 75

4.3.1.2 Data Control and Storage Manage-ment 79


4.3. 1.3 Block Structure 83
4.3.1.4 Scope Rules 85

4.3.1.5 Parameters and Function Values 87

4.3.2 The Data ConÈrol Model 94


4.3.3 Data ConÈrol ln Previous Prograromlng Languages 10t
4.3.3.1 Introductlon 101

4.3.3.2 Pascal 101


. Local Declaratlons 105
. Value Parameters I06

r-1L
Chapter Page

. Varlable Parameters r09


. Procedure and Functton Parameters 111
. Scope Rules 1r3
. Returnlng Values from Functlons LL7
. A Complete Example 119
4.3.3.3 Expllelt Scope Rule Schemes L22
4.3.3.4 Prevlous Coroutine Facl-lltfes L25
4.3.4 Data Control 1n ACL L28
4.3.4.1 Introduction L28
4.3.4.2 Scope Rules 130
. Local Declarations L34
. RO Inheritlng Decl-aratlons 135
. Rfü InheriËlng Declarations 138
4.3.4.3 Parameters 140
. RO Reference (Seen) Parameters L42
. Rl{ Reference (Modiflable) Parameters 145
. Value ParameEers L47

4.3.4./+ Returnl-ng Values froü Subprograms 150


4.3.4.5 Summary, Restrlctlons and DlscLplines 151

5. THE SYNTAX OF THE LANGUAGE 157

5. I Introduction L57

5.2 Declaratlons L57


5.2.L Deflning Declarations 158
5.2.2 Inheriting Declarations 159
5.2.3 Forward Declaratlons 159
5.2.4 A Difficulty of Pascal Avoided in ACL L62

5.3 Parameters L64

5.4 St.aternents r65

5.5 Predefined Procedures and Functions L66

6. TIIE IMPLEMENTATION OF THE LANGUAGE 169

6. I OvervÍer¿ 169

iv
Chapter Page

6.2 Declaratlons L72

6.3 StatemenÈs 175

6.4 Storage Management L82

7 coNcLusroNs 191

7.1 The Programmlng Methodology 191

7.2 Í1l.e Language Design 191

7.3 The ImplementaÈ1on 195

APPE¡IDICES L99

Appendl-x A: Syntax DÍagrams for ACL L99

Appendix B: Sone ACL Programs 207


B.l The Telegrams Problem 207

I I 8.2 The Odd llord Reversal Problem 2L2

. 8.3 Hammlngts Problem 2t8


8.4 LynnLng's Solutlon to Grune's Problen 224
8.5 A Data AbstracËlon Example 226

REFERENCES 229

v
LIST OF TABLES

Table Page

2.L Caller-Callee RelaÈlonshl-ps 1n Flgure 2.1 20

4.1 A Conparlson of Sequence Control fn SÍnula and 2.PAK 52

4.2 A Sunmary of the Sequence Control Operatlons of ACL 73

4.3 Ttre CharacterlstLcs of Varlous SÈattc Scope Rule Schemes L23

4.4 A Sumnary of the Data Control EvenËs for ACL L52

5.1 PredefÍned Procedures Ln ACL Requlring RI{ Access to Actual


Parameters 168

8.1 Names Ln Figure 8.1 CorrespondLng Èo Nodes ln the


Dlscusslon of Chaptex 2 2LO

vf
LIST OF FIGURES

Figure Page

2.I The Structure of Èhe Solutlon to the Telegrams Problem L9

4.L An Example of a Dynamlc Hferarchy 37

4.2 The Sfrnula Text Corresponding to the DynamLc Hierarchy of


Flgure 4.1 38

4.3 The Tree of Instances in an Executlng Slmula Program 42

4.4 Sone Typical Cycles of Instances Ln Coroutlne PASCAL


Programs 48

4.5 An Exanple of a Master Tree 6r

4.6 The Algorfthm for the Computatlon of "live(i) " 62

4.7 The Algorlthm for the ConpuÈation of "susp(l1r12)" 63

4.8 The EffecE of an InsEanee CreaEion OperaË1on on Èhe MasÈer


Tree of Figure 4.5 67

4.9 The Effect of a GeneraLor Call Operatlon on the Master Tree


of Flgure 4.5 70

4. 10 I{egner's Binding Dlagran 75

4.11 A Temporal Partlal Ordering on EvenEs Concerned l^Iith a


Varlable 83

4.L2 Two Algol 60 Fragnents \úith Ehe Same Data Cont,rol Structure B3

4.13 An Example of Èhe Use of Paramet,ers to Construct


Speclalized Data Cont,rol Structures 90

4.L4 A Pascal Fragment Containlng a Functlon Parameter 91

4. 15 Avoiding Violations of the Princlple of Disjoiritness l{hich


were Due, in part, to Access via Scope Rules 93

4. L6 The Pietorlal of Block Instances in


RepresenEation a

DepictÍons of the Data Control Structure of Programs 96

4. 17 Transmlsslon of Access via an Intermediary ldentlfler 98

4. r8 Allor¡able TransmLsslons of Access to a Known ldentifier 99

4.Lg A Paseal Fragment, Illustratlng Value Parameters r09

4.20 Data Control Structures Occurrlng during the Executlon of

vli
Ffgure Page

the Fragment of Figure 4.19 109

4.2L A Pascal FragmenE Illustratlng VarfabLe ParameÈers 110

4.22 Dat.aControl Structures Occurrlng durlng the ExecuÈlon of


the Fragnent of Figure 4.21 111

4.23 À Pascal Fragment Illustratlng Procedure and Functfon


Parameters TL2

4.24 Data Control StrucÈures 0ccurrLng during the Executlon of


the FragmenÈ of Flgure 4.23 LT2

4.25 The ParÈlal Ordering on the Events ComprisLng the Data


Control Effect of Block Entry ln Pascal 113

4.26 A Pascal Fragmerrt lllust,raË1ng the Scope Rules 115

4.27 Data Control Structures Occurrlng durÍ-ng the Exeeutlon of


the Fragrnent of Figure 4.26 116

4.28 Examples of Pascal FunctLons which Cannot Return a Value LL7

4.29 A Pascal Fragment Contalning a Function 119

4.30 Data Control Structures Occurring durlng the Execution of


the Fragnent of Ïigure 4.29 119

4. 31 A Conplete Pascal Program L20

4.32 Data Control Struct.ures Occurrlng during the Executlon of


the Program of Figure 4.31 L2T

4. 33 A Program Fragment IllustraEing an Amornaly with Scalar


Types ln Pascal 136

4.34 Data Control StrucÈures lllustraElng the Effect of Local


and Inheriting Declarations fn ACL r39

4.35 A Slnula Fragment Illustratlng the Establlshment of Mutual


References between Instances L44

4.36 DaËa ConErol Structures Illustratlng the Establishment of


MuEual References between Instanees 1n ACL L45

4.37 Data Control Structures lllustrating the Rebtnding of


Cont.lnuatlon Parameters ln ACL L49

4.38 An Example of a Generator not Exhibiting Procedure-like


Behavlour 154

5.I Speclfylng Recurslvely-deflned Data Types 1n ACL and Pascal I6I


5,2 Specifying Mutually Recursive Procedures 1n ACL and Pascal L62

v11i
Figure Page

5.3 Two Pascal FragmenÈs Illustratlng SltuaÈfons Subject to


InterpreÈaË1on 163

6.1 Steps fn the Development of an ACL Processor fron Pascal'Il' 171

6.2 The LayouËs of the VarLous Klnds of lfeap ObJect L77

6.3 An Example of a Heap Object and lts Descrlption List 186

8.1 A Solutlon to Èhe Telegrams Problem 208

8.2 The Structure of the Program 1n Figure 8.1 after the


InLtlalizaË,lon of lts InsÈances 2LT

8.3 Barter's SolutLon to the Odd I'Iord Reversal Problem 2L4

B.4 AnoËher SoluËlon to the Odd I{ord Reversal Problem 216

8.5 The Sequence Control StrucÈures of the Two SolutLons to Èhe


Odd l{ord Reversal Problem 2L7

8.6 DiJkstra's Solutlon of Hamroing's Problem 219

8.7 Transformlng DiJkstra's Solutlon o¡ ¡l¿rnmlng's Problem 220

B.8 AnoÈher Solutlon to Ham.mlng's Problem 222

8.9 Lynnl-ng's Solution to Grune's Problem 225

B. 10 The Stack Abstractlon ln ACL 228

1x
ST]MMARY

Coroutlnes, although known and dÍscussed for some years, are often
regarded as glving rlse to poor program structure and fnefficlent
progran executlon, and are not wtdely avallable in programmlng
languages. This thesls describes a top-down methodology for programmlng
wiÈh coroutines, r¡hich ls based on the exLensLon of the notlon of
hierarchical program st.ructure to cover programs contalnlng eoroutlnes.
The support and promotlon of thls methodology formed Part of the
motivation for the desfgn of a progranmtng language wlËh coroutlnes;
thfs desLgn lras also motlvaÈed by a desire to experiment $tith the
provlslon of a coroutlne facility 1n the framework of a modern, general--
purpose prograrnming language. Among the goals of the language design was
the encouragemenE of a close correspondence between the staEic, textual
atructure of a program wrlÈten ln the language, and lts structure aË
run-time.

The language with coroullnes, called ACL, , was designed uslng a


novel approach to language design whlch flrstly involves the dlvlsion of
the desLgn Èask Ínto Èhe deslgn of the semantÍcs of Ehe language'
followed by the design of lts synÈax. The flrst of these Ls further
subdivlded lnto Ehree parts, one for each of three aspects of the
language betng deslgned: data structures, sequence conËrol and data
control. For each aspect, a semanElc rnodel was devl-sed which ls tailored
both to the aspect, and Èo the needs of this partícular language deslgn.
These model-s (whtch vary 1n the extenÈ to which they can be described as
for¡nal) were used to compare this aspect of existlng language features'
and to make slmilar comparisons among alternatlves belng considered for
lncluslon ln thts aspect of ACL; these comparlsons were very rnuch
facllltated by the models, with both slnl-larities and differences being
nade clear. In thls way, descrlptions of the senantl-cs of each of the
three apsects of ACL were obtained; these stere then glven a syntactlc
form 1n the Pascal ld1om.

The programnlng language ACL has been lmplemented, and some aspects
of this lmplementatlon are also brlefly discussed.

x
DECLARATION

Ttrls thesfs conÈalns no materLal whl-ch has been accepted for the
award of any other degree or dlploma 1n any unlversity and, to the best
of rny knowledge and belLef, contalns no naÈerial previousl-y publtshed or
written by another person, except where due reference ls made Ln Ëhe
text of the thesls.

C.D.Marlfn
16th Novenber 1979

xl
ACKNO}'ILEDGEMENTS

I would ltke Ëo thank my supervlsor, Dr.C.J.Barter, for hls


guldance and encouragement durfng the conduct of thls research. My
thanks are also due to Dr.J.G.Sanderson for nany helpful dlscussLons,
partlcularly while actlng as my temporary supervfsor, and to the many
other people who have asslsted me whÍle I ¡¡as carryl-ng out thls tilork.
I an also grateful to my wl-fe, Deborah, for her support and for her
careful preparation of the many dfagrams 1n this thesLs.

xil
CIIAPTER I

INTRODUCTION

1.1 CorouÈines

The l-nventlonof the ¡rord "coroutine" is attribuÈed to Convray[29]


who describes a coroutine as "an autonomous program which communicates
with adjacent modules as if they were lnput or outpuÈ subrout.ines. Thus,
coroutlnes are subroutines all at the same level, each acting as if it
were the master progran when in fact there 1s no master programtt.

Ihis view of coroutines as 'rmutual subroutinestt[43] has remained


the most common víew of how coroutines can be used; lt ís epitomized by
the classic example of a parser call1ng on a synËax analyser for the
next token, and that lexical analyser calllng on the parser to dispose
of a token Just exÈracÈed from the input sequence. There is also a
relatlonshÍp, discussed by KnuthtS5l, between multi-pass algorlthms and
coroutines, which allows nulËi-pass algorithms to be fmplemenÈed using
coroutlnes, in such a \lray that the execut.lon of the passes is
interleaved.

For the purposes of this thesls, the following will be regarded as


the fundarnental characterisEics of a coroutine:
(1) the values of data local to a coroutlne perslsË between
successl-ve occasions on which control enÈers it (thac 1s, between
successive calls), and

(2) the execution of a coroutine ls suspended as conÈrol leaves it'


only to carry on v¡here ít left off when control re-enters the
coroutine aÈ some later stage.

Ihese characteristics describe a mechanlsm which allows coroutlnes


to call each other in a s¡rmmetríc fashion, and to pass control back and
forth between each other. Characteristlcs such as these have lead to Èhe

I
vLew that coroutines are some speclal kind of procedures ¡¿lth "oúm
variables" (see, for example, Fisher's dlscussion 1n t43l); the contrary
vlew Ls expressed later 1n thls chapter thaÈ procedures are a special
form of coroutines.

lllthin the constralnts represented by the above characteristics,


there Ls still some flextbllity as to the nanner 1n which the coroutines
execuÈe:

(a) If the coroutlnes communlcate only vla first-in-fLrst-ouÈ (FIFO)


queues, and if there ls no expliclt transfer of control between
the coroutines, then all lnter-coroutlne interactions can be
regarded as inËeractions between a producer (a coroutlne writing
an item onto a queue) and a consumer (a coroutlne r.rhich reads the
Item from the queue) . Under these conditfons, there arises the
possibility of parallel (either virtual or actual) execution of
the coroutlnes, when several of the coroutlnes are not waiting on
any of their producers.

(b) Alternatlvely, ít is possible to transfer control explicitly fron


one coroutine to another, causing the currently executing corou-
tl-ne to become suspended and a target coroutíne to resume
execution. In thls case, only one corouËíne is ever executing at
any given tf-me, and Ëhere arises no questlon of parallel
execution.

The first of these siËuatÍons wlll be referred to as Ehe I'inplicft


sequencfngt' kind of coroutlne and it can be argued, as does
Constantine[28], that this nas the kind of coroutine described by
Conway; ConstanÈlne goes so far as to say that Conway's coroutines are
addressed preclsely to the eIíminatlon of explicitly specifíed
sequencing. A good example of the lnpllcit sequencing kind of coroutine
ís provided by Ëhe system of Kahn and MacQueen[82] ' in whfch the
coroutines form networks and communlcate onJ-y by reading frorn, and
rrrlË1ng onÈo, one-rray communication channels (queues); Kal'rn and MacQueen
also pofnt otrt Ehe relationship beÈween this kind of coroutine and
tteall-by-needtt parameters, "Lazy evaluatíonrt and t'streams". Dennls [34]
describes a variant of the inpllclt sequencing kind of coroutines, which
he calls a rrdaÈa flow representatfontt, in which Èhe fnter-coroutine
communicaÈlon queues are lirnited to a maxlmum length of one, and are

2
called ttcommunicatlon variables"; wrlÈlng a value into a communlcation
varlable is held up until any prevlous value has been consumed by all
modules for whlch the variable provides values, and reading a value from
a communicat.ion variable is held up untll any prevlously read value is
replaced by a new one.

In all its forms, the ftnpllcit sequencing kind of coroutine


represents a language feature ln which the flow of control is not.
explicitly speclfied, but is dynamically determined by daEa dependencies
ln the program (that fs, by the "data flow'r); the execution of such a
program can be said to be I'data-drivenrr.

The second kind of coroutine described above' the "explicit


sequencÍng" kínd, ls the one rrhÍch ls well-tcnown Èo assembly language
programmers (for example, see [85rI44]), although it seldom receives a
great deal of attentlon ín the conLext of higher level languages. It l-s
thls kind of coroutine whlch was the sole subject of the investigatlon
descrlbed here, and will be discussed exclusively in the remainder of
thls thesis; the choice of the explicit sequencing kind of coroutine fn
this case ls not intended as a statement of preference for it over the
fmplieit sequencing kind. It is, however, Ëhe author's view thaÈ Ëhe two
kinds of coroutine should be dlstÍnguÍshed and thel-r study separaÈed.
Some comments are made at the end of this Èhesls as to hovr the ideas
presented hereln nlght be extended to the inpll-cit sequencing kind of
coroutine.

It l-s possible to regard the expll-cit sequeneing kind of coroutine


as a resÈricted form of the lnplicit sequencing kind, as is done by
Grune[59), for example; lt is also possl-b1e to view the explicit
sequenclng kind of coroutlne as a means of implementing or forrnulating
thê inpllclt sequencing kind (see, for example, 18211141)'
Probably the earliest published form of coroutlnes qrere the
ttgenerators" of Informatíon Processing Language V (IPL-V), a s1mbol and
list structure manlpulatl-on language described by Newell and Tongetlf3l ¡
the purpose of IPL-V's generaEors is the producElon of a sequence of
ouËputs, and the applicaÈion of a specífied process to each of the
outputs, to achieve the effect of an lteration statement. One process'
called the "superprocess", calls the Senerator and passes to it the
process (called the "subprocess") to be applied to the outputs, as an

3
argument.. Ttre generaÈor then produces Èhe flrst output and calls the
subprocess; after applyíng ltself Eo an ouÈput, Èhe subprocess'calls the
generator, slgnalllng elther thaL it requires another elernent from the
sequence, or thaÈ no further values are required. In the former case the
generator wlll return control to the subprocess after the production of
the new value, and in the latter case lt wtll return control to the
superprocess, it.s task complete. The subprocess and superprocess execute
1n one context, and Ehe generator in another; thus' an amount of context
switching attends the transfers between generator and subprocess. Durlng
the phase that the generaÈor is producing values to whlch the subprocess
applies ltself, the former can be regarded as subordlnate to the latter
and the relatíonshíp betnreen them can be regarded as asymnetric, being
that between a calling and a called routine. The fact that the generaÈor
executes in a different context from lts caller, and that Ehis context
fs saved between successlve calls, gives Ehe generator a coroutÍne-llke
behaviour. The relatlonshíp between the generator and the superProcess,
on the other hand, is more l|ke that between a procedure and lts caller,
sfnce the generaÈor restarEs the production of values from the seguence
each tlme thaË it ls called by the superprocess'

From these orlglns, the term rrgeneraÈor'r has come to be used fox a
coroutine whose behavLour ls rest,rlcted 1n that lt returns to lts caller
'(Lnvoker) on completion of its Ëask. Ilowever, a generaÈor is st1ll a
Coroutl-ne, in the sense that the values of local data ar.e reÈained
between calls, and execution of a generator always continues from where
ft left off when 1t reEurned from the previous call. The "semicoroutine'l
facflity of the Slmula language[32] and Èhe "semí-s¡mmetric coroutine
lfnkage" described by llang and Dah1t152l both provide a slmllar caPa-
b1l1ty Ëo generators.
A procedure can be regarded as a form of coroutíne which has
further restrlctlons on lts behaviour, ín addiÈlon to those for a
generator: 1t j-s a generator which starEs r.¡ith a fresh set of local data
and comnences executlon from its first statement (instrucEíon) on each
occasÍon thaÈ it l-s called, but becomes suspended (in the coroutine
manner) 1f it calls another subprogram, having it,s execution resumed at
the polnt of thaÈ call wlth the same local data values when that
procedure returns.

4
Thus, the relatlonship between coroutJ-nes, generators and
procedures can be viewed as one of imposing more and more restrictions.
Thls leads to the vlew, also expressed later tn this thesis' thaÈ the
cholce of one of these Ehree for a parÈicular subprogram being designed
represents a declsion about the expected behaviour of that subprogram'
1n Èerns of r¡hich of the resÈrl-ctlons (if any) apPly'

As has been prevlously pointed out by thfs auEhortl03l, Èhe


erroneous view has sometlmes been advanced (for example, by Grune[59]
and Jacobsen[72]) that the difference between corouÈlnes and procedures
(subroutines) is concerned rsf-Èh whether the return address for a
subprogram Ís sÈored in the activatfon record for the calling instance'
or 1n that of the called instance, respectlvely. The irrelevance of
where the return address is stored is demonstrated by the possibility of
implementing languages withou¡ coroutines, uslng a continuaÈion poínt (a
return address stored 1n the calling instance) schemetl04l, and the facE
Èhat f,Iang and Dahl's model of corouËlnes t 1521 does not use the
contínuation point scheme exclusively.
The formal semantlcs of coroutlnes and generators, and the question
of how to prove properties of Programs containing these features, have
been approached ín a number of ways. The most conmonly used one is the
êxiomatlc method of Hoaret66l; this has been employed by Clarke126l,
ClintlZTl, Dahl[31] and Prltchard[I23,L24), to describe the sementlcs of
Various restricted forms of corouËínes and generators' A more speclfíc
approach was developed by trlang and Dahl[152] to describe propertles of a
set of coroutine and generator features similar to Ehose available ln
Slmulat33l; variants of the l,tang and Dahl model have slnce been used by
Soffa and Lindstromtl3Sl Èo describe thto seParate extensions of the
feaÈures covered by Wang and Dahl, and by Sajanieml-tl30l Èo prove
propertles of a ProPosal involvíng groups of coroutlnes' Raulefst125l
has also, independenËly, rnodifled the I,Iang and Dahl model to describe an
extension of the feaÈures in t1521 which is the same as one descríbed by
Soffa and Lfndstrom; Raulefs also uses the denotatfonal semanÈics of
Scott and Stracheytl0gl Eo descríbe hls proposal' The rnodel of Bobror¡
and l^Iegbrelt[1g,2Ol can be used t.o describe coroutines, and it has also
been used as the basls of a deseription of coroutlnes by Aiello et
al. [1]. Finally, JanickLl73,74l uses an aPProach which is different from
all of the above to derÍve various propertles of hls ttvectors'r (groups)

5
of coroutines.
In the remalnder of thl-s chapter, the term "coroutlne[ r¿111 be used
to cover both coroutines and generators, excepÈ where generators are
speclf ically excluded.

I .2 PasL AoplicaÈlons for Coroutines

As noted earlier, the classic illustraÈion of coroutlnes is the


cooperaÈion between the lexical analyser and parser in a compller; in
fact, Conway's origínal descrÍption of coroutines !ìras in the context of
the cornpilatlon of COBOL prograns. Coroutines also figure 1n Llndstrom's
study of various control structures and Ëheir ttaptness" for the
programrning of a top-down parsert95l.
Coroutines can provide a means for a Progranmer to deflne
partícular backtracking sÈrategies, as has been demonst.rated by Gríswold
and Hanson in the conÈext of the SL5 language[57,6L]. Lindstrom[96] has
shown that coroutines and backÈracking, the latter ln the form of Ëhe
nondetermlnistic primitives suggested by Floyd[4S1, can be combined in a
coherent manner; in fact, Lindstrom has used Ëhls combinatl-on to
lmplement a "non-forgetful'r form of backtracking[94], tn r¡hich it is
possl-ble to remember previously searched subgoals and to re-use the
îesults of those searches. The utllity of combinfng coroutines and
backtracking is also discussed by Stallingstl4ll, in the context of
hrrlting interactive sysËems.
A coroutíne-based model developed by Druseikis and Doyle has been
used to describe extensfons to the paÈtern maÈchlng facllities of the
SNOBOL4 language t37 r391, and to permit Programmer-defined paËtern-
matching procedurest53l; the coroutine mechanism provided in the SL5
language is also concerned with the facilitation of string analysis and
synthesis t54l . Another coroutine-based model is that presented by
I^larrentl53l f or the evaluaÈlon of attrlbute graumars.

The coroutine faellity of Siuula lras Èhe main reason that ít was
used for the SCRABBLE Crossword Game program described by Shapiro and
Smlthtl33l. In thl-s program, the subprograur v¡hich performs searches to
find words which can be forued using the current seÈ of tlles was made
as a generator; this means that lt can return to lts caller after a

6
certain number of such words have been found, but that the search can
later be resumed if more words are required for that same set of tiles.
poËentlal uses for coroutlnes are described and classified
Numerous
by Sevclktl32l, t,hese uses comJ-ng from a number of applicatLon areas,
such as business data processing, Èext ProcessLng' simulatlon, and
varlous kinds of daÈa structure manlpulatlon.

1.3 Coroutines fn Programmlng Languages

It has often been saLd that there are few prograuming languages
wlth a coroutlne facllity; for example, this comment ls made by
Floydt46l, Grune[59] and SevciklL32J. As lndlcated in the survey of
Bobrov¡ and RaphaeltfSl, one group of languages which provides a number
of examples of coroutine facl-llties fs thaE concerned wiÈh artlficial
lntelllgence programming; those artlficial intellÍgence languages
containlng a coroutlne facility include CONNIVER[145] ' SAILlL26,L40) '
TELOS[89, 148] and 2.PAKll07, 10Bl .

Another group of languages well-known for examples of coroutine


features 1s simulation languages; Dahl explains ln t30l why lt Ls that
ttquasi'parallel processes'r (coroutines) are useful l-n a process-oriented
approach to slmulation. One sinulation language which has already been
ilentl-oned, and rnrhose coroutine facllíty ¡sill be discussed at some length
later 1n thls thesis, is Simula[16,33,70].
As discussed 1n the previous section, corouLines have proved useful
in strlng analysis and synÈhesis, and thls is reflec¡ed in the
developmenË of languages ln thls area, such as SL5[56'62] and lconl58]'
with some form of coroutine facility. Coroutines are also Present ín
some systems programming languages, for example' BLISSIl65l, Burroughs
Extended ALGOLl22l, and LSDtl2l; examples of other languages v¡hich allol
the consErucÈlon of corouEines are ECLÍL2})' GedankenlI2T), Lucid[6],
Oregano[l3], Madcap 6tl111, and SíL/z [38,55]

In additlon, some attempts have been made to provide coroutines as


extensions to existing languages; examples are Èhe system described by
Gentleman[49,51] and that of Skordalakls and PapakonstantinouII37] ,
r¡hlch both preprocess some augmented. form of FORTRAI{ Ínto ANSI Standard
FORTRAN, and also the scheme described by Gíloi and Hoffmannl52] for the

7
fntroductfon of coroutlnes lnto APL.

The remainder of Èhis thesís is organJ-zed as follows: Èhe next


chapter presenÈs a methodology for programmlng wlth corouÈlnes and gives
an example of 1Ès use. Chapter 3 then Lntroduces an aPProach to language
desJ-gn whlch lnvolves the desfgn of the semantics of the language' ¡¿hich
1s divlded into the design of the semantics of each of Èhree aspects of
the language and involves the use of speciflc semanËic models, one for
each aspect, followed by the design of the syntax of the language. This
method was used to design a language wtth coroutlnes which supports Ëhe
programning roeÈhodology of Chapter 2 and provfdes a general framework
for eoroutine programrnlng. Ihe design of Ëhe semantics of Èhis language
and the models used are descrlbed in Chapter 4. Chapter 5 descrl-bes the
synÈax of thp language, and Chapter 6 outlines an lmplementation of it
¡shich has been carried out. Finally, Chapter 7 presents some concluslons
and indlcates some directions for future research.

8
CHAPTER 2

PROGRA}IMING I^IITII COROUTINES

2. I Aspect s of Prosram Design

of constructing a program consists of the deslgn of


The process the
followlng aspects of the Program:
(1) the sequence conËrol sÈructure of the Program' using Èhe sequence
conËrol features of the language ln which Ehe program is written,

(2) the data control structure of the program, using the data control
features of the language, and
(3) the data structures used in the Program' using the language's
data structurl-ng facilities'

PraLttl21] defines sequence conÈrol as control over the order of


executlon of operations, boËh primitLve and user-defined, and he
catagorizes the sequence control facillties available in prograrnrning
languages according to where the control is exercised:

(a) in expressions; for example, precedence rules and parentheses,

(b) between statemenËs, and groups of statements; for examplet

conditional and iteration constructs,


(c) bet¡,reen subprograms; fox example, procedure calls'

The data control features of prograurming languages allor¡ Èhe


speciflcation of restrictÍons over which daËa structures are to be
accesslble ln, or known to, the various part.s of a program. Pratt, to
whom the partlcular terminology is due, deserfbes data control as
control over the transmission of daEa among sets of operatlons ina
Program.

9
EVery progranmer r.rritfng a program in a hlgh-level language assigns
some struc¡ure to the data manipulated by the prograrn; some data items
are composed of constltuent parts arranged Ln a manner significant to
the progranmer; others consisÈ of a slngle data Ítem, buÈ these have an
fnternal structurer so thaÈ the same string of bits occurring l-n two
fÈems may have completely different interpretaÈions. It is the purPose
of Ëhe data structurlng facilíties of a language to allor¿ the expression
of fhls structure whích the programmer has deslgned for the program's
data. In some programml-ng languages, referred to as 'rstatically typed",
the sËrucÈure (or Ëype) of data is clear from the statlc program text'
elther by declaration or from some other evidence; ín programs r¡ritten
in such languages, ft is possible to deduce the tyPe of any expression
fn the prograü' by an examlnaÈion of Ehe program text'

2.2 Proeram Structure


The structure of a Program can be assessed 1n many \f,ays, depending
on which of Èhe properties of the program are scrutlnize-d, and the leve1
at ¡uhl-ch thls scruÈfny occurs. The level at which Program sructure will
be assessed ín this thesis will invariably be that corresPonding to
subprogram units; in other r¿ords, assessnenÈs of program structure r.rill
be concerned wiÈh subprograms and their lnterrelationshlps. Two
þartlcular ktnds of program structure w1ll be mentioned:
(a) the sequence control structure of a program refers to the PaËtern
of possible transfers of control among the subprogram uniÈs
constltuÈ1ng the Program, and

(b) the daÈacontrol structure of a program is determLned by the data


sharlng relatlonshlps exlsting between the subprogran units of
the program.
These are boÈh characteristics of an executlng program and wilf in
general, change as the program's execution proceeds; they are therefore
regarded as aspects of the dynamic strucÈure of a program'

Programs also have a sÈaËic StrucÈure: thaË ls, Èhe structure


exhibited by Ehe program text. This structure also has sequence conÈrol
and data control aspect.s. Dijkstra, ln hls discussÍon on understanding
programs [35], states r'Èhe deslrabJ-lity Èhat the structure of the

10
program text reflect the structure of the computaËionr', and he then
lnvesÈlgaEes the consequences of this deslre, wíth respecÈ to sequence
control at t,he staÈement level. Corout.ines have a reputaEion for being
more dynamlc Èhan some other klnds of subprogram unit: for example, the
coroutlne transfer command ttresunett has been líkened to tta go t.o command
wlth a moving target'r L82J, and dynamlc (rather than statlc) scoPe rules
have been descrlbed as rtuseful for coroutíne programming" [621 . There has
traditionally been a larger gap between static and dynamic st.ructure ln
the case of coroutine programs, than r¿ith programs not lnvolving them.
One of the maJor aims of the work described in thís thesis was to
investlgaÈe ways of programming wlth coroutlnes, and coroutine
facllltfes for programmíng languages, whlch minimlze the difference
between the sËatfc and dynamic structures of a Program Ínvolvlng
coroutines; stated anoEher way, Èhe afm 1s to make the dynamic structure
more obvious from Ehe statlc structure.

2.3 Methodolosy f or Prograrnming with Q4¡qqt:149Ê


^
The moÈivatlon for devfslng thls meEhodology of programming \{as Èo
aid fn Èhe production of solutions to large, complex problems. fhis
methodology, llke a number of oÈhers, adopts a toP-dolün approach to the
design of programs, but, unlike them, admfts the possiblltty of prograu
componenËs belng coroutines and generators, ln addlEion Èo procedures.

task to be performed is dlvided into sub-tasks, and these sub-


The
tasks are divided tnto furÈher sub-tasks, and so on' unttl the sub-tasks
are of an elementary nature. The task Ls perforned by the program, and
each of the sub-tasks by a subprogram; thus, Ëhe division of a (sub-)
task lnto sub-Ëasks corresponds Eo the elaboraËíon of a (sub-) program
l-nËo a group of subprograms. The result of such a development process
will be a hierarchy, 1n the sense of Simonl135]' of subprograms. From
the above discusslon, lt is clear that Èhe meÈhodology focuses attention
on Èhe relatl-onships between subprograüs.

for the grouping of subprograms in the hlerarchy is the


The basis
sharing of inforuation, under a rest.riction knor¿n as the 'rprincíple of
opaqueness'r. This prÍnciple states that an item, r¡hether a subprogram or
a data structure, can only be accessed in the subprogram ln whlch ít is
deflned, ln the member subprograms of Ehis subprogram (íf it is a

11
group), and in Èhe members (if any) of those subrograms ln which 1t 1s
accesslble; in other r¡ords, access to an item is resÈrlcted to the sub-
hierarchy encompassed by the ltern's defining subprogram. In practice' ft
1s desirable to be able to restricÈ access to items even furEher' by
specifying that only a subset of the members of a group nay access an
item whfch could have been accesslble to all of thern. lhe principle of
opaqueness may be regarded as dellmlting the maxlmum accessibllity of an
item, and effectlvely hldes the lnner detail (both data structures and
of a subprogram from subprograms
ttoutsldett it'
Subprogram componenEs)
to the rrÍnf ormatl-on hiding'r criterion
used by
This is simllar
Parnastl20] 1n decomposing systems into modules¡ and is used by
declarlng ltems as lor¿ down 1n the hlerarchy as possibler so Èhat the
smallest number of subprograms 1s perrnitted to access it, whl-le sÈill
Lncluding all Èhose which musË have access to 1t'

As menËioned above, elaboratlon of subprograms into grouPs


contlnues unËil the the funcÈions of all subprograms which are noÈ
groups are suffíciently priml-tive thaÈ no further elaboration is
requlred. A subprogram whích has been elaborated lnto a grouP of
subprograms is referred to as caterval*, whereas those which have not
are elementarv.

, InÍtial.ly, all subprograms are regarded as coroutlnes; arbltrary


transfers are permitted (except, of course, for those forbidden by the
prlnciple of opaqueness). Assoclated wíth each of these possible
transfers of control is a t'Lransfer conditlonrr, which is a statemenË of
the circuüstances under whích that transfer of control wí1l take place.
The subprograms belonging to a Particular group can be viewed as nodes
in a network in whích the arcs represent the possible transfers of
conürol. The process of elaborating a subprograur ínto a group, whlch is
referred to as the I'caËervation[ of thaE subprogram, then corresponds to
a node l-n the network expanding Ínto another net¡vork. This noÈion of
node expansion bears some sirnilarl-Èy to the the process
trreconfiguration'r of Kahn and MacQueen[82], which fs vlsualized as a
node in a graph being replaced by a subgraph; the difference J-s that'
r¿ith Èhelr iroplícitly sequenced processes, the edges in the graph
represent communication channels, ral-her than explicit transfers of
* from Latln ttcaÈervattr meaning ttgrouptt

L2
control.
As a program strucËure deslgned usLng Èhis nethodology evolves
dynamlcally at run-time, elementary subprograms catervate into groups'
Just as they do durl-ng the deslgn of the program. A subprogram
catervates by creaËing the members of the grouP; the caEervaÈing
subprogran Ls regarded as becoming a member of the group, and is known
as the ttbosstt subprogran of the group. The latter is clearly always an
elementary subprogram, slnce any subprograms 1t creaÈes become further
members of the group, and it equally clearly is the first member of the
group to be created, since there ls no group when 1È 1s creaÈed. As w111
be seen, ln additlon to creatlng the other members of the group, the
boss of a group frequently also coordlnates the execuÈion of those other
members.

Thus, ft 1s clear thaÈ the property of being elther caterval or


elementary is not a constant one for a partlcular subprogram, both 1n
the deslgn of the program and durlng its execution, but changes as the
program structure evolves tn boËh cases: in the case of the desígn
process, a subprogram initially has no infrastructure, but may be later
elaborated, and in Èhe case of the executing program, a subprogram is
lnitfally elementary and has no member subprogram instances, but nay
later create some members.
Each subprogram keeps Ërack of lts o!fit sequence conÈrol stater as

follows:

when control leaves an elementary subprogram' the contl-nuation


point of thaE subprogram 1s seÈ to indlcaÈe the statement after
that causlng the transfer of control, and
. when control leaves a caËerval subprogram' the member from whlch
thts transfer emanates Is recorded as the acÈive member of the
grouP.

enters a caterval strbprogram' that control is passed


I{hen conËrol
to lts actlve component; ln Lhis way, an elementary subprogram (posstbly
the boss of a group) will eventually be identified on each occasion that
control 1s t,ransferred to a caÈerval subprogram. I^Ihen control is passed
to an elenentary subprogram, execution resumes at. lts contínuation

13
point.
The result of ls a serles of networks,
Èhe program deslgn process
1n which the nodes themselves may be neÈworks, and for each arc 1n these
neÈworks there is a transfer conditlon. The PaÈtern of passage of
conÈrol into and out of all nodes is then studied, by examining the
transfer condltions; any nodes for which these transfer conditlons
lndicate that the corresponding subprogram 1s called on Èo perform a
partÍcular task, and then returns to its caller' can be speclalized to a
generator or a procedure. As menÈloned in the previous chapter, this
speclalizatlon 1s deslrable, slnce lt provides informatlon about the
expected behavíour of the subprogram - lnformation r¡hlch may be useful
to someone atternpÈÍng to understand Èhe program, or to a Èranslator
program, for the PurPoses of oPÈinizaÈion. The choice belween a
generator and a procedure requÍres more lnformatl-on than Just Èransfer
conditions, and Ís based on whether or not Ëhe subprogram must retain
lnformatLon about lts state between returnlng and subsequently being
called again.

2.4 An Example: The Teleqrams Problem

The methodology of the preceding section w111 nor¿ be illustraÈed


vla an example; the choice of an example problen is both diffl-cult and
important. The programming methodology ls intended for ttprogramming-in-
the-large'r, and yeÈ ll-nited sPace demands a problen with a short
st,atenent and a relatively short solutlon.

The example chosen ls the "telegrams problerurt of Henderson and


Snowdont64l; it has been used by Barterl11] and, {n a modÍfied form, by
Jackson[71], to illustraEe varfous programmÍng methodologles, and it
seems to be relatively useful in that role. The problem, as staÈed by
Henderson and Snowdon, ls the following:
A prograur is required Èo process a stream of telegrans. This stream
l-s ava1lable as a sequence of letters, dfgits and blanks on some
devlce and can be transferred in sections of predetermined sl-ze into
a buffer area r¿here 1t ís to be processed. The words in the telegrams
are separated by sequences of blanks and each telegram 1s dellmited
by the wotd. "ZZZZ". The stream is termínated by the occurrence of the
empty telegram, thaÈ is a telegram with no words. Each telegram is to
be processed to determine t-he number of chargeable words and to check
words. ttZZZZtt and "STOPtt are
for occurrences of overlengÈh The words

I4
not chargeable and hrords of more than twelve let,ters are considered
overlength. The result of the processlng ls to be a neat lísting of
the telegrams, each accompanied by the word count and a message
lndlcatlng the occurrence of an overlength word'

An ouÈl1ne of a program to solve this problem will be developed in


this section; the outline v¡íll malnly deal wiËh ínteractions at the
subprogram level, which are the maln concern of the methodology. This
outllne, and its development, w111 be presenËed usfng a dlrected graph
noÈatlon in whlch the nodes 1n the graphs represent subprograms and the
arcs represent possible transfers of control. AssoclaÈed wlth each arc
there w111, of course, be a transfer condition; for each caterval
subprogram, Èhe data sharlng relatlonships will be given by specifying
which of the members of the group have access Èo each of the data items
known to the grouP. A complete program to solve Èhis problen, phrased l-n
terms of Èhe programming language designed later ln thls thesis' is
presented in Appendíx B.

At fl-rst, the network representLng the solutlon of thls problen


consists of the single node

whose function ls to Process the stream of telegrams'

, The first group of subprograms 1s concerned with the sharing of the


buffer data structure: the network conslsts of a node (tt2tt) whose func-
tion it fs Èo f111 the buffer from the lnput file, another ("3") which
extracts telegrams from the buffer and processes them, and the boss of
the group ("1tt) which performs initializatlon relevant Èo the group and
also may perform some actíons on program Èermlnatlon. The corre-sponding
network ís
¿i ¡ fr rtsrc

1n ¡shich theellipse signifíes thaE these nodes together constituLe the


whole of a group. Notice that the boss of the group ls below the other
members; this wfll be so in all networks depicÈed in thÍs sectíon'

15
In additlon to Èhe buffer, whlch is shared primarlly between nodes
2 arrd 3, node 2 must have access to thq inpuÈ file and node 3 to the
output flle; all of these data structures are also made avallable to the
boss of the group (node 1) for the purposes of initializatlon and
termlnatfon actions. The data sharlng relatlonshlps in the network can
thus be summarized as:
1r2: lnput fflei Lr?r3: buffer; 113: ouÈput file

The transfer conditlons for thls network are derived from its
structure and from the stated functlons of its member subprograms; these
transfer condLcions are as follows:
(1,3): lnltial start-up
(3,2) the buffer needs filllng
z

(2,3) the buffer has been filled


¿

(3, 1) : enpty telegram has been encountered (normal termlnaÈlon)


(2, l) : asked Eo fill the buffer when already at the end of Ehe
input flle (abnormal termlnation)
The function of node 2 is sufficiently slmple that it does not need
Ëo be elaborat-ed into a network: lt copies characters from Èhe lnput
file to the buffer, padding out the buffer with blanks if Èhe end of the
l-nput fLle is detected during this copying process. If the lnput flle is
already positloned aÈ its end when control enÈers node 2, control ls
transferred to node 1. Notlce that Èhere ls no requirement ln the
problem for the buffer to conÈaln whole ¡¡ords, although the solution of
Henderson and Snor¿don works Ín that manner, which results in an
inefficlent use of the buffer; the concept of a "word" ls not relevant
at the level of the above netrsork.
Node 3 1s no\f elaborated, and the key data structure ln that
elaboratÍon is the word. The requlremenË for a "neat" llsting of
telegrams is taken to mean thaE multl-ple blanks between words in the
inpuÈ are to be converted to single blanks in the output; thus only the
words are sígnlficant and need to be recorded. The boss of the group
(node 3) controls the processing of telegrams; it ftrstly calls a
subprogram (node tt4") which extracts the next word from the buffer, and
lf Ëhis word ls "ZZZZ" then the ernpty telegram has been found and
control is transferred to node l. If the r¿ord is not "ZZZZ", control is

16
transferred to a subprogram (t'5tt) whlch Processes a slngle telegram;
node 5 calls on node 4 r.rhenever a new word is regufred, and transfers Èo
node 3 when the r¿ord "ZZZZ", slgnifying the end of thl-s telegram, is
detected. Node 4 slnply exEracts a word from the buffer and recurns
control back to its caller (node 3 or 5) when Èhis 1s done; if the end
of the buffer is encounÈered as the word is being bul1t up' control is
Èransferred to node 2, which f1lls the buffer. The network for this
group has the sÈrucÈure:

to2

from 2

to I
from I
Notlce how thl,s diagram l-ndlcates Èhat nodes I and 2 have no
knowledge of the inÈerna1 details of Èhe grouP; to them the entlre group
1s known sirnply as node 3. For example, when node 2 has filled the
buffer, and returns control to node 3, 1Ë Ls node 4 to which control
acgually passes, since it rvas thls member of the grouP knov¡n as node 3
which was lasÈ active.

The data sharing relatlonships for the above grouP are:


314: buffer; 3,415: current word; 315: output flle
and its transfer condítions are:
(3,4) ,(5r4): the nexÈ word is required
(4,3) , (4,5): the next word has been found
(3, 1) : the flrst word of a new telegram ís "ZZZZt'
(3,5) : the flrsÈ word of a netù telegram is not "ZZZZ"
(5,3) : the word "ZZLZ" has been found
(4,2) z the buffer needs fill1ng
Node4 1s nor,r elaborated, at the level of characters; a node ("6tt)
l-s defined whích extracts the next characEer from the buffer, and this
node ís used by the boss of the group (that ls, node 4) which bullds up
words by skipping over sequences of blanks, storing non-blank characters
whLch follow, and then Ëransferrlng control to node 3 on flndíng another

T7
blank. The following diagran shows thl-s network's relatively simple
s trucLure:
to2
from 3r5
to 3r5

If the end of the buffer, it requests node 2 to fÍll it;


node 6 detects
noÈice that the original arc from node 3 to node 2 was transformed into
one from node 4 to node 2, and now into one from node 6 Ëo node 2'

The data sharing ir.t the above neÈwork can be described as f ollows:

4: wordi 4,62 currenÈ character; 6: buffer

and the transfer conditlons are:


(4r6): next character requlred
(6r4): next character exÈracted from the buffer
(4'3) , (4,5): next word identifled
(6'2) s the buffer needs fllling

The function of node 6 ls suffíciently slmple that ft does noÈ need


to be elaborated.

. task to be perforured by node 5 is also relatively straightfor-


Ttre
r^rard: 1t prints a heading for the new Èelegram, then reads words (by
calllng on node 4), charges then if they are chargeable, and llsÈs Lhem;
thls is done untfl the wotd "ZZZZ" is found, at Idhlch polnt a report is
prlnEed, Lndlcating the number of chargeable ¡.¡ords in Èhe telegram and
the occurrence of overslze words, if any. Elaboration of node 5 is not
necessary.

This completes the desfgn of the program at the subprogram level;


the cornplete structure of the program can be depicted as Lhe network in
Figure 2.1. The nestlng of the circles and elllpses in this diagram
represents the grouping of subprograms in the program. Each of the
subprograms in the program represented by Fígure 2.1 ís a coroutine, and
could be left as such. Hor¿everr âs dlscussed in Chapter 1, generaËors
and procedures are regarded as rest.rlcted forms of coroutfnes which
return Èo their caller after completing sorne task. Now, the transfer
condltions for the network ln Fígure 2.L ate exarnined to see f-f any of

1B
the nodes ln that neËwork happen to adhere to thls restrictl-on. The
reason that this ls done, raÈher than slmply leaving the subprograms as
coroutLnes, ls that 1f the fact thaË a subprogram exhlblts this 'rret,urn-
to-callert' behavlour 1s expressed in the program text, it can be used by
a reader of the program (to aid in the process of understanding the
progran), and posslbly also by the language Processor (to optinize the
executlon of the progran).

Ffgure 2.1 The Structure of the Solution to the Telegrams


Problem

The resulÈs of examinlng the transfer conditions of the neÈvrork of


Figure 2.1 for evidence of this rrreturn-to-callertt behavlour, are
summarlzed in Table 2.I. Each llne in this table represents a subprogram
whlch exhlbits thls behaviour to some extent. As an example, consider
rrnexË character
node 6: the Èransfer condítion for the arc (4r 6) 1s
requlredtr and that for the arc (614) is Itnext character extracted from
bufferrr. These transfer conditl-ons clearly show thaL node 6 is called on
by node 4 to perform a parËicular task (the supply of a single
character), and that it returns to lts caller on completion of thl-s
task; thus, node 6 can be said to be behaving 1n the restricËed manner
of a generaÈor or procedure.

19
Table 2.1 Caller-Callee RelaÈl-onshlps 1n Figure 2' 1

Caller Cal1ee FuncÈion of the Callee

I 3 exÈract telegrams from the buffer and process them


3 5 process a slngle telegram
3 5 4 exÈracE the next word from Ehe buffer
4 6 extract the next character from the buffer
6 2 load the buffer from Ëhe inPuË file

One case where a "purett coroutine rnight be expected ln this progran


1s node 2, whlch not only has a normal ret.urn via the arc (216), but
also has an abnormal exit along the arc (2't). Ilor¿ever, it so happens
thaÈ thls kind of "error exlÈtt ls often useful for generators, and has
been included ln the language whose deslgn J-s presented later 1n thfs
thesls; consequently, node 2 can also be coded as a gerierator l-n this
language. In facË, an examlnation of the Prograü presenËed in Appendix B
which ís based on this solution (see Sectíon 8.1) reveals no "pure"
coroutlnes whatsoveVêr.
The chofce between a gènerator and a procedure for a subprogram
exhlbiting 'rreÈurn-to-ca11er" behaviour l-s not based on any one plece of
ÍnformaÈion, but depends on a number of faetors, some of them concerned
i{1th Èhe detailed codlng of Èhe subprogram. Anong these factors are
whether or not an error exit such as Èhat above is required, and whether
or not it 1s necessary for the values of variables local to Èhe
subprogram to be retained between successlve activations.

20
CHAPTER 3

A PROGRAMMING LAI{GUAGE I^IITH COROUTINES

3 .1 Introduction
The motivatfon for designlng a nerr programming language was that
there are relatlvely few languages wiËh a high-level coroutlne facilfty
(as distlnct fron languages in whlch coroutines can be simulated), and
thaÈ those languages which lnclude such a facllity are almosÈ invarÍably
the so-called t'advancedtt programming languages. As such, Èhese languages
also contain a number of novel features not concerned wl-th coroutines¡
examples of such features are the class prefixLng and slmulation
scheduling features of Simula[16], and the data base faclllty of
TELOStSgl. The pre,sence of these advanced features tends to make sinple
coroutlne programs (those employing the usual features of a procedural
programming language, as r¿ell as coroutl-nes) dlfficulÈ to wrlte' read
'and debug; in addition, the efficlency of the implementation of these
languages ls often much less than that of familiar programming
languages.

This thesis reports Èhe resulÈs of an experiment 1n language design


and ímplementatíon, almed aÈ designing a general-purPose programming
language which, in addition to all of the features expected of such a
language, is augmented by Èhe inclusion of coroutlnes' In this
experiment, ernphasis was placed on data conÈrol and, as a result' some
relatlvely advanced data conÈrol features were lncluded in the language.
Thls was because of Èhe wider range of data sharing relatlonships which
tend to arlse when programming with coroutlnes, compare<l v¡íth those
which occur when r,trl-ting programs involvLng only proeedures ' This
lncreases the varfety of data control structures that a programmer may
wlsh to construct for a program and this, fn turn' places extra demands
on the data conËrol feat.ures of the language'

2T
The next sectlon enumerates the goals of the language deslgn, by
descrlblng some criteria by which Ehe final product should be judged'
The following sectfon descrlbes a methodology for programmLng language
desl-gn whfch results ln the deslgn of an abstract descripÈlon of the
semantics of each of several aspects of the faciltty belng designed.
Thus the semantics of the whole language will not be descrlbed, buÈ only
that part related to coroutlnes; the remalnder was borrowed from a "base
languagett. In fact, a class of languages is described by the abstract
deseripÈfons of the various aspects of the facility, slnce they could be
used to add the factlity to a number of existing programning languages.
The chotce of the parttcular base language used is explained ín the lasÈ
sectlon of this chaPter.

3.2 The Desisn Goals

These goals have been ínfluenced by the views of a number of


auÈhors, noËably by Èhose of Dijkstra[35], Hoare[67]' LeBlanc[89], and
l,llrth [ 160, L62,163]; the design goals were that:
(1) the language should support the prograrnming methodology described
1n Chapter 2, in that it should allow Ehe expression of
hierarchlcal structure and data sharlng, and the suspension of
groups of coroutines should occur 1n the manner described in tshat
chapÈer; however, apart. from caÈering for programmlng-in-the-
large ln this way, the language should also factlitate the
wrlting of small programs, and programs which use coroutines only
ln a incldenÈal waY,
(2) a programwritten in the language should be easily comprehended
by a human reader - in particular, the various comPonents of Èhe
prograro's textual structure should be readily apparent from the
text,
(3) the dynamlc structure of a Program, consisting of its sequence
and data control components, should be reflected as accuraËely as
possible in its statlc (textual) structure'
(4) 1t should be possible to express a wLde range of sequence control
strucEures, data control strucÈures, and data structures ln the
language; ln partlcular, current programmlng languages generally

22
do noÈ allow the accgrate expressJ-on of a wide range of data
control structurest
(5) the set of feaÈures provided |n the language should be as small
as possl-b1e, while st111 allowlng the succinct exPressfon of
solutions to a wide varieËy of problems, and these features
should be sinple and readily understood; in partlcular, Èhe
temptatfon to introduce other ttadvanced" facillties noÈ related
to coroutines should be avolded,
(6) it should be possible for an implementation of the language to
ensure the secure execution of any program written in the
language, by enforclng all of the restrLctions of Èhe language,
and

(7) the language should lend itself Eo fast conpilation l-nto


efflcient object code, the latter being efflcLent wlÈh regard to
boÈh tlme and storage utllizatlon.

It 1s clear from these crlteria that. the expression of structure


rùas an l-mportant phílosophy underlylng the language design: a Programmer
often knows a great deal about the strucÈure of a program being wrltten'
but is unable Ëo express thl-s information Ín the programming language
belng used (excepE, perhaps, as commenÈs). Thts represenÈs an area which
has long been contentious ín prograrnmlng language desígn; some designers
have held Ëhat a hlgh level language Èranslator should deduce l-nfor-
naÈl-on, rather than have the Progranmer state 1t, while others have
argued that the efficiency of the translatlon process can be lmproved by
not having the translaÈor deduce lnformatlon which rlas kno¡¿n to the
programmer. The stance adopted here differs fron both of these: tt is
clear that the programmer should be able to exPress information about
the (expected) struct,ure of the program (about the tyPe of varlables,
about where ldentlfiers are accesslble, and so on), purely so thaÈ these
assertions cân be checked agalnst actual program behaviour.
Notice that Èhe criteria staEed above interact to some extenË, and
that some priority ordering is necessary in Erade-off sltuaËions. The
priorities applted rrill become obvious as the deslgn is discussed l-n
detall; two of the more corrmon and important trade-offs were resolved as
follows:

23
the flrst four crlteria take precedence over the flfth (expresslon
and comprehenslon of structure ls more lmportant than minÍmality or
slnplicicy), and
the sixth criterion has higher prioriÈy than Èhe seventh (securlty
1s rnore important than eff l-ciency).

3.3 Proerammins Lanquage Desl-gn

To date, progranming language deslgn has been largely carried out


on an ad hoc basis; in the r¿ords of LeBlanc[89]' rrthe programming
language desígn process is far from an exact science'r. Furthermore, the
líterature contalns lit.tl-e specific guidance for Èhe prospecÈlve
progranmlng larrguage destgner; those authors, such as Hoare and I'Iirth'
who offer advice on language desfgn, sirnply propose various crlteria by
which a completed language deslgn can be judged, but do not advise on
how to produce such a deslgn.
In thls sectlon, an approach is descrlbed whlch makes progrannlng
language design more methodical and which was used exclusively ln the
desl-gn of the language described in Èhis thesis. The approach used here
would seem to be useful in all prograurmlng language design, but 1s known
to be particularly helpful when the following conditlons hold (which
they did in Èhe present case):
(a) an extension to a language is belng deslgned, raÈher than an
entire new language - in the present case' a coroutlne faciltty
rüas beJ-ng deslgned and the other features of the language were
sl-nply borrowed from a base language' except where they needed to
be ¡uodifled because of the addition of the coroutlne facllity'
and

(b) the deslgn process is not bel-ng conducted ín a vacuum, ín thaÈ


other proposals have been made for slmllar faclllties; 1t ls then
important Èo relate these proposals to each other and to Ehe
facllity befng proposed, and thls is best done using a common
rnedium of expressíon.

The approach used in the design of the Present language r¿lth


coroutlnes consisÈed firsLly of the discipline that the semantics of the
coroutlne f acilíty \,fas cornpletely designed bef ore ÈhaE f aciliÈy vras

24
given a syntacElc form and ernbedded ín the base language. Furthermore,
the design of the semantl-cs of the coroutine facilíty was divided into
the deslgn of that of three aspects of the facllity' corresponding to
the three aspects of programs dÍscussed in Chapter 2: sequence control,
data control and data strucÈures. It turns outr 1n practice' ÈhaÈ
programming language features can be conveniently divided into those for
the description of each of these aspects of programs, and that the
deslgn of feaÈures r.rithln one of these aspects is relatively lndependent
of that of the other two aspects. The categotizatlon of language
features inÈo these three groups is similar to the notfon of 'rconÈro1
separatÍon'r described by Lemon et al. 1921, in which only two categories
are used: one for the "data-relatedrr components of a language, and one
for the ttconÈrol-related" components.
For each of the three aspects, the following steps r+ere taken:
(1) fl-rst,ly, an abstract model of this aspect was designed,
(2) next, the nodel for thfs aspect hras used Ëo compare previous
proposals and exlsting languages with Èhe facíl1ty of interest'
and

(3) finally, the semantics of Èhls asPect of the proposed factlity


Iüas desfgned uslng the model, by using the model to describe
varlous alternatlves, Èo aid |n the Process of naklng chol-ces
from among these alternatives.

Clearly, the use of modelsis central to Ehis approach to language


desl-gn, and Èhe choíce of appropriate models ls both difftcult and
lmportant. Each of the models must focus on the partícular aspect
concerned, while ignoring the other asPects, and, q¡here possible' the
model should also concentraÈe on characÈeristics of particular lnterest
Ín the case of the facilfty belng destgned. In prevlous cases where
models have been used to compare programmÍng languages, Èhe comparisons
have been gross ones; for example, Herriot's GLOSS rnodel[65] describes
the rrstaÈe strucÈurerr of programmÍng languages (whích corresponds, in
the terminology used here, to both of sequence control and data
control), ignoring only thelr "value-types" (daÈa structures) asPe-ct.
The more speciallzed models used in this language design allowed the
deslgn task to be divided lnto conveniently-sized, but relatively

25
independent, sub-tasks; they also meanÈ that the descriptlons 1n terms
of the varíous models were siuple and facflltaEed tTre process of making
comparísons.

Stanat and McAllLster ÍL42) deflne a model as "an analogy for some
obJect or phenomenon of ínteresÈrr and the three models used 1n this
thesfs all represent analogies. They do, hol¡everr Var1z greatly in the
extent to whlch they are "formal" or rrmaÈhemaËical'r. The model used in
the design of Èhe data structures aspect of Èhe coroutlne facility
consists of a partlcular (lnformal) vlew of the data structures required
to support coroutÍnes, buÈ thls Idas adequate to make the necessary
comparisons, and to descrlbe this aspecE of the proposed coroutine
faellity, 1n an abstract Iùay; 1n fact, very líttle ls saíd about daÈa
structures, since most of these were borrowed from the base language'
rrrith the addition of only those necessary f or corouti-nes. The models
used 1n the design of the other aspects are both more formal: ín facÈ,
they are both ttoperaËiona1 models'r, in ÈhaÈ conputations are represented
as, sequences of transformaÈlons on lnformatlon strucËures and the
semantlcs of a partícular language feaËure is described in terms of the
effect that tts execution has' on the inforuaÈion structüEês. The result
1n all three cases \ùas, however, the Same: an absLract description of
that aspect of the proposed facility. The design of the semantícs of all
three aspects of the proposed facillty is described 1n Chapter 4.
t{hen all three aspecEs of the coroutlne facllity had been designed
1n the above manner, a syntax consistenÈ \üiÈh the base language was then
developed. As Hoare has sald[67], the design of syntax is not a trivial
or arbitrary aspect of language deslgn, and 1t deserves Ehe greatest
care. However, 1t ís lmportant thaÈ the design of a language's syntax be
entfrely separate from that of its semanEics: PremaËure commÍtment Èo a
partlcular synËax ís one of the maJor mechanisms by whlch arbitrary' or
unconscious, decisions are made about the semanLics of a language'

The same set of three abstract descrl-ptlons could be applied to


varlous base languages, Èo produce different languages wíth coroutines.
In Èhe case of the design descríbed in this thesis, there are only Èhree
rnaJor restrict.ions deÈerminlng base languages to which the coroutine
facflity could be added:
(f) the language must be procedural slnce iÈ is the exPlicit

26
sequenclng kind of coroutines r¿hich are belng consldered fn this
thesis,
( il) the language must be such that programs consist of textual unlts
(called blocks) over the whole of whtch Èhe same set of names,
with the same set of interpreÈations, is known - such languagest
whtch will be deflned later to be block-strucÈured, have Ehe
advanEage of allor¿ing the programmer to fact.otLze the sÈate space
of a program lnto ueanl-ngful subspaces, whtch greaEly alds the
development process and improves the readabillty of' the final
product, and

(i11) Ëhe language should require the declaration of all names used 1n
a program (apart, perhaps, from a seÈ of "predeclared'r names) and
such declaragions should indicate, to some exÈentr the kind of
quantlty for which that name is to be used that ls, the
language should be statlcally tvped.

These resÈrl-ctl-ons define the breadth of the class of possible base


languages, and they are sÈaEed here since they greatly influenced the
design of the models used, and other Parts of the desígn process'

FurÈhermore, although Èhe developed design can be applted Èo a


n-umber of base languages, there is some advantage 1n reveallng at thfs
stage the particular base language chosen; this may be considered
prerna¡ure, slnce the syntax was not designed untll after the semanÈics
rüas completely speclfied, buÈ it lras importarrt that the particular
properties (and difflculties) of this base language were adequately
covered during Che design process. The next sectÍon discusses the choice
of thls base language.

3.4 The Cholce of Pascal as the Base Languaqe


pascal[75] was chosen as the base language f,rorn which was derived a
partlcular language vrith coroutínes; the syntax of this latter language'
named ACL (a coroutine language), ís presented in Chapter 5 and its
fmplementatlon 1s discussed 1n Chapter 6. The choice of Pascal vÍas
lnfluenced by the following factors:
(1) lts popularlty and r^ríde availabllity, which allows the use of the
Pascal idl-on with a minímum of explanation'

27
(2) lts set of sequencecontrol primitfves at the statemenÈ level 1s
powerful, and encourages the producÈLon of subprogram units whose
lnternal structure ls lucld,
(3) lts set of data strucÈurlng feaÈures fs snall but qufte
expressÍve, and

(4) a of Lmplementatlons of Pascal exlsË which are relatfvely


number
easy to modtfy; one exanple ls Pascal 'P'[115], and prevlous
experlence with thls implementatlon[104] had suggested that lts
modiffcatLon lras ltkely to provLde a convenient means of
fmplementfng a prograrnmlng language, based on Pascalr contalnlng
a coroutl-ne facilltY.

28
CHAPTER 4

THE DESIGN OF THE SEMANTICS OF THE LANGUAGE

4. I The tlcs of the Data Structures Aspect

In dlscussing the daÈa structures required to support coroutÍnes'


it ls firstly lmportant to dlstlngufsh between the definltlon of a
subprogram, and. an instance of 1t. Whereas programmlng languages
fnvarlably provlde mechanisms for referrlng to subprograrn deflnltlons,
1t 1s not conmon for them to also provide a means of referring to
lnstances of subprograms. In languages which allow recursive procedures
and funcÈions, and hence rnultlple co-existlng lnsÈances of a single
deflnltlon, potentlal ambigulties are resolved by only allowing one of
these lnstances I the most recently creaÈed one' to be (inplicitly)
accessible at any one tlme ln a progranr's execution; in thls waY, the
need for ways of expliciËly referring to instances 1s avoided. To only
Þe able Èo (lnpltcltly) refer to the last ln a sequence of recursive
actlvatlons of a procedure or function turns out to be approprlate in
the situatlons in which these subprograms are commonly used (such as the
factorial funcÈion and Ackermann's functlon) '
coroutlne proposals, such as those of SaJanlernitl35l and
Some
pritchardtl23l, do not allow rnultlple lnstances of coroutlnes, and this
allows the definiÈ1on name Ëo also be used as Èhe instance name'
Ilowever, 1t is very useful to be able to create several Ínstances of the
same corout1ne deflnltion, perhaps using dlfferent actual Parameter
values on each occasion, and to be able to refer to each of them
lndivldually, at the same point ln a program's execution' As an example,
conslder the case of creating several lnstances of a random number
generator definltion, perhaps with dlfferent seeds'

Thus, iÈ ¡.ras decided to a1low multlple instances of coroutl-nes, and


Èo provlde a rneans of referrlng to Í-nstances ln an expllcit fashion. To

29
date, languages allowing expllclt namlng of subprogram lnstances
(usually those of coroutlnes or processes) have achieved lt by provlding
an rtinsLance referencett data type (data strucÈure), variables of this
type conÈalning a reference to an lnstance. Consequently, ft is possible
l-n such languages to have several fnstance reference variables conÈaLn
references to a single lnstance, aÈ the one time'

of the languages with these Lnstance reference varlables


Some
requlre some kind of type lnformatlon Èo be given wLth their
declaratlon. In most cases, thi-s type i.nformatlon conslsts slmply of the
assertlon that the variable will only be used to hold references to
lnstances, but no restrlctlon can be placed on which lnstances; this Ls
referred to here as weak tvplng of lnsEance reference varlables, and
occurs ln Oregano[13], GenËlernan's porËable coroutlne system[51] '
CorouÈ1ne PÀSCALt9ll and ECLll22), among others. In Sinula, the tyPing
of instance reference variables ls somewhat stronger (more lnformaElon
l-s requlred), and is referred to as f al-r1 v strons tvpine: an instance
reference variable l-s declared to be ttquallfled byt' a class ldentlfler,
say rrAtt, and ûay legally contain references to lnsËances of various
classes related Èo the class A (lncludlng A itself); the rules governlng
which classes are allowed, and which are not' are explalned slmply in
[16].
In order to mlnimize the differences between statlc and dynamJ-c
program st.ructures, the instance reference approach \{as not adopted;
instead, the 'rinstancet' data structure qras lntroduced. Variables wiËh
thLs strucÈure, called rrinsLance varlablesrr, conËaln insËances, rather
than references to them. The possibility of several variables containing
references to a slngle lnsEance thus does not arise and thls, along with
certaln data control resÈrictions and dlsctplines to be discussed later'
allows a closer correspondence between the static and dynamic structures
of a program.
are st
InsËance variables v typed tn ACL¡ an instance variable
may only contain lnstances of a partlcular deflnltlon, r.rhose ldentlfl-er
is specified at the declaration of Ehe lnstance varíable' Strong tyPing
of instance variables rras adopted since it represents the klnd of
lnforrnatlon a progranmer uslng the language will know about the expected
use of an lnstance variable, and ít is a stated objectlve of thls design

30
that the programmer should be afforded the opPortunlty to sÈaÈe such
lnformatlon (and to have 1t checked).
InÍÈ1ally, an lnstance varlable cofitalns Èhe value ttno-Ínstance",
lndlcatlng thaÈ lt does not contaln an lnstance; a predlcate ls provlded
whÍch accepts any lnstance varlable and evaluates to elther
tttrue" or
ttfalse", dependlng on whether or not the varlable contafns an lnstance.
Also, a procedure ls provided whlch ttdeletes'r an instance by seEting Èhe
corresponding lnstance varlable to 'rno-lnstancett. Another predicate
provided in the language fs one whtch evaluates Èo t'truett only ff the
lnsËance varlable provided to 1t contains Ëhe currently executfng
lnstance. Clearly, the two predicates and the procedure accePtr âs
arguments, lnstance varÍables of any tyPe.

AnoÈher lupllelt Lnitlalization which occurs ln ACL is ËhaÈ all


polnÈer variables are lnitialtzed to the value ttnlltt; ttris is necessary
as parÈ of the storage managenent scheme used (see Chapter 6 ). Ihe
lnl-tlal values of all other variables are undeflned'
Iu some of the discusslons to follow, 1t will sometlmes be
necessary to distinguish betr¿een subprogran deflnitions on the one hand'
and all other items l¡hlch can be named in a program (lncluding' of
course, instances of coroutlnes) on the other. In such cases, the former
l¡tll be referred Èo as "subprogram ltems'r and the latter as ttdaËa
itemsrr'

31
4.2 A\e Semant s of the Sequence Control AsPect*

4.2.I IntroductÍon
Thls aspect of the design ls concerned only with sequence control
between subprogram instances. Features concerned r¿íth sequenclng between
staËements and groups of statements, and sequencfng wlthln expresslons,
w111 not be discussed; Ln fact, such features were borrowed from the
base language. Furthermore, slnce the discusslon will not be concerned
rvl-th data control, it ls assumed that any ldentlfiers referred to ln
seguence control operatl-ons are accesslble.
Since there are no differences between procedures and functlons ln
Èerms of sequence control effect, funcÈlons w111 not be consÍdered
separately ln thls section; any argument applied Èo procedures may also
be applled to funcÈions. Siuilarily, arguments applled to coroutines and
generators may also be Èransferred to subprograms whlch have the same
sequence con¡rol effect, but whlch return a value (that ls, r¿here the
calling expression ylelds a value), where such subprograms exist in a
language . Also, t.he so-called "anon¡Imous " blocks of some block-
sÈructured languages (for example, A1gol 60 tll2l ) w111 not be considered
separately from procedures, because of their sequence control
sfmllarity.
The remainder of this section f s organLzed in a manner v,rhich
reflects the steps acÈually taken ln the deslgn of thls aspect of the
corouÈine facilfty:

ffrstly, a model of sequence control aË the subprogram level is


presented,

Èhen, some exÍsting and proposed coroutlne facilítles are desclbed


and compared using the model of sequence control, and

finally, Èhe proposed facility is descrfbed in terms of the


seguence control model.

* A prellminary version of the materlal covered 1n Ehis section r¿as


publlshed in If02].

32
4 .2.2 T:he Sequence ConErol Model

The model used 1n the deslgn of the semantlcs of Èhe sequence


control aspect,, whlch r,rill be referred Co as the sequence conËrol model,
was deslgned to focus on sequence control at the subprogram level, and,
fn partÍeular, on those facets of lnteresË when descrlbing coroutine
facillttes. The model used was lnltlally lnsplred by one descrlbed by
Stantontl43l. Stanton's nodel conslsts of four rrprlmltlve" operatÍons:
(a) create d : thls operatlon establlshes an lnstance of the
subprogram r¿hose defl-nltlon name Ís "d", and the expresslon
ttg."t. d" evaluates to a reference to thls ínsÈance; wlthln the
fnstance, the continuation point is set to lndicate the fÍrst
staÈement in Èhe deflnitl-on;

(b) enter I : executÍon of this operaÈlon causes the contlnuation


polnt for the eurrently exeeutLng Ínstance to be set to the next
statemenÈ to be executed, after whlch thls fnstance becomes
suspended and the fnsÈance lndlcated by
rrirr (re-)commences
executlon at lts continuatlon Polnt;

(c) exit : in Stanton's model, there ls defLned for each instance an


instanee reference varíable, called "receiverrr, which is used by
thls prlmltive; wheneverttexit" is eneountered, the lnsËance
Lndicated by the receiver varlable of the currently execuÈlng
ùrstance is entered;

(d) delete f : this prlmltive causes the specl-fled instance to be


permanently díscarded.

The first two primltlves above are also present in the sequence
control model. Notlce Èhat instance reference variables are used in Èhe
model, whereas fnstance variabl-es have been chosen for ACL. Instance
reference asslgnment and mulÈiple references to lnst.ances are both
necessary in the descrlptlon of sequence control operatlons' and Èo
allow thern ln the sequence control model is not inconsistent with the
declslons made 1n the design of the semantics of the data sËructures
aspect of ACL, since l-t ls stfll possible for Èhe desfgn of the other
aspects of the proposed factltty to preclude the user program havlng
access to more than one reference to an lnstance (whtch ls
effectively the same as havfng lnstance variables).

33
Instead of the single recelver variable of Stanton's model, the
sequence control model regards each Ínstance as havlng tkTo ínstance
reference variables. These are the "mastertt variable' whlch fs used Èo
record statically-derived relat.lonships between lnsEances, and the
rtcallertt varlable, which 1s used to record dynanlcally-derived
relatlonships. In addltion, the ldentlfler t'currenttt can be used in
descrl-pËlons of sequence control features to obtain a reference to the
eurrenÈly executlng lnsËance. Consequently, Stanton's thlrd primltlve is
not Lncluded tn Èhe sequence control model, iÈs effect being obtained by
eLther ttattt"a. current.mastertr or tt=ttat current.callerrr, dependlng on
circumstances. The familiarttdoÈtt noÈaElon 1s used, as shown, to refer
to attrLbutes of instances.
As will be discussed in detall in Sectlon 4.3.L.2, storage
management. is elose1-y related to data control, and hence is of little
interest here; since Stant.on's fourth primitlve is purely concerned ¡vith
storage management, it ís not lncluded in the sequence control model.
Although, the ""r""grt' primitive is also related to sÈorage management
evengs, lt has effect.s whlch are of interest in rnaklng comparlsons
between the sequence control effects of varlous features: iÈ
rrestabllshesrr (but does not necessarily al1ocaÈe storage for) a nelv
instance of a definltlon, and it sets the conËlnuatlon polnt of that
l'nstance to the beglnning of lts definlti-on.

Unlike Stanton, who uses the primitlves described above dlrectly as


programmlng language feaÈures to fllustrate coroutines and Eo lnformally
dlscuss the differences beËween corouÈlnes, generators and procedures '
the prírniÈlves of the sequence control model vrill be used ln
tralgorithmlc" descrlptlons of sequence conËrol features. These
descrlptlons will consist of sequences of actions wfth the following
form:
tt (
(1) each descripLfon w111 be dellmited by curly brackeEs )",
(2) the actions comprisLng a slngle descrlptlon w111 be separated
from each other by semicolons ";tt,
tl ll
(3) actlons wflI be grouped Eogether using square brackets
where such groupfng ls necessary,

(4) Ëhe condítlonal and repeË1tlve statements' and the loglcal and

34
relatlonal operators, of Pascal r¡111 be used in obvfous ways Èo
express declsion structures \illthln descrlptlons (keywords w111 be
1n lower case letlers and underllned, sinllar to the prlmiËlves
described above) ' and

(5) the synbol rr<-rr will be used to denote assignment'


These algorlËhnLc descriptlons can be regarded as the texts of
macros, to be expanded wherever the name (and argumenËs) of Èhe deflned
operation occur. Occaslonally, the need ¡.rill arlse for variables local
to a descriptlon; raÈher than declare local varlable idenËifiers at the
time, Èhe identifierstrArr, trBrr, ttJtt and ttstt are the only ones to be used
for such local varlables, and they wfll only be used for this purpose'
Thelr tttypestt can easlly be deduced from context. As noted above, the
Ldentif ier rrcurrentrr has a specJ-al meaning 1n sequence control
descrlptions.
In addltion to ttcreatett and tt@tt, the Sequence control model
also contains the prlmltlve

return x : this causes the value of rrxrr to be irnmediatelv


reËurned as the value of the seguence control descriptlon in
r¿hfch tt appears, and causes thls value to be asslgned Lnto an
lnstance (reference) variable, if such asslgnmenÈ {s appropriate;
executlon Èhen contlnues wfthin the sequence conÈrol descripÈion,
at the point after the "r"t.tro xt'. At most one t'@tt primitive
wtll be encountered ln the evaluatlon of a sequence control
descriptlon.

To lllustra¡e the use of Èhe sequence control model in descrlblng


sequence control features aE Èhe subprogram level, the defÍnltions of
the most famlliar sequence control features at Ëhis level, the procedure
call and return operatlons, are' respecÈlvely:
PCd = { A+creaEe d; A.callerêcurrenE; enter A }
PR = { enÈer current.caller }
where rtdrt is the name of a procedure deflnltlon.

The second of these operations 1s an example of an 'rundirected


transfer operatlon'r, ln Èhat the fnstance Ëo which control ls to be
rrۊ&Jr
passe,d is not spee if ied as an argument to the operatlon; the

35
operatlon of Stant,on's model ls another example of an undl-rected
transfer operatlon.
Clearly, thls roodel is considerably nore formal than that used in
the desfgn of the FemanÈlcs of the data structures asPect; Èhis reflects
the greater diverslty of sequence conErol features in the coroutlne
facilittes to be compared, and Lhe greater number and complexlty of the
decislons to be made 1n the design of thls aspect'

As well as the primltives already presented, whlch are the baslc


ones of the model, other primitlves wlll be inÈroduced as they are
needed to descrlbe various coroutlne facllities. Descriptions uslng the
sequence control uodel r.¡ill not cont.ain any error detectfon, slnce thls
vrould only cloud the essential part of such a descriptlon: sequence
conErol aÈ the subProgram level.

4.2.3 Seouence Control ln Previous Coroutl-ne FaciliË1es

Sluula

The sequence control features of Slmula's corout.lne facllfty w111

be described in some detal-l slnce:


. Sl-mula |s perhaps the best-known programmLng language r^rlth a
coroutlne facllitY'
. thls coroutine facllity conLalns examples of most of the sequence
control feaÈures of lnteresÈt
. 1t has been used as the basis of a number of other language
deslgns, and

. it has been described 1n a number of quf-te different ways, and the


sequence control model can be used to reveal these differences.

Thls section will demonstrate how the sequence control model can be
used to descrfbe succinctly the coroutine factlity of an exlstlng
language, and wlll indicate how some prevlous descrfptíons of the
trclass" facility of Sirnrla have been misleadlngly naive' Those
propertles of the SÍmula facility whlch hlnder Ëhe writing of simple.'
clear coroutlne programs axe tdentified once an lndlcatlon of its true
nat-ure ls given.

36
A very slmple deseriptlon of sequence conÈrol ln Slnula is given by
StanÈon ln 11431: tt 1s that a Sinula class may behave as a coroutlne or
as a generator, dependlng on whether lt is enÈered Vla a ttresumett or a
trcalltt, respectively.

A less sfmple description, conslstent \rfÈh SËanton's, ls given by


Dahl and Hoare L321, which is nevertheless a símpllfled version of the
true story. It describes a discipllne on the use of the Simula
primltives (for exampler oD the order in r¿hich they are used) to
establÍsh a Ër¡o-level hierarchy in which the difference betr¿een the
levels represenÈs semieoroutlne relationshi-ps (which are relationships
betr¡een generaÈors and thelr callers), and the instanees withln a so-
called ttgrouptt at the sane level are relaÈed as coroutines. Dahl and
Hoare describe the effect of a ttdeÈacht' as passing control back to the
origlnal ca11er, as is the effect of reaching the rrg|rr of a elass
lnstance. The semlcoroutine relationshlps between fnstances on dlfferent
levels are establlshed by t'calltt, and transfers between coroutlnes aE
the same leve1 are achelved using ttresunett. Following Dahl and lloare's
descripÈion, a similar verslon of sequence control in Slmula was
described by the author ln [100], ln r¿hlch these eoroutlne/semfcorouÈ1ne
dynamlc hierarchíes r.rere extended to nultiple levels. An example of
these hierarchies ls deplcted ln Figure 4.1, whlch is reproduced from
,t 1001 .

passes through
call(b) ttendtt

resume (c)
call (d) detach

resune (e)

Flsure 4.1 An Example of a Dynanlc HierarchY


hierarchies are dynamic in nature because Èhey are seË uP by
These
occurrences of ttcallttand ttresumet'aÈ run-tlme; 1n fact, iÈ may be Èhat
the corresponding program text glves no lndicaElon of the dynanic
hferarchies which wfll be set uP aÈ run-time. For example, Ëhe text
corresponding to the hierarchy ln Figure 4.1 1s glven 1n Flgure 4.2
(also frorn t1001).

37
begln
ref(A) a; ref(B) b; ref(C) c; ref(D) d; ref(E) e;
class A; begln detach; call(b); ... call(b); ... end;
class B; beeln detachi ..o resune(c); ... resume(c); ... end;
class C; begin detach; ... detach; ... call(d); ... end;
class D; begl-n detach; ... resume(e); ... end;
class E; begin detach; . .. detach; . .. end;
a:- neÍI A; b:- nerv B; c:- new C; d:- new D; e:- new E;
resume(a)
end;

Flgure 4.2 The Simula Text Corresponding to the Dynamic Hlerarchy


of FÍgure 4.1
However, Babclcky has slnce pointed ouÈ[7] that the above
descrlpËíon 1s ínconsistent with the definltlon of Sinula, and that the
hl-erarchy of Figure 4.I would not result from Èhe executlon of the
p rogram f ragment of Fi-gure 4 .2; in f act , the second
ttdetachtt in the
definition of rrCrr would transfer control to the nearest textually
enclosing prefixed block (gt the main program' if there were no
t,extually enclosing prefixed blocks). The lmpression glven by Dahl and
Hoare that a "resume" in a Simula class insÈance called using "calltt
p_asses on the obligatlon to return to the orlginal- caller, Ís simply noE
correct. The precÍse differences between Dahl and tloarets descripÈ1on of
Sfmula, and Lhe actual case, will be htghlighted by the later
descrlption of 2.PAK tn terms of the sequence conErol model, sínce this
latter language was based on Dahl and Hoarets descrlPtion.
An lndicaÈion of the true nature of sequence conÈrol 1n Sirnula ls
norr given. Ttre deflnltlons belor¿ are derlved from those of Dahl et
al.t33]; ln this latter document, the sequence control PrlmlElve "ca1l"
1s noÈ regarded as part of Sirnula. However, since ft has been lncluded
fn the discussions of Símula's sequence control mentloned above' ft will
also be discussed here; for this purpose, the definition of ttcalltt and
the nodÍfl-ed deflnltion of t'detachtrgiven Ín a t'ecoûlûlendatfon of the
Sinula Development Grouptl36l (expllcated by Babcicky ln [8]) is used.

The creatlon of a class lnstance is accomplished by an expression


evaluaËing to an lnstance reference, involving the operaÈor t"ltt". This
creates aû insÈancen evaluates and traûsmlts any parameters (of no

3B
lnterest 1n thts sectlon), and control enters the instance at its
beglnning. Ilrrlng the ensulng lnltlalLzatlon phase, the lnstance ls said
to be executÍng in the 'faÈtached'r gtate. The evaluatlon of the creating
expresslon is completed when elÈher a ttdetach" Ís executed by the
lnstance, or the instance reaches lts "@tt; fn the former case' the
lnstance ls now l-n a 'rdetachedrr state, and ln the latËer r lt is
ttterminaÈedrt. To record the state of a class lnstance' a new varlable ls
defined for each such instance, called 'rstate'r; thls varíable can take
trdetachedrr and tttermlnatedtt.
On any of the Values trattaChedtt,

In the descriptlon of Simula using the sequence conËrol nodelr Èhe


master variable of an lnstance Ls used to record an importanÈ
staÈically-derlved relatl-onship: that beÈvreen an lnstance and the 'rmain
programtt of Èhe t'quasl-parallel systemt' to whlch lt belongs. For the
purposes of thl-s discussion, lt is only necessary to know that the main
program correspondíng to a class lnstance is an instance of the nearest
textually encloslng prefixed block (sinilar to an Algol anon)rmous block,
but one r,rhlch is pref ixed by a class ldentif ler), and hence thi-s is a
statlc property. (SecÈlon 9.2 of t33l glves a preclse deflnitlon of
quasi-paralle1 systems, and Johnson's descrlpÈ1on of. the run-time
behaviour of Sinula programs[76] contains an accurate' but more readily
comprehenslble, descriptlon of thls and relaËed aspects of Simula.) For
the purposes of descrÍbing Slmula, the sequence conÈro1 model is
augmented by the inclusion of the primltive "maln(i)
t', which evaluates
to a reference to the main program of the quasl-parallel system to which
the lnstance rrirr belongs.
The above relatlonshlp ls recorded by seÈting the approprlate value
fn the master variable of a class lnstance aÈ Èhe time that lt 1s
created (iÈ remains the same throughout the lffetlme of the lnsÈance).
On the other hand, the caller varÍable of a class lnstance ls used to
lndlcate the instance to whlch lt is "aLtachedr', using Slmula
termlnology; 1n the case of a newly created lnstance, it is attached Lo
the lnstance whLch created lt.
The descriptlon of lnsEance creation, ln terms of the sequence
control model, 1s as follo¡¡s:
new d = { A+g!eate. d; A.master ênain(A); A.caller <-current;
A.stateêaÈtached; enter A; return A )

39
Control wfll return to thts definltlon, at the süatement after rrenter
Att, when Èhe inltlallzaElon phase of the creaÈed lnstance fs complete
(regardlng the execution of "nel¡ dtt as a macro expansion 1n the objecÈ
Ln whlch 1t occurs), because of the effect of 'rdeEachr', as explained
below. A reference to the newly-created instance will then be returned,
as the value of the expresslon ttnew d".
Theeffect of a I'detachrr in an attached instance is to cause the
lnstance to become detached and control enters the instance to whl-ch
this one is attached, given by lts caller varlab1e. This covers not only
the case of creatíon, buÈ also Èhe case where an lnstance is ttcall"ed,
thts latter prlniËive being descrlbed later. If the instance is a
detached componenÈ of a quasl-parallel system' tt is suspended and
control returns to the main program of this quasl-parallel system' as
lndicaËed by its master variable. In Eerms of the model, Èhe effect of a
t'detachtt is:

detach = { lf currenL.state=attached
then I current.state+detached; enter current'caller ]
else enÈer current.master )
Frornthis definÍ-tlon, it ís clear that the "statett of an lnstance
acts as a swftch determinlng whether a "detach" causes conÈrol to pass
t-o thaÈ lnstancets rrmastertr or 1ts ttcallertt.

The sequence conÈrol prlmitiVe ttresumett haS A parameter, Say rrftrt


whlch refers to a detached instance whlch is a component of a quasi-
parallel syst.em. This prlmftive causes conErol to leave Èhe eurrently
executlng insEance, which becomes suspended¡ and Èo enter t,he lnstance
lndicaËed by "1". This can be simply descrlbed as:

resune(f)={enterl}
The primltlvettcall" also has a parameter, say ttit', referring to a
detached instance whlch Ís a componenÈ of a quasl-parallel system. Thls
primLÈlve causes the lnstance indlcated by "Í" to become attaehed to Ehe
instance contaínlng Ehe t'calltt (not.ice the slmllarity Eo the
lnitiallzation phase during lnstance creatlon), control enters the
Lns¡ance referred to by "1tt, and thls lnstance continues execution. In
terms of the model, thls ls:

40
calt(1) = { 1.callerêcurrent; l.stateêattached; enter i }
The effect of reachlng the "endtt of a class lnstance 1s the same as

the effecL of a "detach", except thaL the lnstance always becomes

terninated:

class-end = { S + current.state; currenÈ.staEe <- terminated;


if S=attached then enter current'caller
el-se enter current.master )

The sequence control effect of procedure call and return ln SLmula


is the same as Èhe previous, general definiÈlons of these operations;
these same definltlons also apply Ëo anon)¡mous block entry and exit,
lncluding that of prefixed blocks.

There remaln two areas in which Èhe precedlng description of


sequence control 1n Simula is nalve:

. procedure lnstances (and those of anonlrmous blocks, including those


of prefixed blocks) form stacks whlch are associated with the
nearest class or prefixed block fnsËance to r.shlch Ehey are linked
vl-a a chain of caller llnks (a ttcaller chain"), and

one of (class lnstances) comprlsing a quasf-parallel


Ehe components
system, or the maln program of the system, ls dlstlnguished as
belng actlve at any one tlme.

$Ihen conslderatlon of these is added to the descriptlon of Simula'


that descriptlon becomes consLderably more conplicated' A bríef
lndfcaÈlon of thaÈ added complexiËy will now be gfven, largely derived
f rom Johnson's descrlptionl76]. I^Ihen "enler 1" ls executed (sayr as the
result of trresume(f ) tt), where rrlrr ref ers to a class lnsÈance' one parÈ
of the tree deflned by caller and master llnks (1n whlch preflxed blocks
form multl-way nodes, and other lnstances corresPond to one-way nodes)
becomes suspended, and another Part of thls tree gains control' To
illustrate the way in which these "parts" are defined, consider Figure
4.3, in r¿hlch the stralght solid arro\^rs represent masËer links, the
straight dashed ones caller links, and the curved solid ones are used to
fndlcate the active component of a quasi-parallel system; the "Citt are
class instances, the ttPltt procedure lnstances, and the ttPBitt instances
of prefixed blocks. All class lnstances in Figure 4.3 are assumed to be

41
l-n the t'detached" state, and hence thelr caller 1lnks are not depicted
(since these have no meaningful values ln that case).

P P
I 3

P
2

Figure 4.3 The Tree of Instances in an Executlng


Slmula Program

Now, an rrenter C1'r (say, as a resulÈ of ttresuue(C1)tt) occurrlng ln


ttP3tt (r¿hich 1s the currently execut.lng lnstance fn Ffgure 4.3) causes
'
suspenslon of the sub-Èree wlth "CZ" as l-Ès root' sLnce Èhe target
(ttCltt) and ttC2tt share a conmon main program (rrPB1"), and the resumption
of the sub-tree rvith "Cltt as it.s root. To flnd the lnstance Èo which
control 1s actually transferred (whlch 1s necessary slnee ttC ltt has lts
owTt infrastructure), Èhe stack assoclaËed with "Cltt is traversed, and
the acÈlve branches of any prefixed blocks are followed, untÍl the
traversal cannot be contlnued; ln this wElY, the lnstance "Pltt is
l-dentlfled as Ehat to whlch control is actually transferred. All thls 1s
acconplished by changing Èhe acElve component of "P81" from "CZt' to
ttCltt, and so executlon wlll cont.lnue withtn ttP3t' when next "CZ" ls
entered. If a prefixed block is entered (say, because of a t'detachtt ln a
detached instance), the block ltself becomes the actlve component' and
the pref txed bl-ock's otJn stack, 1f there ls one, is traversed to f lnd

42
the lnstance to whlch control is transferred, 1n a manner slmllar to the
one descrlbed above; slnce the preflxed block 1s no\ü the acÈive
component of fts quasi-parallel system' a sub-tree whose rooE ls a
componenL of this system nohr becomes suspended. A
ttdetachtt from ¡vithin
an attached class lnst.ance (or a procedure on its assoclated stack)
causes the tnsÈance to beco¡ne suspended and the lnsÈance lndicaÈed by
lts caller varlable, which may be an instance of any kind, to be
entered.

Ihe behavlour described above for Simula quasi-parallel systems


bears some símllarLÈy Ëo the descriptlon of the intended effect of
enÈering a caterval subprogram, as glven ln Chapter 2, and the nature of
these similarities, and some differences, w111 becone more apParent when
a detalled descripÈlon of sequence control 1n ACL 1s glven later.
Neverthelessr lt is worth noLing at this poinÈ that a quasi-parallel
sysÈem ls a group of corout,ines, but thaÈ Eo obtain the effect of a
group iÈself actlng as a coroutfne, ít ls necessary to embed the (class)
declarations of Èhe members of the group ln a preflxed block withln lts
block; when thls ls done, there is always a prefixed block "lntervening"
betr¿een the caterval coroutlne and lts members, such as in the case of
the class Ínstance "C2" and its merobers "C4rr and "C5tt 1n Figute 4.3.

. It would be posslble to enhance the sequence control model to also


provlde a precise descrlption of the above aspecËs of SÍmula; however,
thls will need to be done, in any caser to enable the description of
sequence control in ACL, and Èhe two seEs of enhancemenEs are not
compaÈible. The lnformal description of Ëhese asPects, given above, w111
sufflce for the purposes of the comparlsons ruhLch are to be made.
Taken as a whole, the formal descrlptions of SÍnulats sequence
control operations demonstraEe how Sinula classes may behave as
coroutines or as generators, depending on the value of thelr state
variables:

lf an lnstance's sÈate is I'at.tachedtt, it is behaving as a generator


(it rùill return to lts caller on the executlon of a'rdeEach'r),

1f the süate of an instance is "detached'r, it is behaving as a


coroutine (1t rnay be "resume"d by another lnstance' and tt would
transfer l-o the naln Program of lts quasi-parallel system on a

43
trdetachtt), and

tf its state lg "terminated'r, the lnsEance is behavlng as nelther a

coroutine or a generator.

Further, a class instance may act as both a coroutine and a


generator in íts llfetlne; this fact is one of the aspects of Sirnula
whfch results in a very poor correspondence between the statlc and
dynarul-c structures of some Simula programs, as already noted w1Ëh regard
to the dynamic hierarchies of Dahl and Hoare.

Another problern with using Simula for wrÍtlng coroutiue programs ls


the way in which initlallzation is handled. Ttre inltiallzaÈion of class
lnstances Ís unsatisfactory ín tr¿o ways:
(f) the first "detach" (dynaulcally) encountered ín an lnstance has a
dlfferen! effecÈ frorn all other such occurrences' 1n thaE 1t
signals Èhe conpletlon of the creatlon of the instance and causes
a reference to Èhe insÈance to become the value of the "neqtt
expressl-on, and

(1i) arbltrarlly complex processíng is posslble in the lnltiallzatlon


phase (which may l"nclude almosÈ Èhe entire execution of the
progran) before a reference to the lnstance has been returned.

The first of these 1s often a naJor factor ln obscuring the


relatLonship between the staËlc and dynamic structures of a Slnula
program: any dtfflculty in declding whlch of Ëhe "detach"s fn a class
deflnLtlon ls the one which termlnaLes l-nftíalizatlon (especlally 1f
this ls not always the same one) serves Eo complícate thls relatl-onshlp
and to make the program harder to understand. One dlsclpline on Slmula
prograrnming which overcomes thls dlfficulty is to ensure that the firsÈ
textual 'rdeÈach" 1s also always t.he first dynamically encountered - ln
thls case, the text ahead of thls flrst "detach" is the initializaËlon
sectlon of that class definition.
The second aspect of class lnlÈiallzaÈton listed above ls a mlxed
blesslng: StanEontl43l sees a general need for lnitlalLzatíon processing
of arbitrary complexlty in classes, and ÍC can certainly give rlse Èo
eleganÈ programs, such as the syntax analyser example descrlbed by Dahl
and lloare l32l , 1n whlch the more-or-less equivalenË acEion of "new" and

44
"ca11" is used to good effect slnce no dlstincË1on is made beÈween the
flrst ttdetach" encountered dynamically, and subsequent ones. Although
elegant once flnally understood, the operaÈion of this program is
difflcult to deduce and equally difflcult to descrlbe; ParÈ of thls
difficulty ls due to Èhe fact that some of the ltnks ln Èhe parse tree
generated during the computaÈion are expllclt, fnstance reference
variabl-e lÍnks, whereas others are "attached Èorr llnks implfclt 1n the
computatlon before references to the corresponding lnstances have been
returned (since ttlnitiallzationrr is noË yet complete) - Thus it ls clear
that part of the dlfftculty arislng fron (1i) 1s, Ln fact, due to (r);
however, even 1f the difficulty ln (f) Itere overcome' clearer programs
would probably result fron restrictlng the kinds of transfers of conÈrol
out of an lnstance during lnltiallzatlon.
Various other coroutlne facl-litfes will now be descrlbed using the
sequence conÈrol model, but ln less depth Èhan was the case 1n the
precedlng deseripEfon of Sfmula.

Gentleman 's Portable Coroutlne SYstem

The portable coroutine system of Gentleman[49'51], whlch is an


extenslon of ANSI Standard FORTRAN and was implemented as a Preprocessor
t-o FORTRAN, provides sequence control- features which are símflar to
those of Sinula, except that the conplicatlons of the full class
mechanlsm are absent. Instances ("coplestt) of coroutines are created by
usl-ng the coroutlne's name (posslbly followed by an lnitialization
parameÈer l1st) as if it were a logical function:

d = { 1f cancreate then I NEWCPY<-create d; reEurn true ]

else return false )


fn r+hich t'cancreaÈe" is a prirnitive whlch lndícates whether or not an
insÈance can be established; a typical reason for this not being
possible fs insufficlent sLorage being available for the lnsEance. The
reference to the new instance (1ts "copynamet') ls returned via the first
location ln a common block labelled "K2COM", this locatlon being kuown
as "NEI^ICPY". ( Sone accounts of thts system [50 r 5 1] describe a 'CREATETI
statement, but the user manualt4gl and the lmplemenÈatlon sent to Ehe
author both use the forn shown above.)

45
The two ma|n sequence control operaÈions 1n Gentlematl's system are:
I = ( l.caller <-current; enter f
INVOKE )
RESUMEi=(enreri)
Ln which rrfrr ls a reference to (that 1s, the copyname of) a coroutlne
lnstance. These operaÈions elearly corresPond to Simula's ttcall" and
t'resumett, respectfvely. Ttrere is no primltlve operation correspondlng to
ttdetachtt, buË the caller aEtrlbute of an fnstance is expllcÍtly
available r.rlthin that instancer âs the coPyname varlable "CALLER";
hence, the effect of a'rdetachtt can be achleved by ||RESUME CALLERIT.

As tt 1s an extenslon of I'ORTRAN, Gentleman's system also allor¿s


subrouglnes. It |s difficult to deflne the sequence control effect of
FORTRAN subroutine call and return using the sequence conËrol model;
thls Ls primartly because the definlEion of ANSI SËandard FORTRANI3]
does not deal ln the concepts of lnstances and deflnltions. IÈ ls thus
not made clear r¿hether a fresh lnstance of a subroutlne is created on
each call, or whether the same instance Is re-used (multiple co-exlsÈlng
lnstances of subrouÈlnes are not posslble); 1t 1s, however, made quite
clear that the contlnuatlon polnt of the lnstance ls set to indicate the
beginnlng of the subroutlne on each call. The followlng deflnitions are
consistenÈ with most FORTRÂN inplementaËlons :

CALL 1= { reset(l)i i.callerêcurrent; enter i }


RETURN = { ente! current.caller }

rri-rl
where rrreseE(1)tr simply seÈ.s the continuaÈlon poinÈ of the lnsÈance
to lndicate the flrst (executable) sËatement in the correspondi-ng
deflnition. In these definlti-ons, it is assuned Èhat one lnsEance of
every subroutine definitlon (with the same name as the subroutlne
deflnltion) is created prior to the commencement of Program execution.

CorouLÍne PASCAL

Coroutine PASCALI9I,92] is the result of the addition of a Slmula-


Like coroutl-ne faclliEy to Pascal. The deflnltion of this facllity'
presented ln terms of the Control Definitlon and ImplementaÈion Language
(QDIL), is based on wang and Dahl's descriptfon[152] of a set of
prlmÍtlves ttresetnbllng" those of Slmula. Wang and Dahl's model, which
does not address |Èself to Èhe complexlties of quasl-parallel systems'

46
regards executing programs as conslsting of cycles of lnstances' all but
one of whl-ch are suspended; the actlve cycle, called the 'roperatlng
chaln'r, Ls the one which conËaLns the main program and the ttprocessor"
(the execut.l-on envlronmenÈ of the entlre program). The varlous coroutine
sequencing prinltlves are then regarded as having the effect of deleting
eycles from, and/or addlng cycles to, the operating chain'
Following llang and Dahl's model, Coroutlne PASCAL does not have the
concepÈ of quasi-parallel systems, nor of any statlcally-defined
sequence control relatlonships beÈween lnstances. I{hen describing its
features with the sequence cont.rol model, the ttcallertt at.tribute of an
instance w111 be used to record Ëhe slngle dynanlcally-defined
relatlonshÍp between lnstances. There ls no staEic distlnctlon between
coroutines and procedures ln Coroutine PASCAL, thls being a dynamic
dlstinction determined by the "sËatusrt of an instance. The staEus of an
Lnstance is always one of the followÍng:

ACTP - actlve procedure lnstance


ACTC - active coroutlne lnstance
SÀC - suspended, but. activatable, coroutlne instance
SNAC - suspended, but not actfvatable, coroutine lnstance
TRM - terminated corouË1ne instance

In general, cycles other than the operatlng chaln have an instance


at thefr head with status rrSACrt and are otherwise composed of lnstances
with sÈatus ttSNACtt or ttACTPtt; the operating chaln conslsts of lnstances
wlth status I'ACTC'| or rrACTPrt. Figure 4.4 depiets some ËyPfcal cycles of
lnstances, and the status of each Lnstance ln the cycle. Ttre flrst cycle
fs an operaLlng chaln; in the present descrl-ptton, the status of both
the maín program and the processor w111 be regarded as rrACTCrr, which J-s
not the case ln Ehe CDIL descriptlon (where Èhey are treated as specíal
instances). Not,lce that "currenÈ" in the sequence control nodel
colncldes with the lnstance Índicated by the call-er attribute of Èhe
processor. The other t¡,ro cycl-es in Flgure 4.4 rePresent suspended sets
of lnstances.

47
ACTP ACTC ACTP ACTC ACTC

main program processor

SAC

SNAC ACTP SNAC SAC

Flsure 4.4 Sone Typlcal Cycles of Instances in Coroutlne


PASCAL Programs

The sequence control features of Coroutine will now be


PASCAL
fornally described, uslng the sequence control model; in this
descrÍption, each lnstance will have a "staËus'r attribute. The values
ItSACtr, |'TRM" will be set lnto such varlables to preserve the
"SNACrr and
correct pattern ¡.¡lthln cycles, but slnce thelr mafn use 1s the detection
of certafn errors (noÈably, Èrylng to attach a suspended cycle, by a
poLnt other than lts head, to Ëhe operaÈing chaln) ¡ they will not be
used ln the manner of the CDIL descriptlon.

Coroutlne lnsÈances are created by the operation:

CREATE d = { A€-create d; A.staËus<-SAC; A.caller<-A; return A }


NoËfce that the caller attrlbute of a newly-created instance 1s set Ëo
ÍndicaEe the lnstance itself (as ln the second cyele ln Ffgure 4.4) ' and
that ft ls not entere<l for inltlalfzatlon processl-ng. Procedure caIls,
r¿hose syntactlc form ls the same as in Pascal (merely glve the procedure
definltion ldentifler, and possfbly a Parameter l1st), have a sequence
cont,rol effect slmflar to the deflnitlon given prevlously, except Èhat
the status att.ribute of the creaÈed lnsÈance must be set:
d = { A+creaÈe d; A.status <-ACTP; A.caller+current; enter A }

4B
The najor sequence conÈrol operaÈlons of Coroutlne PÀSCAL are the
followfng:

CALLi={Aêi;repeat
Á, +cal1er;
A.
lf A.status l¡.Ctp then A.status <-ACTC
Ps!4 A=l;
A<-t.caller; i.callerêcurrent; enter A )

DETACHi={A<-current;
rvhf le A # i do I if A. status =ACTC then A. status <- SNAC;

A+A.caller l;
L.staËus <- SAC; A + i.caller;
l.callerêcurrent; enÈel A )
RESIIME f = { A+i; repeaÈ
A <- A. caller;
lf A.status +ACTP then A.status <-ACTC
untll A=Íi
A<-current; while A.status lAcTc do A<-A.caller;
B <- i.caller; 1.caller +A.caller;
A.staÈus+SAC; A.caller+current; enEer B )
t'i" are
In the flrsÈ of these, the Lnstances ln the cycle lndicated by
inspected and any coroutine lnstances acqulre the status ttACTCtt; afÈer
this has been done, the cycle fs slmply appended, by the polnt indicaÈed
by "ltt, t.o the end of the operating chain, and the lnsÈance whfch hras aÈ
the ttËalltt of the "CALLrred cycle (glven by tti.callertt before 'TCALL i'r)
ls entered. The second operation descrlbed above Ís a ttmulËi-level" form
of Slmula's "detach" (also, fndependently, suggested by R¿ulefstI25I);
rritr and
tÈ sl-nply breaks the operatlng chain between the instances
tri.callertt, the former becomlng the head of a nerr suspended cycle and
the latter galnlng control. The lnstance t'Ítt, whlch musË have status
IIACTC" bef ore
"DETACH i", has l-ts sEatus changed to rrSACrr; any other
fnstances on the ne\,ù suspended cycle r¿hlch are actlng as coroutines have
their status changed to "SNACT'. In CorouÈine PASCAL' the ldentifier
ttSELFtt refers to the nearest corouË1ne lnstance Èo the currently
executlng insÈance on the operaElng chaln (t'SELFtt indlcates the
currengly executing lnstance 1f lt 1s a corouÈlne lnstance); thus, the
effect of Simula's "detach[ can be obtafned by ITDETACH SELF". The ffnal

49
operation above, TTRESUME", flrstly seÈs the staEus of all coroutine
fnstances on the cycle belng ttRESUME"d to "ACTCrr, and Èhen the nearesÈ
coroutine lnstance to the currently execuÈlng lnstance 1s located (in
fact, a search fs no¡ necessary Ln the actual lnplementatlon' since lt
is recorded in TTSELF'|), this lnstance beeoming the head of a suspended
cycle aft.er its status has been changed to trSACtt, and the head of the
I'RESIJME''d cycle (that is, rrirr) belng appended to the oPeratlng chaÍn;

finally, control is transferred Ëo the tail of this cycle, the lnsÈance


lndicated by tti.callertt.
Instance Èermination (passlng through the ttendtt of a procedure
deffnition) has the following effect:
terminaElon = { if current.status=ACTC currenÈ'status+TRM;
enter currenÈ.caller )

It fs not necessary Ëo alter the status of a terminatlng proeedure


instance since no references to lt exisÈ (except posslbly in the caller
variables of instances before 1t ln the cycle, and there wlll be no such
Lnstances when it ls termlnating). 0n the other hand, Ëhe user Program
conËalns instance reference 'variables and these may be used in an
aËtempt to IICALLTT or I'RESIJME'| a terminated corouÈlne lnstance;
consequenËly, such lnsÈances must be marked as terminated so that such
âtÈenpts can be detected.

2.PAK

The prograruming language 2.PAK' described by Mell{[107'108]' is


ÍnËended primarlly for artificlal lntelligence appllcatlons, and among
its ttglobal control structures'r (sequence control features aÈ the
subprogram level) are coroutlnes. This coroutine faciliËy f-s modelled on
the descrfption of Sinula given by Dahl and Hoare (see earller commenÈs
on thls description, under t'Sfmula").

Instance creaElon is accompllshed by using the coroutlne name as a


trpseudo-functÍon'r which evaluates to a reference Ëo the created
fnstance; its descriptfon in terms of the seguence control model 1s:
d = { A€-create d; A.caller<-current; return A; enter A }
The caller variable of the created Ínstance is used to record a

50
reference to the creaÈor, to enable a reÈurn after lniÈialization
processing. Notice Èhat t.he above descrlpt.lon states that the reference
to the creaÈed lnstance is returned before Èhat tnstance 1s enEered for
Ínl-tialization, unllke Èhe sLtuation in Simula; this is lnplied, but not
clearly stated, by Me1li in [107]. The sequence control operations
lnvoke 1 { 1.caller+current; enter L }
detach = { ent.er current.caller }

resume I { l.caller+current.caller; enter f }

COrreSpond to ttcallt',rrdetachtt and ttresumettr resPectiVely, in Dahl and


Hoare's deserlpElon of Slmula. Note, in partLcular, the way ln which the
above "resume" results in the obltgation to return to a caller (set up
by an lnstance creaÈion or an ttlnvoke" operation) being passed on. The
definltion of procedure call and return (vla an expllclt "return"
staÈement) is the same as the general one glven elsewhere' Ttre
defÍnition of t'detachtt given by Melll 1s thaÈ it reEurns control to the
t'fnvoke"
latest lnstance whlch executed an lnstance creation or an
operatLon; the above defl-nltlons achfeve the same effect, since "resunett
and 'rdetach" operations can only occur 1n coroutlnes. Coroutlne
termlnatÍon has Ëhe saue sequence control effect âs a "detach'l
operaËion.

The above deflnLtLons glve preclsely the sequence conÈrol effect


described for Simula by Èhls author 1n t1001 and they would, for
exanple, result 1n the generatfon of the dynamic hierarchy of Figure 4.1
from a sultably recouched verslon of Figure 4.2. Table 4.L displays,
sfde by side, the sequence control rnodel deflnitlons of eorresponding
operaÈions in Simula and 2.PAK, demqnsErating both the extent to whlch
Dahl and Hoare's descripÈ1on of Simula dlffers from the actual case, and
also the usefulness of the sequence conÈrol model in making comparisons
beÈween coroutine facilities on the basis of sequence control at the
subprogram level.

51
Table 4.1 A Comparison of Sequence Control ln Simula and 2.PAK

Operatlon Simula 2.PAK

lnstance {Aêcreate d; {A+create d;


creaÈLon A.master <-nain(A); A.caller + current;
A.caller <- current; return A; enÈer A)
A. state <- attached;
enÈer A; return A)
ttdetacht' {-Ll current. state = aÈtached {enter current.caller}
then
[current. staÈe + detaehed;
enter current.caller]
else
enÈer current.master)
tlresumett {_."t.f f} {i. cal1er <- currenE.caller;
enter L)
ttcalltt/ {1.caller <- currenÈl {l-.caller + current;
trinvoke" i.state <- attached; enter 1) enter 1)
termlnatlon {S + current.staEe; {gnÈer. current.caller}
currenÈ. staEe + termlnated;
1fS = attached
then enter current.caller
else enter current.master)

SL5

The procedure mechanism of St5 162l enables the formulation of


coroutlnes and generators, as well as normal proeedures. Ïnstances are
established by:
create d = { A+creaËe d; returlr A }

and lnstances created in thls manner may then be used as generators vLa
the palr of operatlons:
resume 1= ( t.caller+current; enter i )

return r = { enter currenÈ.caller }


(in the latter case, rrrrr ls the result returned, and is not of interesË
here). It fs also posslble to transfer to an instance LtiËhout fnplicitly
updating lts caller variable:
returnrtoi={enÈeri}

52
where rrrrr is once agaln the transmitted result. Notlce thaÈ the major
way Ln whlch 1r thls facility dlffers from that of 2.PAK' Èo which ls
slmllar ln nany other respects, ls that the slmmetrlc coroutlne Ëransfer
opera¡lon ttr.È"rn ... to .. .tr does not pass on the obllgatlon Eo return
to a caller (called a ttresumertt in SL5).

In SL5's successor, Icon[58], the posslbllity of a symmetric


transfer between lnstances has been eliminated, resulting in a pure
generator facllity.

Kriee's Co ooeratlons of CoProcedures


ttcoproceduresrr
Krieg[86J descrlbes a scheme for the grouping of
(coroutlnes) Lnto Itcooperatlonstr (groups which themselves behave as
normal procedures); ln this scheme, a cooperatÍon is lnstantlated by
glvfng 1ts definltion identifler, as if 1t were a procedure call in an
Algol-l1ke language:
d { Aêcreate d¡ A.caller+current;
f or J:=1 to n do
I t' ècreate dri ir.master<-A ];
enter A )

Ín which is the deflnitlon ldentlfier of a cooperatl-on conslsting of


rrdrr
rrftrt CopfocedufeS (Whose names Are ttdltt, ttd2tt, . .. , ttdrt'). The actlon
tt3!.a4 d" establishes an lnstance of the body of the cooperaÈion, and
its caller varlable l-s used to record Èhe (dynamlc) relatlonship beÈween
the cooperatÍon and Èhe insËance calling it. There is a single fnstance
establl-shed of each of Ehe coprocedure deflnitlons, and these instances
are referred to by the corresponding deflnítlon ldentlfier. The
(statlcally deterrnlned) relationshlp between each coprocedure instance
and the body of the cooperation fs recorded 1n the master variables of
the coprocedure instances. Ilpon Èhe creatíon of all of the coprocedure
lnstances, the body of the eooperation is entered; thls body will
contaln a ttglarq" statement passlng control to one of the coprocedure
lnstances:

starEi={enterÍ}

53
Control is passed among the varlous coprocedure lnstances through
the use of the following statemenÈ:
srüapf={enteri}

and control may reËurn to the bodY of the cooperatlon through the
executlon of a rrreturntf statemenÈ (or through the LermlnaÈion of a
coprocedure, whlch has the sane efflct):

relurn = { ent-e! current.master }

On the other hand, the terminatlon of the body of a cooperatlon


causes the entl-re cooperaÈlon Èo Lermlnate:

body_end = { enter current.caller }

which l-s ldentical to the effect of a procedure reLurn, slnce no


reference to Ehe cooperaÈion lnstance exlsts, and a new one will be
created if that cooperation 1s again called.

Pritchard's Pools of Coroutlnes


The "multiple corouÈine systemrr for which Prltchardtl23l PresenÈs a
proof rule 1s the ttpooltt, which ls lnstantiated through the "4!!y4tt'
staÈement:

actlvate d = { Aêcreate d; A.caller<-current;


f or J:=1 !g n do
[ 1J<-creaËe d¡; t¡.caller+current ];
enter A; enter 11 )
1n whlch t'S@ d" establishes an insEance representing the
ttlnftiall-zation statemenÈ" of the pool. As with Krleg's scheme' one
l-nstance of each of the rrnrr def lniËlons ln the pool is created (once
agaln the definltlon names are also used as instance names), and then
control ls passed to the tnltlalization statement. trühen conÈrol returns
from this staËement, the lnstance corresponding to the coroutíne
deflniEion whlch appears texÈuaIly flrst ls entered. Control is
transferred among the corouËines of a pool uslng:
resumei={enteri}
and terminatlon of a coroutine instance (or of the lnltiallzation

s4
statement) has the follorrlng effect:

termlnation = ( enÈer current.caller )

whlch ln the case of a coroutÍne causes Ehe return of control to the


pol-nt af ter the """9.1v"!g'r statement whtch lnstantiated Èhis poo1,
effectively resulË1ng in the disappearance of the pool (sLnce no
reference to 1t exists). It ls thus clear that thls kind of grouP of
corouËlnes also behaves l1ke a procedure, and that a new instance of Ëhe
pool is created on each occasion that lt 1s called.

Saianíeml's Cogroups

Slnilar ln many respects to lhe two preceding proposals for Ehe


groupl-ng of coroutlnes 1s Sajaniemi's descripÈ1on of t'cogroupsr'[130].
The creatlon of a cogroup insÈance ls achleved by gl-vlng lts deflnitlon
ldenElfier, as wlth Krteg's cooperations:
d={forJ:=1 tondo
I I t <- create d r; I r. caller + currenÈ ] ;
enter i^ù-)
From thls deftnition, tt is clear thaË cogroups do not have bodles or
lnLtlalLzatlon statements, although each cogrouP does have a I'start
'notlcerr indicating whlch of the rrnrr coroutine lnstances is to gal-n
control lntÈ1ally (this lnstance ls denoted t'i"" above); once agaÍn a
single lnstance of each corouÈine deflnition Ís funpllcitly establl-shed
when the group of corouËines ls created, and each fnst.ance is known by
tts definition identifier.
Transfers betrveen coroutine insÈances fn a cogroup occur by
executlng â statemenE consfsting sinply of Ëhe lnstance name (that ls,
the corresponding definition ldentifier) :
1={enteri}
Coroutlne termlnatlon causes the termlnation of the entire cogroup
to which Ít belongs, and conErol 1s returned to the polnt aÈ whÍch the
cogroup was lnstantfated:

termlnatlon = { enter currenÈ.caller }

whÍch 1s l-denÈícal to the effect of the same occurrence 1n the scheme

55
descrlbed by Pritchard and, once agaln' means that the grouP of
coroutines behaves as a Procedure.
Another slmllarity between the above three schemes is that the only
means of Ëransferring control among the members of the grouP is a sfunple
coroutine transfer, there belng no provlsÍon made for the establishment
of a generaÈor regime

Alphard and CLU

Both of these languages conÈaln a generaÈor facllity which is


provlded solely as a means of allowlng ttfor" statements to lt.erate over
more general sequences of values than is usually the case. The creation
of an lnstance of the generator, and calling on it for successive
values, is carried ouË lnpllcttly by Èhe code lmplementÍng the loop. The
fmplicít operatlon to create an instance of an "iteratortt in CLU[97] and
then t.o pass control to 1t for Ëhe production of the ffrst value, could
be regarded as having the followlng sequence control effect:

lnitlalize d = { A+create d; A.caller<-current;


ènÈer A; return A )

Subsequent values are lhen obtained by an operation of the form:


nexÈi={enteri}
1n whl-ch the instance name rritr can be regarded as Èhe same as the
ttvfeldtt
iteraÈor's deflnition name rrdrr. Iterator defl-niÈions contaln
statements (which also give the value to be returned) at points where
control 1s to reÈurn to the looP:
vl-eld = { enter current.caller }

whereas a t'Elttttt statement (or reaching the end of the lteraÈor's


deffnftlon) terminates both the iterator and the loop for which lt was
produclng values.

The t'generatortt of Alphardtl34l has a slmllar description, excePt


that it has a separate inlttalization section, raÈher than the situation
in CLU, where the flrst occurrence of a "yieldtt during executlon
termlnaÈes inttialization and returns the flrsÈ value (sinllar to the
firstttdetachtt encountered during the executlon of a Simula class

56
lnstance) .

TELOS

TELOS is an artlflclal 1nÈelligence programning language based on


Pascal; both the version of the language described in tl48l and that
presented ln LeBlanc's thesls[89] contaln a coroutlne facility. The
latter version of TELOS will be dlscussed excluslvely here, not only
because 1t ls more recent, but also because of the lack of detall Ln the
description of the sequence conÈrol prlnitlves of the former.
Two of the signifLcant innovaËlons of TELOS ar.e the concept of
ttoverseerstt and the wide use made of tteverltstt. An overseer 1s a specLal
purpose procedure which can be used Èo implement new sequence control
f ac11Ítles and problersolving sÈrategl-es; TELOS fmposes various
restrictíons which prohibit the manlpulation of corouÈine instances
outslde overseers, except for one Partl-cular use of such lnstances'

Coroutlne lnsËances are establfshed using Èhe expresslon:

NewProcesg d = { A<-create d; return A }

and instances created in thfs by a ttContlnuett


manner can then be lnvoked
statement. Such a statemenÈ has a sequence of "event handlers" appended
to Lt (in the "Untll" part of the statement) and one of these w111 gain
control when Èhe lnsLance suspends ltself; r¡hlch evenË handler Ëhis 1s
depends on the event ldenttfier specffied in the "S,t"p"ttdtr event
stalement (see below). Thls makes the ttCotttinn"'r statement very
lnterestlng l-n Eerms of sequence control at the staEement level, but aÈ
the subprogram level lts descripÈlon 1s sinply:
Continue t UnEil ... End = { t.cal1er+current; enter i }

a reference to the Ínstance contalning the above statement being sÈored


fn the called lnstance's caller variable. Sinllar Í-n effecÈ 1s the
overseer call (sl-m1lar syntacË1cally to a procedure call), whlch 1s also
followed by a llst of evenE handlers:

d[* *l = { A<-create d; A.caller<-current; enter A }

where rrdrr ís an overseer deflnition ldentifier.

57
A ttsrsp".tdtt event sEatement ln a coroutlne or overseer lnstance
returns control Eo the appropriate event handler aÈ the polnt of call;
ln terms of the sequence control model, Lts effect ls descrlbed by:
Suspend e = { current.caller.suspender <-current;
enter currenÈ.caller )

ln which tte" ls the event ldenÈifier, whose purpose was explained above.
The LdenÈlty of Èhe instance executlng the above statement is recorded
1n a varlable, called "suspendertt and lntroduced ínto Ehe model for the
descrlption of TELOS, of Ehe l-nsÈance t,o r¿hlch the statement passes
conËro1; thls lnformation nay be used by the standard procedure
ttResumett, whtch has the following effect:

Resume = { enter current.suspender }


and may only be used in an evenL handler; 1t results ln control
returning to the l-nstance which caused that event Eo occur. This
procedure, and the fact that overseers may Íssue suspend events, makes
overseers more than procedures, since an impliclt reference to an
overseer exlsts after it has -returned to its caller via such an event'
and this reference can be used to laÈer resume lts executlon.
Consequently, Èhe faclllty provided by overseers for the grouplng of
c,oroutlne instances is more flexfble than those of Krfeg, Prltchard and
SaJanleml, although an overseer is far from being a coroutine.

TELOS also provldes a t'ForStep" (looplng) construct whlch uses a


coroutine instance (acting as a generator) to provfde values for use 1n
the statement controlled by Ëhe construct, slmilar to Alphard's
generator and CLU's iteracor (the maln difference befng that 1n TELOS
the values are returned to the loop via a reference parameter); a
corouÈine lnstance being used in this way issues a speclal suspend evenÈ
after the productÍon of each new value: rrstepr'.

4,2.4 Sequence Control fn ACL

4.2.4.1 Introduction
The startlng point for the deslgn of the sequence control features
of ACL was the vie¡¡ that procedures, coroutines and generators all
represent dlfferent patterns of sequence control behavlour, and thaL fn

5B
speclfylng a subprogram in a progranlning language, a Programmer should
be able to state which of these behavlours ls exPected. SpecÍfically'
these three klnds of subprograms are Eextually dfstlngufshed from each
other (unltke the sltuatlon ln languages such as SL5 and Coroutine
PASCAL)

The dtfferences between these three kinds of subprogram have


already been discussed 1n Chapter 1; it 1s clear from these dlfferences
that since procedure lnstances are created afresh on each call, they are
more transient obJecÈs than coroutlne and generat.or lnstances, which are
normally re-entered a nurnber of times. Thus, the run-È1me structure of
an ACL program ls regarded as betng largely determlned by the
relatlonships among íts coroutine and generator lnstances, and procedure
instances are regarded as incidental to this structure.

Furthermore, the relatlonshíp among coroutlne and generator


ínstances whích determlnes Èhe structure of a program 1s the grouping of
such instances, based on the notion of a caterval subprogram i-nstance'
r¡hich vras discussed in Chapter 2. CaÈerval lnsEances are themselves
elther coroutine or generator lnstances; because of thelr Pattern of
sequence control behaviour, procedure lnsÈances can form themselves lnËo
chains, but not lnto groups.
All coroutine and generator instances are lnitially elementary;
they may Èhen cacervate (become caterval-) by creaËlng some member
instancesr or by such lnstances being created by an instance of a
procedure defined in that coroutine- or generator (see later). IÞon
catervatlon, the original elementary lnstance becomes a special member
of the group thus created, known as the "boss" of that grouP. As w111 be
discussed shorËly, the prfnclple of opaqueness 1s enforced with respect
to transfers of con¡rol among coroutine and generator instancesr ln Èhat
an lnstance outslde a group must pass conÈrol to the group via Ehe boss
of that group (transfers to other members of Èhe group frorn outside it
are not perrnltted). Thus, 1È is clear that the external ttappearancett of
a coroutlne or generator lnstance does not change through the t.ransitlon
from elementary to caterval; tt ls, in fact' not possible to tell from
the outside r¿heEher such an lnstance is elementary or caterval.

59
The main program lnstance w111 be regarded as a coroutine lnstance
for the purposes of this dlscusslon; 1t 1s elementary If. there are no
coroutlne or generator lnstances creaÈed by the program, but ls caterval
if any such lnsËances exist.
Because of some data control restrlctlons dfscussed later ln thís
chapter, there is a close correspondence between the static nesting of
coroutine and generator definitions in the text of an ACL program' and
the dynanic grouplng established by instances creating other instances.
Slnce grouping 1s a statically-derlved relatlonship, 1t w111 be
represented via master variables in the sequence conÈrol descriptions:
the rnaster variables of the members of a group fndÍcate the boss of Ehe
group.

Just as single coroutlne or generaÈor lnstances must keep track of


thelr internal sËate between befng suspended and subsequently being
reactivated, caterval corouÈfnes and generators must be able to do the
same. As part of the mechanlsn by whlch a group records fts lnternal-
state, one member of any group ts distinguished as belng "active" aÈ any
one tlme. Coroutlne and generaÈor lnstances are regarded as havlng a
varlable named "active'r, and the acËÍve varlable of the boss of a group
fndÍcates Èhe acLl-ve mernber of Ëhat group (which may well be the boss
itself). The active varlable of an lnstance whlch is not the boss of a
group has the value "nil".

4.2.4.2 Extenslons to the Sequence ConLrol Model

Because of lts translent nature, a procedure lnstance 1s regarded


as being Ín some sense subordinaEe t.o the nearest coroutlne or generaÈor
inst,ance to vrhich lt 1s connected through a series of procedure
Lnstances línked by ca1ler 1lnks. Thus, each coroutlne or generator
insÈance has a (possibly empty) sËack of procedure lnstances associated
wlËh tt. Such stacks of lnstances are deplcted ln the followlng manner:

1n whlch Ehe dashed arrolrs represent caller llnks. (In Èhls and other
representations of dynamlc program structure, the "Citt are coroutine
instances, the ttGltt generator lnstances, and the ttPitt procedure
fnsEances; recall that the main progråm lnsÈance Ís regarded as a

60
coroutine lnstance.)
The structure of executlng ACL programs w111 be depicted via
rrmaster treesrr, in whlch the lnstances of the prograB are arranged ln a
tree based on the master llnks among corouÈ1ne and generator lnstances.
In such trees, the master llnks will be depl-cted as stralght solid
arrows, Èhe active lnstance of a grouP wfll be indicated by a curved
solid arrov¡ from the boss of the grouP, and the stack of procedure
lnstances associated wtth a coroutine or generaÈor instanee will be
deplcted as above. (Compare thfs Èree rePresentatlon wlth the
representat,lon of Simula run-Èlme structure 1n Figure 4.3. ) For example,
Ffgure 4.5 depÍcts a master tree qrÍth the caterval coroutl-ne l-nstance
ttCltt as lts rooÈ; notlce that "C2tt is the active member of "C lt', ttC4tt
that of ,rC.rr, and ttG5" thaÈ of t'Ch". Notlce also that lt 1s the boss of
Itcrt' which ls lts actlve member.

Fieure 4.5 An Example of a Master Tree

In vlew of the above Èree structure of programs ln thls language,


ttg@t"
and the subordinate role of procedure lnsÈances, the effect of
w111 no\t be dtscussed tn some detall. Conslder, |n general, the
occurrence of ltenter irtr 1n an lnstance ttl1tt (tn other words, a transf er
from the insLance ttirtt to the instance "i2tt).

If ,rí2,, is a procedure lnstance, then the effect Is merely as


described in Sectlon 4.2.2; in particular, no actlve lÍnks are affected.
However, if "i.t' is a coroutine or generator fnstance, Èhen the effect
lnvolves more than sirnply settlng the conÈlnuation point of
ttil" and

61
lnterrogaË1ng that of "IZttl. 1n general, a set of lnstances becomes
suspended and another set of lnstances becomes acElve' Ehrough the
adJustnenE of active llnks. Si-nce "ir" Ls an insÈance of a coroutlne or
generator, Lt may have some lnfrastructure, and iÈ ls necessary to find
whfch of the lnstances eomposing this lnfrastructure actually galns
control. The lnstance to which control ls acÈually transferred when a
coroutine or generator instance rrirr is entered is referred to as the
ttlivett insËance wfthtn rrltr and is denoted "llve(1)tt; the algorithm for
lts computatlon 1s given l-n Flgure 4.6. In thts algorlthm, "top(i)"
evaluates to a reference to the procedure lnsÈance on top of the stack
assoclated wfth Èhe corouÈ1ne or generator lnstance |tirr (if thls stack
1s empty, a reference to rrltt ítself ls returned). The algorlthm 1s
wrl-tten 1n a notaÈion simllar to Ëhe sequence control model, and the
value of "live(1)t' is the flnal value of Ëhe variable t'l1ve". The
computatlon of which lnstance gains control sinply lnvolves startlng at
the l-nstance rrlrr (which 1s a coroutlne or generator lnstance), and
followLng the actfve links until an elementary lnstance' or a caterval
lnstance l-n nrhlch the boss ls actlve, is encountered; the requlred
lnsÈance ls then that on top of this fnstance's sÈack of procedure
l-nstances (or the lnst.ance ltself , l-f the stack is empty). For example,
the lÍve lnsËance r,rl-thin "Clt' of FLgure 4.5 1s ttP3t', and that within
rrP2rr.
.tlGltt is
lfve + 1;
rshlle (live.actlve#nil) and (live.actl-ve# l1ve) do

lLve <- live.acÈive;


l1ve <- top(live)

Flsure 4.6 The At gorithrn for the Computation of ttllve(i)tt

control is passed to the subÈree whose root ls a coroutine or


I{hen
generaËor fnstance, preclsely one active varlable wfll be affected; in
Èransferrlng control from ttlltt to "Í2" and making the instance "iZ"
become Èhe acÈive member of a group, t.he subtree r.lhose root is some
other member of that group r.¡lll become suspended. This other member will
be denoted "susp(tlr12)tt (that is, the instance suspended when "il"
executes "=g!."t 12"), and FÍgure 4.7 glves Lhe algoriÈhm for lts
computat,lon; in thls algorithm, "head(1)" is a primitive yieldlng a
reference to the coroutine or generaLor lnstance at the head of the

62
stack of procedure instances Ëo whlch ttlttbelongs (tf trlrr is a coroutlne
or generat.or lnstance, 1t yf elds a ref erence to rrlrr itself ) . The
variables "s1tt and tts2" are local Èo the algorithm definitlon.
s1 €head(tt); s2 ês1i
l-f s'LZ=lô.mast.ef
then susp (- sr
else I whlle sl.master # 12.rnaster do
I + s1 i sl ê sl.master ] i
s2
1f s, = i. then gugp ê So
LL

else susp <- sl 1

Flgure 4.7 The À1 gorithrn for the Conputatlon of "susp(i1rt2)"

As mentl-oned earller, the prlnciple of opaqueness 1s enforced with


respect to all transfers of control among instances on the master tree
of an execuËlng ACL progran: an lnstance ttil" rnay only execute "Stt*
I2tt íf elther of "!rt' or rrl2.mastertr is on Èhe master chaln leading from
fthead (tl)tt. In other words, the transf er ls allowed only if "L2t' is a

member of the group wfth "head(tl)" as boss, if the former is an


lnstance on the masEer chafn leadlng from tthead(i1)tt, or lf tt fs a
mernber of a group r,rhose boss is on ÈhaL master chaln. Adherence to the
prl-nclple of opaqueness ls assured by restrictlons on the arguments of
'dtrected transfer operat.ions, and by Èhe deflned behaviour of Ëhe oÈher
sequence control operatlons of ACL.

The algorlthn of Flgure 4.7 firstly locaÈes the corouÈlne or


generaËor instance at the head of the stack to r,¡hich "il" belongs, if
lndeed 'ri1r' ís a procedure lnstance, and stores this reference in "s1".
If this instance is the master of the lnstance "LZt' Èhen thís 1s Ëhe
case of a transfer from a boss lnsÈance to one of lts members;
accordlngly, Ëhe instance to be suspended 1s "srtr. For example, Íf "Gl'r
r,ras active within "Crttln Fígure 4.5, then conÈrol would reside 1n "P2";
now, if tt-enter Crrt were encountered Ín "P2", then the eff ect r¿ould be to
6et rrGr. actlve" to indicate "C3", since ttsusp(P2, C3) tt evaluates Èo a
reference to trGrrt.

If ttL¡tl ls not a member of the group wfth "head(t1)tt as boss, Ehen


(presumlng that the princlple of opaqueness ls being observed) rrl2rr must
either be on the chain of master llnks frou tthead(l1)ttor be a member of

63
a group whose boss Ls on thaÈ master chaln. Ttre "whilerr loop in the
algorlÈhm follows the master chaln out of I'head(11)" unËll an 1nsÈance
(tt"ltt) is found whose master is the same as that of "L2", and also
records the prevfous lnstance on the master chain in t'srtt as the chain
ls followed. When the two master 1lnks coLnclde, Ëhe two cases above can
be separaEed:

1f tf sltr contalns a ref erence to t'it2", then tri2rr is actually on the


chaLn of master links, and the intentlon l-s Ëhat the boss of the
caterval insÈance "LZt' should become lts active member, by
suspending the prevfous instance on this masler chain (that ls,
tt"2,t); f or example, if rrP3rr in Ffgure 4.5 executes 'renter C4rr, then
t'C4', becomes the active component of fts grouP by alËerlng
trC4.activett fron "Gr" (the value of "susp(P3rC4)tt) Ëo 'rc4'l ,

tf. tt"ltt does not refer to tri2rr then these lnstances are dlfferenÈ
members of the same group (their master varlables indicate the same
tnstance), and the subt.ree wlth ""1" as lts root (which contaÍns
ttil,'wiËhin it or associated with lt) becomes suspended; for
example, lf ttP3" in Flgure 4.5 executes t'gg C5t', then Èhe
subtree with t'C4tt as tts roog becomes suspended (s ince
ttsusp (P3, C5
) " has Èhe value
t'C4t') by changing ttC2. acÈlvett f rom
ttc4" to rrc5rr.
,
A degenerate version of the first alternative occurs when "lr" 1s
in fact t'head(il)tt (conslder, for example, the execution of ".tt!tt G5"
wlthln "Prt' in Figure 4.5); ln this case, "susp(11,í2)t'always yields
tti2.master.activetr is changed f rom tti2tt to "ízt' ; 1n oËher
"iz" , and
words, no change ls made to the actlve variables of caterval fnstances.

In the ltght of the preceding discusslon, it ls clear that


descrlptíons of Ëhe sequence control operatlons of ACL, in terms of the
sequence control model, w111 need to make adjustments to the active
varlables of various instances. In sone cases, this Process of
adjusËment !t111 lnvolve the use of ttsusp(11ri2)ttas deflned above, and
so 1t fs incorporated inÈo the sequence control rnodel.

The execution of certaln control operations by a procedure


sequence
l-nstance in an executfng ACL program ís regarded as occurrlng on behalf
of an lnstance of the coroutlne or generator whose definitl-on most

64
closely textually encloses that of the procedure; thls 1s anoÈher of the
means by whlch a close corresponderrce between the program text and its
behavlour at run-tfme ls ensured: lt will always be clear, from the
program text, to which corouËl-ne or generator such sequence control
operaÈlons app1y, even lf they occur 1n procedures. To allow the
descriptlon of this aspect of ACL' the sequence control model is
augmented by the addition of:

ttencl(1)" whtch evaluates to a reference to the fnstance tt|" if 1ü


is a coroutine or generator instance; lf, however, rrltr is a
procedure instance, "encl(i)" evaluates to a reference to the
lnstance of the eoroutlne or generator whose deflnltion most
closely textually eneloses t.hat correspondlng to rrirr (1f there ls
more than one such instance, the one which is llnked to 'rit' by the
shortest sequence of caller and then master llnks ís chosen). If
rrírt 1s a procedure lnstance and no coroutine or generator instances
exlst, then "encl(i)rr evaluates to a reference to the main program
instance.

4.2.4 .3 The Secuence Control Operations

Procedure call and return 1n ACL are deftned in an ldentical


.fashlon Ëo the general deflnltlons given ln SecÈion 4
.2.2, which are
repeated here for the sake of completeness:

PCd = { A+create d; A.caller<-current; enter A }


PR = { enter current..caller }
(Note that names such as wlll be used fn this sectlon for
"PC" and
rrPRil

the sequence control operatlons of ACL; they are merely convenlent


labels, and are in no rray related to the syntax of the language')
Creation of coroutlne and generator Ínstances tn ACL 1s explicit '
unllke oLher proposals for groups of coroutlnes (for example, Èhose of
Krleg, Pritchard and Sajanienl) in which all of the members of a group
are lmplicltly created on lnstanElatlon of the group. Thus, in ACL, the
members of a group may be created at various times during the lifetlrne
of the group; this not only has the poÈential for savlng the storage
occupled by lnstances not yet actually requlred, but also gives Ehe
prograrnmer the power to limit the number of program components to Ehat

65
appropriaÈe at the time. Another advantage of expllcl-t creatlon of
l-nsÈances 1s that lt allows the members of a group Eo be created in an
order, posslbly varying, speclfled by the programmer; a dlsadvantage of
explicit creaÈion 1s that 1t does noL conÈrlbute to a close
correspondence between statl-c textual structure and the structure of the
executl-ng program, in that the number of members ÈhaÈ a group wÍll have
at run-tirue will vary and hence wLl-l not be clear from the text' as lt
would wíth tnpllclt creaÈlon. In partícular, whether coroutine or
generator ln ACL ts caterval or elementary 1s a dynamic' rather than a
static, property.
Coroutine and generat.or instances are creaÈed in ACL programs uslng
the operatlon:
IC d = { A+create d; A.naster€-encl(current);
A.caller <- susp(currentrA); return A;
encl(current).active êA; enter A )
in r¡hich the master varíable of the created insËance ls set to indicate
the boss of the group to which that l-nstance nolr belongs; thls boss will
be the creatfng lnstance 1f the latter is a coroutfne or generator' or
some other instance if Èhe instance creatlon operaElon ls encountered in
a procedure insÈance. The caller variable of the new instance 1s used to
'record a reference to Èhe subtree (or slngle instance) v¡hlch is Ëo
become suspended v¡hen the tt.nlgt Arr actlon is encountered, transferring
control to the ne\{ instance for lnltlalizatlon processlng; thls
reference allows the lnltial-ízLng instance to behave as a generator and
for execuÈion to carry on wíthln the lnstance actually lssulng the
lns¡ance creatlon operatlon, after the new ínsÈance has conpleted its
lnl-tiallzation phase. NexÈ, the expressLon "IC dt' (again, thls bears no
relatlon to the actual syntax of ACL) evaluat.es to a reference to the
newly-created instance; this ls done before the instance begins lts
initializatlon, to avoid the difficulty descrfbed earller for Simula.
The actlve varlable of the boss of this grouP is then adjusted to
fndicate thaE the new instance 1s the actlve member of the grouP, after
whlch the fnstance 1s entered, and tts Lnl-tlaLlzation phase beglns.

As an example of lnstance creatlon, conslder the case that 'rP3r' in


Fígure 4.5 ls an instance of a procedure deflned 1n the coroutlne
ttencl(p3) " is "C2"),
def lnl-tion of whlch "CZ" ls an instance (that fs,

66
and that lt creates a furÈher coroutine lnstance ttC6". The effect 1s to
transform the masËer tree of Tigure 4.5 lnto thaÈ sho¡¿n 1n Flgure 4.8:
"C6" becomes a member of the group of whlchrtCr" is the boss¡ the caller
variable of Èhe new lnsÈance ls set to lndicaEe "C4" (the root of the
subtree suspended when "Prtt executes I'enter C6"), and the actlve
varlable of. "Crtt 1s changed so that l-t lndicaÈes "C6rr.

ct

G c
I 2

G C: c c C
2 4 6 5

G3 G G P
4 5 3

Fisure 4.8 The Effect of an Instance Creatlon Operatlon on the


I'faster Tree of Flgure 4.5

. The lnltfalizaÈlon phase of a corouÈine or Senerator instance l-s

terminated by that instance executlng the following operatÍon:

TI = { A+current.caller; current.caller +nÍl;


current.master.actÍve<-A; enteq A )
Notlce that a speclal operatlon has been introduced into ACL for the
sole purpose of terminaEing inltlalization, thus avoiding the sl-tuation
in Sfmula, in which Ehe t'detacht' operatton 1s "overloaded", performlng
different functlons depending on whether lt ls belng execuËed for the
first time in a class instancer of noE. The effecÈ of the above
operation 1s to lransfer control to the l-nstance lndicated by Ëhe caller
variable of the instance 1n r.rhich the operatlon l-s executed, havlng
flrstly adjusted the actlve varíable of the boss of the group. The
reason for setÈlng the value ttnll" inÈo the caller variable once lts
former value has been obtained will become clear shortly.

67
Consfder, as an example, that the lnstance 'rC6'r ln Figure 4.8 were
Èo execute a TI operatlon; the effect would be to erase the cailer link
f rom |tC6tt to "C4", and to set the actlve variable of "C2" to lndicaÈe
ttC4tt, thus suspending ttC6" and resumlng the executlon of the caterval
lnstance ttC4tt. The resulÈ of resumÍng this structure 1s that executlon
conElnues wtthin ttP3tt, at the statement after that whlch caused the
creaÈlon of the lnst.ance ttc6" (slnce t'P3tt is the llve lnstance r,¡iËhln
the subtree with root ttC4tt).

A TI operatlon is always execuÈed from within the text of a


coroutfne or generauor (it may noÈ, for example, be executed from within
a procedure) and lts executíon ts never condltional; fn fact, a TI
operatlon dlvldes the text of a corouElne or generator into two distinct
sectLons: the ttinlti-alization sectÍon[ and the ttmaln sectlonr'.

Transfer of control Eo a coroutine lnstance may be effected in an


ACL progran vla the following operaË1on, whlch ts an example of a
rrdfrected transfer operationtt (one l-n whtch the lnstance to which
control ls to be transferred ls speel-fl-ed exp11c1È1y):
CT c = { A+susp(currenÈrc);
ff A=c.masÈer
then A.acÈl-ve (- c
else 1f A=c.actlve then c.actlve(-c
else A.master. actJ-ve + c;
enter c )

1n whlch "ctt must refer to a coroutlne instance such that the transfer
from ttcurrentrr to "ctt conforms to Èhe prlnclple of opaqueness; the above
operation sinply transfers control to the specified coroutlne insËance'
havLng correctly adjusted the relevant active varlable. Ttre complication
fn doing the latter arlses because of the need Èo dlstíngulsh between
three different cases:
a Ëransfer from the boss of a group to one of lts members,

a transfer from an instance to one further up the chain of active


llnks (signifying EhaÈ the boss at that level ís to become acElve),
and

. a transfer ttacrosstt the naster tree to an lnactive member of some-

6B
group ¡shose boss Ls on Ëhe chaln of acEive Lnstances whose head is
the maln program itrstance.
The difference between the last two cases ls the difference¡ sâyr
between rrP3lt 1n Flgure 4.5 executl-ng rrCT C4'r (neanfng thaË Èhe boss of
tta4tt'" group should gain control) and iÈ exeeutfng ttCT C5 tt (a simple
transfer of conÈro1 to the instance specified).

JusË as the above operation is used to transfer control to a


coroutine instance, another operatlon Ls provided in ACL for
transferring control to a generator instance:
GC g = { lf g.caller=nil then
I A ê susp(currenË rg); g.caller +A;
1f A=g.xnasÈer then A.activeêg
else A.master.actÍve ê g;
entsr g I )
fn whlch rrgrr must refer to a generator instance which is such thaÈ the
prlnciple of opaqueness ls befng observed. Ttre inltíal test on the
caller variable of Èhe target lnstance "g" is Èo prevent the formatLon
of "rlngstt of caller llnks, so that a sequence of instances returning
along their caIler llnks cannot cause control to reÈurn to another of
the lnstances on that sequence; thus, the caller varlable of an instance
1s set to "nllt' when lt 1s not in use (see TI above, and GR below) and a
GC operaÈion ls only allor.red íf the calle-r varlable of Èhe target
lnstance has this value for the caller variable to have any other
value 1s regarded as an êrroEo (In Slmula, slmllar rlngs of class
lnstances are prohlbited by dernandlng that Èhe instance referred to by
the argument of a "calltt sÈaÈement be in the t'detachedttstate.)
If the generator call operaÈion 1s legal, the (free) caller
varlable of the target lnstance is used to record a reference to the
atructure whlch will become suspended when control is transferred to the
target lnstance; it ls this entlre structure whlch ls regarded as
rrcalllngtr the generator and to qrhlch the generaÈor will later reËurn
control. Once the cal1er varlable has been seÈ, the actlve links are
adJusted; thts latter process ls complfcated by the need to distingulsh
beÈween the case that Èhe mâster of the target lnstance is becoming
suspended (that ls, a boss 1s calling one of Èhe members of lts group) r

69
and the case that the rooE of the sÈructure becoming suspended is a
member of the same group as Èhe target lnstance. After the approprÍ.aEe
actlve varlabl-e has been changed, control is transferred Ëo the t.ârget
LnsÈance.

Â,s an example of a non-Èrivlal generat,or call, consider the effect


of ItP3'r in Flgure 4.5 executlng trGC Gl"t the caller variable of 'rclrr ls
used. to record a reference to ttCz" , the latter being the root of the
subt,ree whi-ch will become suspended when "P3" executes ttgqq Gltt, the
value of the active variable of t'CrttÍs then changed from "Crtt to "G1",
and the latter's l1ve instance (t'P2tt) starts executing. The resulting
master tree is shown 1n Figure 4.9.

Fisure 4.9 The Effect of a Generator Call Operatlon on the


Master Tree of Flgure 4.5

Returning from a generaÈor lnstance |s accomplÍshed by the


operatlon:

GR = t A+encl(current) .caller; encl(current).caller <-nl1;


lf A=encl(current) .masÈer then A.active +A
else A.naster. actlve +A;
enter A )

whlch |s only alLowed ln the maln secÈ1on of generaEor definiÈions, and


1n procedure definitions textually nesÈed wfthln generator deflnltions,
the lagter allowing lntervenfng definitlons of other procedures, but not
fntervenlng coroutine definitlons. The generator instance from which

70
control ls returned by this operatLon ls rrencl(eurrent)"; fts caller
varl-able l-s inËerrogated and then set to "n11", Ln accordance wlth the
scheme described above for preventlng the formatlon of rings of caller
l1nks. The adjustment of actl-ve variables requires Ehe case of returnÍng
to the boss of the generator's group (the ftrst alternatlve ln the test)
to be distlngulshed frorn the case of returnlng to some other member of
fts group (the second alternative).

For exampte, Lf 'tPr" Ín Figure 4.9 r.¡as an lnstance of a procedure


deflned wlthin the definítlon correspondlng to t'Glt', and it executed a
GR operatlon, the effect r¡ould be to erase the caller link from "G1" to

"CZt', to seË the actlve varlable of ttcltt to fndicate "CZt', and to


transfer control Èo the subEree whose root is I'C21r, at whích poinÈ "P3r'
would recommence executlon. After these actlons, Èhe master tree would
agaln have the form shovm 1n Flgure 4.5.

Coroutine and generator lnstances may transfer control to the boss


of the group to rlhich they belong with the operatlon:
MR = { A<-encl(current).master; A.active+A; enÈer A }

whlch returns conËrol to Èhe lnstance lndicaÈed by the master variable


of Ëhe currently executlng instance tf that lnstance ls a coroutlne or
generator, or that indicated by the masËer variabl-e of an Lnstance of
the coroutlne or generator whose deflnltlon most closely textually
encloses that of the currenËly executing instance, 1f the MR operatlon
Ís executed by a proeedure lnstarrce. In elther caser the instance to
whlch control passes is the boss of the group, and hence its actlve
variable is seÈ to indicaÈe ltself. The above operatÍon may only appear
Ín the main sections of coroutlne and generator definltions, and in the
deffnltlons of procedures textually nested within the deflnitlon of a
coroutÍne or generator.

A,s an example of the effect of an MR operation, suppose agaln that.


trPttt in Flgure 4.5 was deflned Ín the deflnlllon corresPonding to "C2tt,
and thaL it executed an MR operation; thls would result in the
suspension of the caterval corotrtine instance "C2t' and control would
then pass to "C1", whose boss l¡ould start executing (that i-s' the actlve
variable of "Cr" would be adjusted to Índicate ttCltt Ítself).

7L
ACL's I'fR operation 1s sl-mllar to Simula's ttdetacht', and the effect
of the ttmultl-leve1 deÈ.ach'r of CorouÈ1ne PASCAL can be obÈalned by
applytng the CT operaÈ1on to a corouÈlne lnstance further up the master
tree along the chain of active llnks, which results ln the boss at that.
level gaining control and the subt.ree which rüas its actlve member
becomlng suspended. Ttris use of the CT operation produces an effect
sfmllar, but noË ldentlcal, to thaE of a series of MR operations belng
executed by the lnstances on Èhat chaln of active links. Unfortunately'
thls technlque cannot be used l-n the case of generaÈors, but another way
of obtainlng a "multi-level deÈach'r in ACL (which can also be used w1Ëh
coroutines) ls for an MR operation to be executed by a procedure defined
l-n the definLtlon corresponding to Ehe active member of the group Èo
whose boss control should pass.

It is clear that a generator lnstance (or an lnstance of a


procedure defined r"¡ithin a generaËor deflnitlon) rnay execute one of Èwo
dlfferent undÍrected transfer operatlons: a GR operatlon, returning
conÈrol Èo the l-nstance lndicated by the cal1er varlable¡ oE an ¡{R
operatLon passLng control Èo that indicated by the masÈer variable.
IlavLng both of these operattons available 1s of conslderable advantage
when programming with generators; for example, 1n the solutlon to the
telegrams problem descrlbed ín Chapter 2, node 2 is a subprogram whl-ch
'normally returns control to its fnvoker (node 3), but under exceptional
cfrcumsËances (when the lnput f1le is exhausted and node 2 1s asked to
f111 the buffer), control should pass instead to Èhe boss of the group
to whtch node 2 belongs (Èhat l-s, to node l) , ln whaÈ v¡as described in
Chapter 2 as an "error exittt. This behaviour can be accomodated in ÀCL
by naking node 2 a generator which can use a GR operation to return to
node 3, or an MR operation Eo transfer to node 1 (1ts boss).

In fact, one YraYÈo vlew the difference betr¿een coroutlnes,


generators and procedures l-n ACL 1s in Ëerms of the klnds of undirected
transfer operations avallable to them:
a coroutine lnstance may only reEurn to lts 'rmaster" (fgnorlng its
use of the caller varlable during l-ts initializatlon phase),

a procedure lnstance may only return to its ttcallertr, and

a generaEor instance may return eiÈher to lts ttmasterrr, or to lts

72
ttcallertt.

Reeall that, in each case, Easter varlables record relatlonships


thaÈ are |n some sense statlcally-derived, whereas caller variables
always record dynamically-derived relattonshlps. Tt¡e separatfon of the
Concepts of rrnastertt and ttcallertt, As suggested here, 1s sinilar to the
lndependenÈ suggestlon of Soffa and Lindstrom[138] for Èhe separatíon of
the concepts of trcreatortt and ttresumertt. One dlf f erence is , however,
that it ls possible Èo change both the ttcreatortr and ttresuüer"
relatlonshlps in their proposal, whereas the 'rmasËerrr relatlonshlp l-n
ACL ts flxed for the lifetlme of the partlcul-ar coroutlne or generator
Lnstance; another difference ls the fact thaÈ no distlnctlon is made
between coroutines and generators, and hence any t'coroutlnett in their
System may pass Control elther to lt.s ttcreatortt or to its
rrresumertr.

Table 4.2 contal-ns a brief summary of the sequence control


operatlons whose deflnltlons have been given Ín this section; it also
lndícates tn which kinds of subprogram deflnitions each of the
operations may appear: ttPtt, trCrr and rrGtr stand for procedure def lnitionst
coroutlne definltions and generator deflnitions, respectfvely (the nain
program deffnitlon is regarded as a procedure deflnitlon for the
purposes of thls table) . "P'" stands for procedure definltions whlch are
and ttP"tt stands for
,textually nested ¡ulthin a generator definttion,
procedure definítlons textually nested within Ehe deflniÈ1on of either a
coroutine or a generator. NoË1ce that all of these restrictions are
textual, and hence can be enforced by checks durlng program compÍlation.

Table 4.2 A Sumroa ry of the Sequence Control Operatl-ons of ACL

Operation Purpose I,Ihere Allowed

PC procedure call PrctG


PR procedure return P

IC lnstance creatlon P, C,G


TI termlnation of lnltializat.ion C'G
CT coroutine transfer P,CrG
GC gerrerator call PrCrG
GR generaËor return P'rG
MR master return P,, ,C ,G

73
The sequence control effect of the termlnaË1on of a procedure
lnstance ls the sane as Èhat of the PR operaÈ1on; the effect of a
coroutine or generaÈor lnstance terminaÈlng 1s the same as that of the
l"IR operaÈion (that 1s, control passes to the boss of the appropriaÈe
group). In additfon, the terminaElon of a coroutlne or generator
lnstance causes the corresponding instance varlable to acquire the value
frno_instancett. The appllcation of a CT or GC operaËíon Èo an lnstance
variable with Ëhe value 'rno l-nstance" results in an error (at run-time).
Non-local Jumps ("gototts whose target statemenÈ ls outslde the
subprogram ln whlch the Jurnp sÈatement occurs) are precluded by data
control design declsions to be discussed later, and so transfers of
control between subprogram instances ln an ACL Program can only be
achieved using the seguence control operatLons descrlbed above.

74
4.3 The S ntics of the Data ConÈrol Aspect

4.3.1 Da ta ConÈrol in ProsramminÊ Languages

4.3.1.1 Introduction
A.s already mentioned ln Chapter 2, the data conËrol features of
programming languages are concerned wÍËh Ehe specificaEion of restric-
tlons over which data structures are accesslble ln varlous Parts of a
program; ln other r,rords, they give a Progranmer conÈrol over where
references to daËa items can and cannot occur in a progran' Such
features may also allow the prograruner to restrlct the conÈexts 1n which
accessf-ble ldentlfíers may appear, thus resÈrictlng the klnd of access
to the corresponding ltem.
Informatlon blnding, deflned by Elson[40] as rrassoctatlng synbollc
references with intended obJects", represents a vlew of daEa control
whtch has enJoyed some popularlty. Various representaElons of
fnformatlon bindÍng have been suggested; one of these ls the binding
diagran of l.legner t 155 L shown 1n Flgure 4. t0 , which gives the
relatlonshlp between names, references, cells and values' The name 1s
the trsymbolic reference'r referred to by Elson, and 1s typically an
ldentlfier; the cell 1s the hardware locaÈions occupied by the value'
and is thus synonymous with a hardware address; the reference ls a
ttsoftware addreSstt: for example, a Polnter to An actiVatlon record,
along with an offset' Data conErol ls concerned ¡'rfth the name-reference
relatLonship and with making changes to such relationships; on the other
hand, reference-cell relatlonshíps are handled entlrely by the storage
nanager. Restrictions on Ehe kin<l of access allowed to a variable amount
to protecting cell-value relationships from change'
name

POSSeSSeS

reference
refers to ce11

conÈains

value
Ftsure 4.10 l^le gner's Binding Diagram

75
The bindlng tfrne ls deflned by Jones and Muchnlckl8l] to be the
polnt in the processing of a program at trhlch each relatlonship ln
Flgure 4.10 becomes flxed, or bourid. No two authors agree on the set of
possl-ble bindlng tlmes; the followlng llst ls proposed by Jones and
Muchnick, and glves some ldea of the wfde range of PotenEial blndlng
tlmes: compilation, loading, beginning of executlon, block entry, and
explicít sLaEenent time.
As already lndlcaÈed, daÈa control facllltles allow Ëhe prograutmer
to restrlct access to data or subprogram items; the reasons for wanting
to restrict access may vary from prograûrmer to progranmer' and from
program to program. One reason for utllizing Ëhe data conÈrol facillties
of a language 1s that lt is then possible to reduce the number of
progran varlables whlch need to be consldered when htriting or attemptlng
to understand a partlcular sectlon of a program. Thl-s is related to
DlJkstra's vlew, expressed fn Chapter 10 of [36], thaÈ the net effect of
a program component can be vfewed as a movement ln the subspace (of the
state space of the progran) spanned by the few variables that are
affected by it. The desÍre to reduce the number of dinensÍons of thls
subspace, 1n order to lmprove the couprehensibllity of the componenË'
and to have the program text give some clear indicaÈl-on of the nature of
thls subspace, leads Dijkstra to introduce an expressive set of daËa
'conÈrol facilltles. However, data control speclficatlons prescribe the
varlables which might posslbly be affected by the program component, but
not those r^rhich are actually affected; thus, the subspace described as a
result of using the daÈa control features of a language (lncluding those
of DiJkstra's proposal) maY, in fact, have more dimensions Èhan the one
originally sought by Dijkstra. This use of data control Èo subdívide the
state space 1s one of Ehe advantages of those programming languages wlth
data control facllities, for, at the other end of the "p."ttrr*r'nthe
lnterface between every two consecuËive lnstructions ln a machfne code
program consists of the state of the entire machine"167l.

Another reason for Lncludlng data conËro1 speclfications in a


program ís to improve its vertflabllity, as is discussed at length by
KÍeburtz [83] , who suggests some ways in which the data control
facLlities of block-sÉructured programming languages can be nodifled to
enable Eo be ¡¡rLtten programs whose correcËness is easier to verify. The
basls for these nodificatlons fs thaE there should be I'avallable ¡¿ithln

76
the scope of each procedure deflniÈlon the lnformatlon requlred to
determlne the course of a computat.lon by thaE procedure'r, and the effect
of hfs proposal ls that itglobal data objects can be proÈected from
unlntended aecesses by a procedure, and that thl-s protect.lon does not
depend on the correcLness of the code of the procedure bodytt'

The vlew of data conËrol taken by operatlng system designers ls a


protectioníst one (for example, see t93l or t871), and some of the
proposals for improved data control in progranming languages (such as
t791 ) have also been based on thls vlew. The protecÈÍonlst view of data
conÈrol ls slnply that access to data items 1s restricLed to protect
them from interference by modules which do not have the permlsslon Èo do
so. The proposals of Palmetl18l and Parnastl19l' whlch advocate
rrinformatlon hÍding" and clearly deflned ínterfaces between nodules are
'
derlved f rom a sÍnllar polnL of vie¡.¡.

It is possfble, 1n sorne languages, to speclfy that a data item (or


a set of relaÈed data iterns) can only be accessed via certain
operatLons, such an aggregate of data and operatlons belng called a
ttdaËa abstractlon"; 1n some. of the languages wlth data abstracEions
(exarnples are those described in I1671 and [164])' the progranmer can
specify whlch of the avallable operatlons of a parË1cular instance of a
data abstracElon are t.o be accessible within a module creating (in the
case of [167l) ot uslng (1n the case of A1phardtl64l) that lnstance, in
whlch case the facíllty ls knov¿n as a 'rcapability-based data
abstractlon". As polnted out by Koster[84], the essenÈl-al characterlstic
of data absÈraction facilities 1s Ëhat they provide control over the
'Vislbil1ty" (accessibllity) of data, and the need for special language
constructs for daÈa abstractlon can be obviated by providing
sufficiently expresslve data control features 1n programming languages.
In of the fact that 1t was one of the goals of the design of
vle¡u
ACL thaË lt should be posslble to express a wlde range of data conÈrol
structures in the language; the assertlons made by a programmer as a
result of uslng the daÈa control features of a language may then be
checked by the language processor, provided that. this can be done
reasonably efficiently. Thus, the view of data control to be pursued in
this secË1on 1s that data control facllities allow a programmer to make
statements about where, withtn the program being written, the varlous

77
program and data ltens are going Eo be used, and Eo have these
assertions checked. Fisher [44] Puts |t slrnply, by saying that "the
safety of programs ts enhanced by requiring speclficaElon of the
prograümer's intentfr. Clearly this view of data control is related to
the proÈectionlst vlew, in that the programner's intentions, as stated,
can be checked againsÈ his actual behavlour, and thus provide some
degree of protectlon, or securlty. The dffference ls, hov¡ever, that we
wl11 be concerned wlËh how well data conÈrol facilities allorv the
progranmer Lo express the desired daEa control strucÈure (the lntended
paËtern of use of identlfíers) of programs, rather than l¡lth provldlng
data control mechanisms which force the programmer to tlghtly control
access to Èhe attributes of a subprogram unit (by' for example,
enumeratlng all other units whlch may access each of them), when he does
not wish to do so (when he is noÈ sufficlently aware of the intended
pattern of use).

Borrowfng from access control conventlons in multlprogramming


operatlng systems, Kieburtz [83] initlally proPoses three kinds of
ttread-onlytt,
access, 1n hlS diScussion of data control: "read-writett,
and t'execute"; however, Kleburtz eventually discards the last of these
,rslnce the names of entry poinÈs w111 always be distingulshed from
varíable names by other declared attributesrr in hls proposed systeu.
'Thls thesis, for Èhe sake of simplicity, wfll also only dístinguish the
f irst two kl-nds of access, which r¿tlt be denoted by RI^I and RO
respectlvely, and, of course, "no-accesst' (NA). The lnterpretatlon of RW
and RO access to the definitlon and ínstance names of subprogram unfLs
will be discussed later, when 1t r¡i1l be shown thaÈ Èhey more than
adequately cover the notion of execute access'

Kleburtz advocates that ttno procedure can pass along an access


privllege which lË does not hold for ftself"; this principle, whieh will
be referred Lo as the "princlple of non-lncreasing privilege'r, is also
enbodled in the bindlng and assignment rules of Jones and Liskov[80].
These rules state that binding (or asslgnment) is only legal if the new
access path provides at most a subset of the rights obtainable via the
origlnal access path. The present case is quite simple compared to those
descrlbed by Jones and Liskov, 1n that we are concerned with only two
rights and dlstinguish only Ehree subsets of these rights (these subsets
wlll contlnue Èo be called "kinds of access"). The rights are R (read)

7B
and I,I (wrlte), and the kinds of access are:

¡¡¡ = {R,I,I} R0 = {R} NA = ()

Gtven expresslons of the same tyPe (ln Èhe usual sense), the
following |tgreater than or equal to"[80] relationshfps, based on subset
relationshlps, can be enumerated:
RI,{>RO > NA

and hence the followl-ng bindlngs (assignrnents) are the only ones allowed
by the blndlng (assignmenÈ) rule:
(Ì'IA,NA) (Ro,NA) (RW,NA)

(R0,Ro) (RI,¡,R0)
(RtI,RW)

1n l¡hich Èhe noÈatlon tt (old, new) " is used to denote these t'blnding
pairs tr.

The structure of the remainder of Sectlon 4.3.1 1s as follows:


f1rstly, the relaElonshlp between data control and sËorage managemenE ls
explored, and then the vier¿ of block structure adopted ín this thesls l-s
explained; ftnalty, lnplicit and expllclt forms of data control are
dlscussed ln turn, the former belng exempllfied by scoPe rules, and the
-latter by parameters and functLon values.

4.3.1.2 Data Contro 1 and Storase Manaqement

The princlple relatlonship between data control and storage


managemenÈ ls ÈhaÈ storage allocated for daÈa items which have become
(perrnanently) lnaccesslble can be reallocated by the language processor
to data lterns which are Just becoming accessible. In systems wiËh
dynamic storage management, in whích the reference-cell relatlonships of
FÍgure 4.10 are establlshed during execuÈ1on, this can lead to
conslderably more efflcient use of Ëhe sÈorage resource. Of course, 1t
is also possible for a language to allow the progranner to expllcitly
allocate and deallocate Ehe storage occupied by data ltems, but, as
Hoare .remarks in [68], this aff ords t'unbounded scope for complexity and
êf foÉrr.

79
Probably the most wldely known example of automatic reallocat,l-on of
fnaccesslble storage is the usual irnplementation of A1gol 60
(disregardlng "ortn" variables): the blocks of an A1go1 60 Program,
includlng any procedures whÍch are called, are always entered and left
ln a strictly last-ln-first-out manner, which permlts reallocatlon of
storage to be accomplished by stack technlques. Thfs is only posslble
slnce, Ìvhen an A1gol 60 block ts exfted, all of the local daÈa ltems of
that block become permanently lnaccessible; except for ttowntr varlables,
new variable lnstances w111 be created for those daÈa ltems lf ever Èhat.
block Ls agaln entered, and hence the old varlable lnstances are no
longer requlred. It is worth noting at this point that there are no
expliclt references to block instances 1n Algol 60 and related languages
(such as Pascal), and that lf nultlple instances of blocks exlst, lt is
the most recently creaEed one whlch becomes parÈ of the coriÈexÈ of any
block insEances whlch have access to items of that block. As ¡¿as noted
ln SecËfon 4.1, it, turns out ln practlce that thÍs "latest acEivatlon[
rule, rather than allowing access to variables of oÈher of these
nultiple lnstances, is a vfable one, and that expllcit references to
lnstances are not needed. Explicit references to instances ls one asPect
of certaln languages l-ncorporating coroutlnes which can lead to storage
management schemes whlch are less simple than the sÈack technÍque.

points out the dif f iculties which can arlse if stack


I,tregner t 155I
management is used to lmplemenÈ block-structured languages whlch contain
certaln features, such as poinÈers to instances (or to attrÍbutes of
instances), and procedure-valued data objects. In tr{egner's paper, and fn
a number of oËhers (such as [14], [15], and l24l), two dÍstlnc¡ strat-
egfes for the deallocation of block Ínstances are discussed:

(1) the storage 1s deallocated upon exlt from the block - thls ls
knor¡n as the deletlon strategy, and

(2) the storage 1s only deallocated r¿hen 1t 1s no longer accesslble -


thls is the reÈention straÈ egy.
If Èhe deletfon strategy ls adopted for a ttgenerallzedtt block-
structured language (one havlng Ehe features mentloned above), such as
Oregano[13], PARALLEL EIILERl24l, or GBSL[15], the problems known as
ttdangling ref erence" or rrÍmposEer envlronmentrr [24] can arise. For
example, conslder Ëhe case of a block-structured language whlch allows

BO
poLnters to varlables belonglng to lnstances; the situatlon may arlse ln
such a language where a pofnter variable belonging to the context of an
actlve lnstance polnts to a varlable of an lnstance whlch has been
exl-ted - ff the deletlon strategy has been appll-ed, the sËorage for that
lnstance will have been deallocated. In the case of an attenPt to
dereference the polnter varlable, the run-time sysÈem may detect an
atÈempt to access a location outslde the stack area (the dangllng
reference problem), or the polnter may indtcate a location lnside the
stack, wÍthln a subsequently allocaÈed instance (the imposÈer
environment problern). ImplementaElons of such languages may use the
deletion straËegy, elther to gain the efflclency of a run-tirne stack or
because Èhe hardware offers little choíce (see [116]), and Èhen impose
restrfctions on the use of pointer, Iabel and procedure values Lo
prevent the occurrence of the above problems. These restricÈlons require
the addition of run-tlme checks, the various alternaÈfves for which are
descrlbed, in detall, 1n 124).
All of the discusslons of rrretention versus deletlon'r cited above
recommend. the retentlon sËrategy, sÍnce 1È precludes the danglÍng
reference and lmposter environment problems from ever occurring, and
since 1È can be shown t15l that an i.mplementatÍon of the retentlon
strategy usíng a partial reference count systen fs, for a certain class
óf programs, approximately as time-wlse efflclent as an implementatlon
of the deletion strategy with the appropriaËe run-time checks.
Although ACL does not conEaln features such as procedure variables
or polnËers to varlables 1n instances, the retentlon versus deletion
argument, ls relevant Ln that lt rras decided that coroutlne lnstances
should be retained until they can no longer be enÈered and their
aÈtributes are no longer accesslble - thaÈ ls, a retentlon strategy \{as
adopted. Ttre manner tn which the retenÈlon strategy has been implemented
w111 be discussed later in thls thesis.

To avoid the problerns of unlnltlallzed varlables, DiJkstra (in


Chapter 10 of t36l) Proposes thaÈ the creatlon of the storage for a
variable be forced Èo coincÍde with its lnltializatlon. Since Èhis
lnitlallzation does not occur at the varlable's declaratlon, DijksÈra
iritroduces the noLlon of "passive scopet': thts is that parÈ of a
varlable's scope before its inittalízatlon and is noE really scope at

81
all, ln that no reference to the varlable can occur thereln. In order to
avold the added complicat.lons of ldeas such as "passfve scope" and
"vlrgintt variables (those not yet inltlallzed), and reJectlng the notion
of fnplicit l-nltlallzatlon for all varlables (as is used, for example,
1n Sinulat33l ) slnce iE nakes "a11 sorÈs of nonsensical Programs
artiflcially into legal ones" [36] , the concePt of an ttundefi-ned"
variable (one that has yeÈ to be lnlttallzed) ls admitted ln ACL and
consideration of initlallzation wíll be omltted from our discussion of
data control. Followíng from thls decÍsion, the relatlonshlp between
data control and sÈorage managenent can be viewed in Èerms of the
following events occurring for each varLable:
(A) openlng of Èhe scope of access for the varlable,

(B) closing of the scope of access for the varlable,


(C) allocation of storage for the variable, and

(D) deallocetlon of sÈorage for the varlable.

A temporal partial orderlng on Èhese events, for each varlable, can


be defined and thts 1s shown ln Figure 4.1f. Thus, for example'
allocaÈl-on of storage should precede the first opening of access, and
Èhe scope of access may open and close many tlmes before closing for the
'fina1 tlme. In tmplementatlons of Algol-like languages, allocatlon of
storage for a variable coincides with 1Ès fl-rst openlng of scoper and ft
1s deallocated at the last closing of scope. In Ëhe pasÈ, the quesÈions
of the accesslbillty of data ltems and of Èheir temporal perslstence
have been confused. In languages such as A1go1 60, changes ln the
accessÍb1l1ty of variables occur at the same texÈual points as those at
whlch events involvlng the all.ocatlon or deallocat.lon of the storage for
those varlables are known (by those programuring in such languages) Èo
occur. To emphasíze the distlnctlon betr^reen data control and storage
management, the Algol fragments shovrn 1n Flgure 4.12 are presented.
Their data control structures are idenÈical, buË their storage
allocatlon/deallocat.lon behavlours at run-time are dlfferent.

82
Fleure 4.11 A Partlal Ordering on Events
Temporal
Concerned wlth a Variable

begin lnteger f; begln lnteger l-;


sti sti
begin lnteger j; begin own 1nÈeger j;
szi szi
end; end;
s3 s3
end; end;

(a) (b)
FLgure 4.12 Turo A1 go1 60 Fragments with the Same

Data Control Structure

4.3.1.3 Block Struct rtrê


In thfs thesls, a definitlon of block structure w111 be used which
ls less restrlcted than some oËhers; the alm 1s to dlstlnguísh a more
general notlon fron the partlcular form used fn languages such as A1gol
60 and Pascal. The view to be adopted here ls that a block (or block
levelr if the concept of levels of blocks is used) ls that part of a
program over which a partlcular set of fdentlflers can be used, and that
each of these identiflers has a conslstent lnterpretatfon (that is,
refers to the same subprogram or data lten) over the enËlre extent of
the block. In brief, blocks consist of uniform referencing envlronmentst
where a referenclng environment ls deflned by Pratttl2ll to be the
currently act,lve set of tdentifler assoclations; thusr our notlon of a
block corresponds to Bobrow and Wegbrelt's 'runiforur access module" t19l .
Progranming languages nrhich allow the construction of blocks such as
these will be referred to as ttblock-structuredrr; ACL 1s sueh a block-
structured language. In some block-structured programmlng languages'
part of the terminology (identiflers and their meanlngs) usable ln a

83
block lnst.ance 1s acquÍred f rom oEher blocks, and some is ne\t
Èermlnology lntroduced for that block; 1f the new termLnology lnvolves
references Èo variable instances whlch had not previously been
accesslble, then some allocatlon of storage may be requlred. In adoptlng
block structure for ACL, no assumptions are belng made aË this sEage
abouÈ data control between blocks; in particular, the scope rules of
Algol 60 may noÈ necessarlly apply to nested block structure, lf nesting
Ís indeed present.
The possiblllty of multlple insËances of a slngle block deflnltlon
Lmplies the use of actlvation records as an lmplementaÈlon scheme; ln
the general case, these actlvatlon records will contain sequence control
fnformation (either a returD address or a continuatlon polnt) and data
conÈrol Lnformatlon (such as where to ftnd non-local variables, lf
access to non-local varlables is posslble). The contexË (or environment)
of executlon of a block fnstance, eonslsting of Lhose data items which
are accessible in the instance, ls contained l-n an ordered list of
activatlon records; the scope rules of Algol 60, for exampler glve rfse
to a pa-rtlcular choice of whlch activatlon records are to be on the
llst, and to a partlcular orderÍng on Èhem. The ordering speclfies the
order tn whlch the search of a part,icular idenÈlfier 1s to be conducted
at run-time, although 1t may be posslble to conduct thl-s search, 1n
'ánttclpatlon, during conpilatlon.
The maJor advantages of block structure are as follows:
(1) iÈ ls essentlal to the factorizatlon of the state space of a
program lnto subspaces¡ âs described by Dljkstra (see Sectlon
4.3.1.1) , and, as such, leads to the produetlon of betLer
programs t

(2) 1Ë allows a dynamic storage manager to deal trith larger sectlons


of storage (since the need for nelr sËorage ls concentrated at
block-entry tine), whlch Eends to make storage managenent more
efflclent, and
(3) in languages whlch require dynamic storage managemenÈ' it gives
rlse to nore efficÍenÈ addressing of varlables (for example, as
an offset r¿iÈhin an activaEíon record).

84
4.3.1.4 Scope Rules

Seope rules, in thelr simplest form, represenÈ an implicit form of


daËa conËrol, and occur ln a large number of programmlng languages;
these rules specify ways ln which access ls granted, in one block, to
ltems of another block, wÍthout expllcit actlon by the programmer to
grant access l-n each case. Slnce the daÈa control effected by scoPe
rules is lmpllclt, they provfde a low level of expresslveness: the daÈa
control structures which can be set up using scoPe rules belong Èo a
very resËrlcted set. PraÈtl,L2Ll defines static scope rules to be those
which are based on Èhe st.rucËure of Èhe program text; sinee the
lnterpretatlon of the meanlng of ldentlfiers ls a vltal Part of
understandlng a program, and slnce iÈ lùas one of the afms of thÍs
language design to facllitate the process of understandlng a program
fro¡n lts text, only staËic scope rule schemes r¿ill be consldered Ín this
discussl-on (and will simply be ref erred to as ttscope rules'r). In the
ltght of the discussion of the previous section, sÈatic scoPe rules can
be defÍned to be those which glve rlse to an ordering on the list of
actlvation records forming the context. of executlon, which 1s based on
the program (text) structure; 1n the case of dynamic scope rules, this
ordering r¿ould be based on the passage of (sequence) control during the
progrants executlon.

The most wldely knor¿n example of scope rules is undoubtedly Èhat of


the scope rules of A1go1 60 and related languages. The first of these
rules is that access to a program or data ltem l-s restricted to the
block in whlch 1t is declared, and to blocks textually nesEed wiÈhln
that block. This rule is nodÍfled by the proviso, known as the
t'redeclared identlfler rulett, that name confllcts arlsing from its
appllcation are resolved by taking the lnnermost declaratlon;
consequently, ff an item of the same name is declared ín an Ínner block'
then the previously avaÍlable item is no longer accesslble. These rules
describe a parLicular way in v¡hl-ch the vocabulary of usable ldentlfiers
(and the declaratlons to which they refer) can be calculated for any
pol-nt 1n the prograrn text; this calculatlon ls partlcularly well suited
to machine computation and one wonders, as does DiJksÈra[36]' whether
this noËfvated their adoptlon, rather than considerations of programmer
convenlence. The redeclared ldentifier rule, whlch Díjkstra calls the
"prlority of lnnermost declaraÈlons", does have some Justlffcatíon: thls

85
1s, accordlng to DtJksÈra, that the composer of an lnner block needs
only to be aware of the global narnes 1n the surroundlng conÈext Èo which
he is actually referringr but thaÈ any other global names should not
restrlct hln ln the freedom of chofce of his own names with local
slgnlflcance only. Barron[9] cites as an advantage of the redeclared
identlfler rule, the fact that lt gives "at1 elegant way of providing
default declarationst'. The first rule, descrlbing the ldea of nested.
scope, has Èhe advanÈage, accordlng Eo Hoare[67]' that lt glves rise to
a ttclose correspondance between the statically vtsible scoPe of a
vartable ln a source program and the dynamlc l-ifetine of iËs storage
r¿hen the program is runrr.

These scope rules have, hor.rever, cone ln for some sharp criÈicisn
Ín recent years, the best known of whlch is probably the paper of I'Iulf
and Shar¿t1661. I^Iulf and Shaw clte the following unsaEisfactory aspects
of A1gol's scope rules:
(1) side-effects,

(2) lndlscriminant access: instead of restrlctlng access to that vla


cerÈain operaElons,

(3) vulnerabtlity: lnadverEant redeflniËion at an lnner block level,


and

(4) lack of overlapplng definitlons: lnability Ëo speclfy data


sharlng relationshtps betl¡een procedures declared at the same
level, withouË allowing all of the procedures access to all of
the data.

The notlon of ever-widenlng access as you go to deeper and deeper


levels of nestlng 1s critlcized by KieburEz [83] as 1t "gÍves Ëhe most
speciallzed procedure an unjustifiably wide scope of access", oEr as
pointed out by DiJksÈra[36], this conventlon has the dfsadvantage for
the programmer that "it rnakes the variables declared in hls outermost
block extremely vulnerable". An added dtfficulty i.s the fact that lE is
noÈ possible to distingulsh kinds of access wiÈh Algol's scoPe rules
all inherited data ltems are RI,I accesslble. It is thís that makes
varlables declared in ouËer blocks l1able to change ln inner blocks r arìd
Èhus glves rlse to slde-effects.

86
Another widely found crltÍclsm of Algol's scope rules is, l-n fact,
due to a fundarnental property of all totally ímplicit scope rules: that
1È l-s not poss1b1e, merely by examinlng (in lsolatlon) the text of a
block, to know the complete vocabulary of identlflers accessible 1n that
block. This has been found to be unsaElsfactory by a number of authors.
For example, DiJkstrat36l Proposes that a complete descripElon of a
block's possible lnterference with the state space of Ehe surrounding
block (by enumerating at the head of a block all of the ldentifiers
r¿hich Èogether form its 'rtexÈual contextrr) should be given, whích would
ll¡nit the amount of text whích would have to be sÈudled when a global
variable had been lnterfered with ln an lll-understood manner.
KleburËz[83] makes a slmilar suggestlon, but for dlfferent reasons: as
already mentioned in Section 4.3.1.1, he contends that the verlflabflity
of programs can be lmproved by having available in the texÈ of a block'
all of the informat.ion necessary to determine the effect of thaÈ block.
There have been a number of proposals aimed at rnaking Algol's scoPe
rules more expllcit and a detailed comparison of some of these will be
found ln Section 4.3.3.3.

Flnally, ít ts possible to have a block-strucEured language without


any scope rules aÈ all. Glpsyt2l is just such a language - subprogram
unlts (called "routi-nes't) deflned in GyPsy cannot be nested, and
"variables can only be def fned r.rithin these routlnes. This means that
Gypsy has no non-local variables, and that ttall varlables âre elther
local varlables or parameters'r.

4.3. 1.s Parameters and Functlon Values

These data control meehanisms are used in conjunction with those


blocks which are subprogram units and whlch, anong other things, have an
ldentlfier assoclaËed wLth Ëhem. Parameters and function values
represent expliclt forms of data control: ln both cases, the idenEifier
assoclated with the bloclc to whlch an access prlvilege ls to be
transmÍtted (the "called" block) ls glven explicltly 1n the block frorn
which Èhls privilege is to be Eransmitted (the "calllng" block); also,
the name by whlch the ítem to l¡hl-ch access privilege ls being
transmitted 1s known ln the calllng block, and the name wÍÈh vrhtch it is
to be associated in the called bloclc, are glven explicitly (sornewhere).
In the case of returnÍng a value from a function, all three of these

87
names are the same (the funcElon ldentifier). In addiÈ1on to belng more
expllcl-t, these forms of data control dlffer from (static) scoPe rules
in that they are more dynamic lf there are several calls on a
subprogram, wlth dífferenÈ actual parameters, varlous daËa control
relatlonshlps may be posslble between the calling and called blocks'
depending on which call acEually takes place.

A funcEion ls a special klnd of subprogram l¡hlch returns a value to


the polnË of cal1. One ruechanlsm for achieving this is to have the
functlon ldentifler avaflable as a "pseudovariable'r[121] wlthln the
functlon block; assignments can then be made to thls pseudovariable
durl-ng the functlon's execution, and its final value 1s returned as the
Value of Èhat call on Ëhe functlon, on exiÈ. An alËernatlve, used in
PL/L, is to designaEe, at each point of exlÈ from the functlon' an
expression r¡hose value is to be returned as the value of that call on
the function, if exlt occurs vla that exit poLnt. The rnotlvaÈ.lon for
fncluding function subprograms in block-structured languages with other
ktnds of blocks and subprograms 1s sirnply that 1t allows convenient
reËurn of a single result from a subprogram; Ëhis allor¡s, for example,
lts direct use 1n an expressfon in the calling block, rather than havfng
to employ some lndfrect means of uslng the result of a subprogram call
1n an expression. This notlon that a functlon subprogram returns a
'sLngle result can be enforced, as l-t was ln an early verslon of Pascal
(see tl5Bl), by prohlbitlng side-effects 1n a function.

of this secÈÍon is concerned with the maJor expllclt


The remainder
form of data control in bloclc-struct,ured programmlng languages:
paremeters to subprograu blocks. A subprogram ís invoked by specifying
lts ldentlfier and a list of actual paraueters (which rnay be idenLlfiers
or more general expressions) t.o be substítuted for the formal paraueter
ldentlfiers speclfled in the text of the subprograu block. There are
basically t\.{o $tays Èo indicate which actual parameters are to be
substltuted for ¡¿hlch f ormal paramet.ers: the t'positionalt' and ttkeywordtt
notatlons. The former, which is the mechanism used in most programmlng
languages with parameters, uses a one-to-one, left-to-right pairing of
actual and formal pararneters; the latter, advocated by llardgrave[63] and
Francez 1411, requlres expllciÈ denotation, withln the actual parameter
l1st, of which actual parameter ls to be substituted for whlch formal
parameter, by glving the formal Parameter identlfter in each case.

BB
There are a number of htays of carryLng out the process of
rrsubsÈltutl-on'r mentloned above, and of lnterpretlng references to formal
parameters ln a subprogram btock: these are the varlous parameter
tr.ansmlsslon mechanlsms (or modes). For example, Jones and Muchnickl81]
dl-stinguish slx such nechanlsms: call by text substitutlon, eall by
name, cal-l by reference, call by.value, call by resulÈ, and call by
value-result. The varieEy of parameter transmission mechanlsms reflects
some of the many uses of subprograms:

(a) Subprograms can be used to factotLze cornmon code out of a


program, replaclng each occurrence of the code by a call to the
subprograrn; the ability Eo parameterlze a subprogram makes it
posslble to perform such faclorLzatlons fn a wlder set of
circumstances slnce, Ln the words of lJirtht161l,
t'if a partlcular
sequence of operatlons ls applied to different operands in
different parts of a program, the sequence is formulated as a
procedure , and Èhe operands become parameterstr' .41 1 of the
paraneter passing methods are useful ln such situaÈlons, but call
by name allows f.acEotLzation in more cases than does any of the
oEher common methods.

(b) Another use of subprograms 1s as a program structuring device'


efther by carvlng large pieces of Program text lnto smaller
pieces (vertlcal decompositlon) r or by nesÈíng subprogram
definiÈlons to indlcate "fauily" relationships between different
pieces of the program (hierarchlcal decornpositlon). In both of
these sltuatlons, precisely-defined lnterfaces between Ëhe
subprograms is luPortant, and parameters provlde a useful means
of speclf ying these interf aces . (Reca1l , f or example ' I'lulf and
Shaw,s objectlon thaL Algol's scope rules do not a1low the
speclficaÈlon of certaln daÈa sharing relationshlps between
procedures called in sequence from the same block')

(c) It ls someÈlmes convenient to be able to refer to a comPonent of


a structured data ltem by a simple identifier, and passing the
componenL as a Parameter Eo a subprogram allows this to be done'
A net gain ln efficiency may also occurr lf the parameter
transmlsslon mechanlsm 1s such thaE the calculation of the
address of Lhe desired component 1s only performed once; this is

89
the case wtth, for example, call by reference and call by value.
(d) Finally, parameter transmlsslon ls a useful daÈa control device
1n a block-structured language with Algol's scope rules (or a
more explLclt varlant thereof), ln that lt allows access to an
item to be extended to a block whl-ch would not have access via
the scope rules. In other words, the superlmpositlon of parameter
passlng on scope rules allor¡s the speclfication of more
speclalized data control structures. A fragment of a Pascal
program, íllustrat.lng this use of parameters, 1s shown in Flgure
4.13; ln thls example, the variable ttactual" is made accessible
1n procedure rrcrr and procedure rrarr (ln the latter, under the
name ttforroaltt), buÈ not. in procedure
ttbtt.

procedure a (var
fornal: T);
begln .. . end { of a };
procedure b;
procedure c
var actual:T;
besin .. . a(actual) end{ofc};
besin .. . end { of b };
Ffeure 4.13 An Example of the Use of Parameters to Construct
Speclalized Data Control Structures

The seË of paramet.er Èransmission modes provided in Pascal conslsts


of ttvalue" (ca}l by value), t'varlablett (cal1 by ref erence), "procedurett
and 'rfunction'r parameters; each of these w111 be more precisely deflned
later, and a short, informal description will suffice for the present
discussl-on. A value parameter amounts to an lnplicitly defined variable
local to the called instance which is inltialized to the value of the
actual parameter; for the purposes of this lnitl-alizaÈion, RO access to
the actual parameter ls required (but no more). Variable parameters
result ln Èhe formal parameter ldentifler standlng for the actual
parameter (whlch rnust be a variable); since the value of the actual
parameter variable nay be changed via the formal parameter ldenÈlfier,
this transmission mode will be referred to as 'rRI{ reference".

90
procedure and functlon parameters enable the Èransmlssion of the
name of a procedure or function to a subprogram, so that lnvocaÈlon vla
the formal parameter idenLlfÍer may result ín the i-nvocaÈlon of a number
of dLfferent subprograms, depending on the value of Ehe corresponding
actual parameter. The Pascal fragment of Figure 4.L4 lllusÈrates the
dtfference bethteen passing the result of a functí'on invocaÈlon Èo
another subprogram, and passing the name of a function: the flrst
parameter of the procedure rrptr is a value Parameter and hence the
occurrence of trfrr as an actual paraoeter causes a call on the functlon
rrfrr and the value of the result of thls call ls passed to "P", within
whlch thls value is available under the name rrirr. The second parameter
trfrr iS encountered
Of ttptt, hOWeVef , iS A |tfUnCtlOntt pafameter and when
as the corresponding actual Parameter, iÈs name ís transmitted to "P";
whenever rrgtr is referenced wlthln ttPt', its actual value ls treated as
Ëhe name of a functlon, and thus
ttfrr is called'

functlon f:lnte ger;


begin... end { of f };
procedure (i: integer; function
p g: integer) ;

besin ... end ( of p );


begin ... p(f,f) end

Flsure 4.I4 A Pascal Fr agment Containlng a Functlon Parameter

Sone recent languages and proposals based on Pascal have augmented


lts parameter transmlssion modes with another, whlch rnay be descrlbed as
ttRO reference", in which the formal parameter stands for the actual
parameter as in the case of variable parameters ' but the called instance
does not have permissfon Èo change the value of the acEual Parameter
(whlch mây, in fact, no longer be resÈricted to being a varlable)'
Examples of thts kind of transmlssion mode are Ëhe "valt' feature of
PASQUALII47l, and "ReadOnly" Ín TELQSt89l; these suggestlons are
parÈ1cularly interesting 1n view of Ehe fact that the early version of
pascal described in t15Bl had "consÈantrr parameters in place of value
paramet,ers, and these were of the RO reference variety' The transl-tlon
from constanÈ to value parameËers in Pascal is justlfied by Amrnann[4] in
terms of the latt.er belng more foolproof, belng more compaÈible with
Algol 60, and offering the Programner the choice between copying (value

91
parameÈers) and not copylng (varlable paraueters), enabling him to trade
space agafnst Èlme. An lnterestlng hybrld beÈween value and RO reference
parameters is the "consÈ't Parameter transmisslon mode suggested by
Mltchell and l^Iegbrelt I I 10 ] : Èhe parameter fs passed by value, but the
value of the formal parameter may not be changed in the called instance
- Ëhls mechanism is not entlrely equivalent to RO reference, in Ëerms of
effect, especlally 1n the context of coroutlnes'
One difftculty wlth the procedure and function transmisslon modes
of Pascal 1s that nothlng l-s speclfled about the parameÈer llst of such
a formal parameter, and thus complete compile-time checking ls noÈ
possible (see, for example, the discussion ln t1561). PASQUAL, for
example, demands the speciflcatlon of the number and types of the
parameters of all procedure and funetlon Parameters 1n a formal
parameter list, and hence all lnvocatlons of a formal procedure or
functl-on parameter can be verified for consistency with all
corresponding actual paraneters' durlng compÍlation'

Notlce tha¡ {n those block-structured languages ln whlch the daÈa


control structures establfshed by dynamlc, expllcit parameter trans-
mlsslon mechanlsms supplement. those due to staËlc' lnplicit scope rules,
difflculties can arise tn reading and understanding programs. An attemPt
rrprlncl-ple of dlsjolntness",
.Èo avold some of these difflcultles fs the
which states that no data ltem (or eomponent of a data lten) should be
RI,l accessible ln a block under more than one name. (Violations of Ëhis
principle have been referred to as traliasing"[I51] and "sharing"[25].)
The reasons why adherence to thls prlnciple has been advocated \{ere
discussed by this author ln [101]; 1n short, ft leads to Programs which
are easler to understand and verify. The sirnplest !¡ay to follow the
princlple Ís Èo ensure that all actual parameters transmitted by
mechanisms grantlng RI^l access are disÈinct. Ttris, however, is not
enough: even 1f all actual parameter llsts contaln disjoint ldentifiers'
the principle nay be violaEed if a formal parameter galns RI^I access to
an external daËa ltern which ls also accessible via scope rules. IE is
difficult for a prograümer to detect a vlolation of Èhe laÈter kind ín a
ttrenaming
program, and, when detected, lt rnay be necessary Ëo resort to
tricks[ to remove it f rom the program. Flgure 4. 15 consists of t\'to
Pascal fragrnents illustraElng one of these trlcks: using the same name
for the external variatrle and the formal parameter. In Figure 4.15(a)'

92
the external varlable 'tatr Ís RI{ accessible in procedure rrPrr under two
names ("at' and "btt) and hence the principle of disjolntness is violaÈed;
thls has been overcome fn Figure 4.15(b) by changlng the formal
parameter to tta". Notlce that the more expl1clË forms of scope rules
discussed ln the last subsection obvlate the need for such Èrlcks ' by
allowf-ng the programmer to express the fact that the external variable
should noÈ be lnherited into the nested block 1n thls case. Also, as
discussed with respect to Euclld ín [151], expllcit inherltance enables
fatrly slnple detectlon (by the translator durlng compilatlon, and by
the programmer) of mosË violations of the princlple of dlsjolntness, by
rrextended
ensurlng that the same tdentifl-er does not occur twlce ln the
parameter list", consisÈing of the (RI^I accesstble) actual parameters for
a partlcular call, concatenated to Èhe llst of ldentiflers expllcltly
inherlted (wtth RI{ access). lÏhis does not, for example, detect cases of
an array element being aliased because the indices in two array element
expresslons occurrlng as (Ri,I accessible) actual parameters happen to
have the same value aÈ run-Ëlme - such sl-tuations can only be detected
by a run'time check.l

var a:lnteger; g a:integer;


procedure p (-var. b: integer) ; procedure p (var a: integer) ;
begin ... end; begin ... end;

besin ... p(a) ... end besin ... p(a) ... end

(a) (b)
Fleure 4. 15 Avoldin g VÍolatlons of the Principle of Disjolntness Which
were Due, in part, to Access via Scope Rules

Kleburtz [83] points out that l-ransmlssfon mechanisms such as call


by reference and call by value have the advantage that I'the evaluaElon
of any expresslons appearíng tn the actual parameters takes place before
any reference to formal parameters are evaluated ... Tkrus ali lnstances
of a reference to a formal Parameter in a single invocation of a
procedure refer to the saüe objectrr. Although Kiebr¡rtz's motivation for
his preference ls once agaÍn lncreased verlfiability of programs, the
above property of Ehese parameter transmission mechanlsms makes Ehem
preferable from the point of viers of making programs easler to wrlte and
understand. On the other hand, call by name and call by text

93
substltutlon do not, for example, have the above properËy and hence
thelr use leads Lo programs r¿hlch are more dlfflcult to comPrehend.

4.3 .2 The Data Control Model

In the previous secLion, a partlcular vlew of data control eras


developed; Èhls view conslsts of the concepts of klnd of access,
transmlssion of access, lmpliclt and expl1clÈ forms of daÈa control, and
so on. Collectlvely, these concepts represenÈ the level of abstraction
at whlch we wish to exenine the data conÈrol aspects of existing
languages and proposals, and at t¡hích the design of the data control
aspect of ACL was carried out.

Semantic models of prograrnming languages have rarely provided an


adequate coverage of their data control features; two excepLions'
however, are the Coutour I'fodel of Johnston[78] and the AccessÍ-ng Graph
Model descrlbed by Sntthtl39l. The former represents a computation as a
sequence of snapshots, whlch are transformed by the allocatlon and
deallocaÈlon of "conËours", and 1s oriented towards the description of
block-sÈructured prograrnming. languages, whereas the latter model is
based on a graph-theoreÈ1c approach, and 1s almed speclfíca1ly aÈ
solving the "nane accesslng problem": the determlnatfon of the meanlng
of a name aÈ some point in a computation.
The data control nodel described in thls section focusses rnore
closely on daÈa control than either the ConLour Þfodel or the Accessing
Graph Model, and it corresponds to the level of abstraction represented
by the dlscussion of the precedÍng secÈlon. This model is an operatlonal
one, and Ís also an rrinformatlon structure modeltttl55l (both of which
are equally true of the sequence control model), fn that the semanÈics
of a data control feaËure l-s described 1n terms of Èransformations on
certain lnformatlon structures; just as the maJor lnformaÈlori structure
involved 1n the sequence control structure was the 'rinstancett, the daca
control model is based on the concept of a "list of names'r. Descriptlons
of daÈa control features uslng Èhls model are algorlthmlc 1n the sense
that the earller descrlpÈions of seguence conÈrol features are
algorithmlc: they consisÈ of sequences of actlons to be taken and
declsion structures Eo choose whlch action 1s appropriate l-n a
partlcular case. Because of the difftculty of visuallzLng data control

94
relatLonshlps, the definltlons of data control features presented in
this thesis wtll be complemented by some examples, and Èhe data control
behaviour of Ehese example program fragments ln execution will be
explicated through the use of pict.orial snapshoÈs of the data control
structure of the executlng programs. the method of contrucLlng these
pictorl-al representaÈlons of data control strucEure, whJ-ch are a
development of those presented by Èhe author ln t1011, will also be
explalned.

Unllke the sequence control model, the data control model 1s not
specl-fic to the task of descrfblng coroutine. facllities, but rather 1s a
model of data control for languages r+hlch exhlbit block structure' as
that term was defined in Section 4.3. I . 3, and for whlch expllclt
declaration of identlfiers (say, aÈ the head of a block) J-s requíred' As
with the sequence control model, the advantage of employlng chls model
in the design of the data control aspecE of ACL l1es in the fact that lt
deals only with Ehe concePts of LnteresÈ in designlng this asPecË'
abstracË1ng a\üay from lrrelevant detail. In the context of data control,
examples of lrrelevant detalls are the Eype and value assoclated wl-th a
varlable identlfier.
For each block lnsEance, a list of all of the identlfl-ers usable
llst'l
.wlthin that block lnstance 1s defined; this 1s called the "knortn
for that block instance. IË ls divlded lnto two parts (etther of which
may be ernpty) : the "RW l1st'r and the 'R 0 llstr'. This dívlsion
corresponds to a distfnctlon bet¡¿een the kinds of contexts in which
known ldentlfiers may occur during Ëhe executlon of that block instance;
the former 1|st contafns ldentlflers corresponding to RI^I accessible
items, and the latter those of RO accessible iÈems. Associated wÍth each
block instance (and hence rvtth each known llst) is a unique ídentifier'
whlch fs asslgned in some language-specifle manner.

For a block lnstance "btt, the knov¡n list, the RW l1st, and the R0
l1st, wtll be denoted KNOI^r\, RWb and ROO, respectively. Lists such as
these are sald to have entries, and these entries ate sald to contaln
names. These names are not necessarily single identlfiers, but may be
expressions consi-stlng of a number of fdentifiers an<l llteral constants;
a primiÈ1ve predicaLe
fdentifter (n)

95
Ls provlded whl-ch evaluates to tttruett if the name t'ntt 1s an identifier,
and to t'falsett otherwise.

The plctorlal representatlon of Èhe known lists of block lnstances


wtll take the form shor¡n 1n Flgure 4.f6. NoÈlce that the name of the
block instance appears above the top leff-hand corner of the known lisÈ'
and that a double line separaÈes Èhe RI.l l1sÈ frorn Èhe Ro lisÈ.
name

Rtr'l list
known
11st
RO list

Flsure 4.16 The Pictorlal Representatlon of Block InsÈances in


Depictlons of the Data Control StrucËure of Programs

For the purposes of the algorl-throlc descrlptions, references to


entries ln lists wfll have the form:
(name) of <11st>

.which denotes the entry ln Èhe given llst which contaLns the given name;
care must be taken to ensure thaE an expresslon of the above form does,
fn fact, yield a unlque reference to an entry.
Two klnds of known list entries are dlstinguished: deflnlng and
non-deflning. Definlng entries are reserved for the names of ltems whlch
are defined ln the block correspondíng to the known l1sÈ in which Ehe
entry occurs; these ltems rnight be defined by expllcit declaration or
fuop1icitly, as ln the case of Pascal's value parameter (see 1aËer) '
lNotice that a defining entry for a varlable name in an lnstance's known
list implies that the acÈlvation record for that. instance w111 conEain
the storage allocated for that variable.l Non-definlng entries are used
to hold names whlch sirnply "stand fort'items defined 1n other blocks. In
the plctorÍal representatlons of data conErol relationships ' names
contained in defining entries will be preffxed by an asterisk ("*"),
whereas Lhose in non-defining ent.ries will not.

96
The creaÈÍon of list enErles is achetved by the prlmitlve
Lnsert(nrLrk)

whlch creates a nerl entry in the líst 'rL" (at its end), and the name "ntt
fs seÈ lnto thls entry; the kind of entry created is elther definlng or
non-def lning, depending on whether
rrkrr has the value rrDtr or "N",
respect.ively. For example, I'inserË("rR%rD)'r creaÈes a definlng entry in
the RO list of Ëhe lnstance rrbrr and sets the name ttxtt lnto the entry'

The modelalso allows Èhe transmisslon of access prlvilege between


block lnstances to be described; transmissl-on of access privilege occurs
ruhen one block ínstance b1 whieh has (some kind of) access to an ÍEem
grants another block instance b2 permlssl-on to access the item (with
posslbly a dífferent klnd of access). Thts transmisslon of access
prl-vÍlege is regarded in the model as the establishment of a link from
the appropriate entry 1n the known llsË of. b2 to the defining entry for
the item (wherever thaÈ rnight be). NoEice that the 'rappropriate" entry
fn b2 wlll be the one wlth which the transmlssion of access prÍvllege ls
rrassociated"; the nature of this 'rassociation" depends very much on the
particular daEa control feature concerned. Two Ëypes of l1nk are
disttnguished, according to the klnd of access which is allowed to the
item concerned. If bZ has permlssion to read and change the value of the
,ltem then an RW link is used, where-as lf the value of the ltem can only
be read, an RO link is used. (Clearly, 1f neither readlng nor wriËing ls
allowed, then no link exists.) In the píctorÍal representaLions, Èhese
lfnks are depicted as directed llnes from the entry in b2 Lo thaÈ 1n b1 i
a solid line ts used for an RW link, and a dashed line is used for an RO
l1nk.

Llnks between entries are establlshed using the prlmítive


l1nk(e1,e2, t)

whose effect 1s to set uP a link of type I'trr (which l-s one of


rtRl¡¡rr or

t,Rott) from the entry "er" Ëo the entry ""Z", 1f the latter is a definlng
enÈry, or to the enÈry lndicated by the llnk leading out of "u2", if it
ls a non-definlng entry. The existence of a l1nk emanating from any non-
defining enEry is assured because of the use of non-deflnlng entries: to
hold names standing for names defined in other inst.ances - consequently'
they are always ltnked to a deflnlng entry. Thus, 'rlinkrr must. establish

97
a llnk directly to a deflnlng enEry.
ttat' has
For example, conslder a program in whleh a block lnstance
RIù aCCess, under Ehe name
ttytt, to an item called ttxtt defined in a block
lnstance rrbrr (the f ormer siurply sÈanding f or the latEer) ' Now, the
actlon ttflnk(z of KNOI^IN., y of RtrIrr RO)", where 'tztt is contained in a
definlng entry, does not, establish the data control structure of Flgure
tty" itt tta" represents
4.L7 (a), but rather that of Flgure 4. 17 (b) r since
tlztt
a non-defining entry. The relatlonship flnally establtshed betr¿een
ttytt in ttAtt as
in ttctt and ttxtt in rrbrr Was made possible through the use of
an lntermediary, but this lnformatlon is not consídered relevant to the
data control structure of Ëhe program, and is not recorded. (Notlce that
Lt 1s not specified 1n Figure 4'17 r*rhether "ztt 1s RI^I or Ro accessl-ble in
ttctt.
)
b

*¡ *x -ì
I

I
I

I
I

I
I
I
a a
I
I

I
v I I

I
I

I
I
I
I
I

c c I
I
I

*2 __t _J

(a) (b)
Fisure 4.17 Transmj-sslon of Access vla an Intermediary Identífier

The prlnciple of non-Íncreasing privilege, discussed Ín Section


4,3.I, lmplies that a llnk must lead to an entry whose access wlthin
thls ttokmlng" block is greater than or equal to (in the sense of Jones
and Liskovt8ol ) the klnd of access trnplied by the tyPe of the llnk.
Sufficiently few kinds of access are dfstinguished Chat it is feaslble
to enumera¿e all possible cornbinations of lncomlng link type and klnd of
identifier access; the pictoríal representations of all three cases
allor.red by Ëhe principle of non-increasÍng privilege are shown in Figure
4.18. This princlple also requires that any llnks notionally established

98
to fntermedlary ldentifiers (although they w111 not be present ln the
ftnal daËa control structure) must conform to one of the cases of Figure
4. 18.

t-
I
I
t-
I
I
I
I

(a) (b) (c)


Fieure 4.18 Allowable Transmlsslons of Access to a Knonn Identlfier

The f irst t!,Io cases, (a) and (b) , represent the Èransmisslon of
access to an lten whfch fs RI.I accessible l-n the instance shown; Fígure
4.f8(c) represents Èhe case where the item ls RO accesslble 1n the
lnstance. In terms of the discussion of Sectlon 4.3.1, the three cases
correspond to the following binding paÍrs, resPectfvely:

(RI^I,RI,¡) (RL{,R0) (RO,RO)

all of whl-eh conform to the prlnciple of non-Íncreasing privl-lege'


FurÈhermore, since RI^I>NA and R02NA, in the sense of Jones and Llskov,
and. sl-nce all ldentifiers in known llsts are either RI,I or RO accesslble'
it 1s clear that all llnks must lead somewhere.
are placed on the type of llnk which may emanate
No restrictions
from a deflning entry 1n e1Èher part of a lcnown llst; this ls because
the nature of the relationship betneen the definlng entry and the entry
to which 1Ë 1s llnked (whÍch must, of course, be another definlng entry)
l-s very much determlned by the particular feature being descrlbed and
senslble interpretaEions can be glven to all of the four combínatlons of
link type with kínd of access for the defining enËry. On the other hancl'
the specifieatlon that non-defining entries are to be used for names
whlch stand for names defined elsewhere leads Èo the followlng
resËrlctlons for non-definlng entrles: if the non-deflnlng entry is 1n
an RI,I (RO) list, then an RI{ (RO) link must emanate frou tt arrcl this link
must lead to a deflning entry ln another Rli or RO (RO) list'

Another primitive rvhich w111 be useful in the algorfthmic


descriptlons 1s
fol1or¡(e )

99
whlch evaluates to a reference to the entry lndicated by the l1nk
leadlng out of the entry I'e". IÈ 1s a property of the model that at most
ttet',
one llnk leads ouÈ of an entry; if there 1s no llnk emanating from
then itfollow(e)rr evaluat.es to the argumenÈ tte" iÈself '
The algorlthrnic descrlpÈlons of data control features will have a
slnllar form to those of sequence control descrlpÈlons:
(1) each descriptlon will be delirnited by curly brackets "{"'}",
(2) the acÈions comprislng a single description will be separated
from each other by semicolons ";tt,

(3) actfons will be grouped together using square brackets "[...]'r,


where such grouplng 1s necessary'

(4) the condltional statenents, and the logical and relatlonal


operators of Pascal (except for "Et, see (6) below)' will be
used ln obvious lrays to express declsion structures within the
descrlptlons,
(5) the symbol 'r<-r' will be used to denote assignment,
(6) tests for list membershlp will be expressed as
(name) in <11st>

which evaluates to rrtrue" if there 1s an entry ln Ehe given l1st


containíng the given narDe, and to ttfalse" otherwlser and
(7) a construct of Èhe form

for each (control vari ble name> in <list> do (sequence of actlons)

wiLl be used to cycle through lists; it results in the sequence


of actlons being repeated with the control variable taking the
values of, successÍvely, each of the names present ín the glven
llst.

As wíth seque-nce control descrlpÈ1ons, data control descriptions


should also be regarded as the texts of macros, fn this case describing
the effecË of various evenËs concerned with changes ln the data control
structure of executing programs. Again, there w111 occaslonally be a
need f or varl-ables 1ocal to descrlpt.ions, but ln the case of data

100
control descriptlons, fdentifiers conslstlng of a slngle lower case
t'tyP"", and Èhe
letter will be used for these local varÍables; Èhelr
fact. that they are loca1 variables, should be obvious'

4.3.3 Data Control in P revious ProeramminP Lansuaqes

4.3.3.1 Introductlon
This sectl-on wtll descrlbe daÈa conÈro1 ln some programmlng
languages whtch do not have coroutlnes, as well as thaË in programming
languages wiEh a coroutlne facillty. The reason for thls is the facÈ
that data control has generally receÍved little aEtenElon in the design
of coroutine facilities in the past and consequenÈly their data conÈrol
aspecË tends to be noE as lnnovatlve as their sequence control aspect.
The lnteresting and innovative ideas ln data control are ofËen to be
found 1n languages wlthout coroutlnes, and these ideas, where relevant,
are dlscussed in tliis sectlon. One programming language wiÈhout
coroutlnes whlch ls di-scussed here ln some conslderable detail 1s
pascal; Èhe major reason for examining Pascal to thls extent is that
data conËrol in ACL o\¡res rnuch Ëo that 1n Pascal, although they also
dlffer J-n signlflcant \^¡aYS.

_ As the descrlptlon of daEa control fn Pascal demonstrates' to use


the data control model to preelsely define daÈa control in a programming
language occuples conslderably more space than does a description of a
Language's sequence control aspect using the sequence conËro1 model;
consequently, the data control model wfll not be used to provide full
descrÍptions of data cont-rol in all of the languages dlscussed in this
section, although this could have been done. Sometines a verbal model
concentraÈing on a small, speclflc set of characterist.ics ls more useful
in Èhe context of the comparlsons whtch have to be made; the comparison
of explicit scope rule schemes in Section 4.3.3.3 provides a good
example of the utll1ty of such models.

4.3.3.2 Pascal

are used to refer to varlables '


In Pascal[75] , identlfiers
constants, types, and procedure and functlon deflnltlons, and to denote
the values of scalar (enurnerated) types; at leasË soue data control

101
feaÈures apply to all of these classes of ldentlfler. Labels in Pascal
programs are denot.ed by unsigned lntegers, raÈher than by idenÈiflers,
but the accesstblllty of labels ls also governed by data conErol
feaEures, and hence unslgned integers denoÈing labels will be regarded
as identlflers for the purposes of this discussiorr. Any unsigned
integers appearlng by Èhemselves in representations of known lísts may
be assumed to be those of labels.
Another use for ldentlfiers ln Pascal ls to denoEe the fields of
records, to allow the selection of a particular field of a record
varlable; these ldentifiers wfll not be included in the known lists of
Pascal block instances, as they are noÈ regarded as being part of the
vocabulary of the instance, but rather of that of the record variable
concerned.

For the description of data control ln Pascal, another priurltlve ls


introduced lnto Ëhe data control model; it ls
class (1)

WhiCh eValUateS tO one Of "1¡afiablett, rrCOnStAnttr,


tttypatt, ttprOCedurett,
Itf unctlontt, ttlabeltt or ttScalart', depending on the class of the

ldentlfier rrlrr.

Pascal is a block-structured language, and consequently changes in


the daÈa control structure of an execuÈ1ng Pascal program occur only at
block entry and exit. Known lísts are only associated with lnstances of
procedures, functfons and maln programs; there are no "anonymous blocks'l
in Pascal, as Èhere are in Algol 60t1121. The only other kÍnd of block
(unlform referencing environmenE) which can occur ln a Pascal program is
the "with statementrr, whlch provldes a üeans Èo dlrectly access Èhe
fietds of a record variable. The data control effect of a with sÈaÈement
can readlly be descrlbed usíng the data conErol model; hor^lever, 1t has
been omltted from thls discusslon because of the length of Èhe
description of data control ln Pascal, and slnce f-ts lnclusíon is not
necessary 1n the context of the design of ACL (in which the with
statement ls present in preclsely the same form as ln Pascal).

Since knownllsts are only associated wtth lnsEances of subprograms


which already have an ídenLifl-er assocíated with them (procedures,
functlons, and the maln program), this ldentifier w111 be used to name

102
known llsts for fnstances of that block; tf roultiple lnstances of the
block occur, or are expeeted, this naüe ls subscripted' eomroencing at.

one.

Block exlt will simply lnvolve the deletfon of the known lfst for
that block lnstance, and of all of the ltnks leading out of it; it Ís a
property of the descrfptlon of data control ln Pascal thaÈ no llnks will
be leading lnto that known llsÈ when Èhe deletfon occurs. This ls
because known llsts (corresponding Èo block insEances) wiJ-l be created
and deleted in a last-in-fírst-ouÈ fashlon and Èransmlsslon of access
prlvilege is always frorn a pre-existing l1st Èo a newly-creaEed one.

Thus, the descriptlon of daLa control 1n Pascal w111 focus on block


entry, and the data conÈrol effect of block entry is composed of the
effects of the following data control features:
(1) local declarations'
(2) value parameters'
(3) variable parameters'
(4) procedure and functlon Parameters'

(5) the scope rules, and

(6) the return of the value of a functlon.


the effect of each of these feaEures r.¡ill
The events representlng
be labelled L, V, R, P, S and F, respectively. An algorfthnlc
descrfption w1ll be given for each of the events; Ín cases where the
particular event does not aPply (for example, R when there are no
variable parameËers, or F tn the case of a block whích 1s noÈ a
function), that event should have a null effect.
In addition Ëo Ehe llsts already defined, a furEher five lfsts (any
or all of which rnay be enpty) are assoclated with every block insEanee,
Itblr.

(a) LOCA\: a ltst of the declared locally to the bl-ock; thts


names
llst lncludes the ldentlflers of procedures and functions
declared 1n the block, and those enumeraËed in any scalar types
declared ln Èype or variable declaratlons ln the block'

103
(b) vA\: a ltst of Ehe formal value parameter names for the block'
(c) VAR6: a list of the formal variable Parameter names for Ehe

block,

(d) PRo$: a l1st of the formal procedure parameter names for the
block, and

(e) FUNC6: a l1st of the forual function parameter names for the
block.

The primltlve
actual (e)

Ls also lntroduced; it ylelds the nane of the actual Parameter (not


necessarily a simple ldenÈifier) corresponding to the formal parameter
name contalned tn the ent.ry t'e", for the block entry currently being
descrtbed. Thus, valid arguments for this prlmitive wfll only be
references to entrles in the lisEs VAh, VAR6r PROCb, and FUN%, where
rrbrr Ís the block ínstance being entered.

It w111 always be assumêdthat Pascal programs whose daEa control


sLructures are being described are legal according to the definltlon of
Pascal given by Jensen and l{lrtht75l. Thus, for example, it can be
'ássumed that, for every block instance "b", no name will appear ln more
than one of LOCA\, VA\, VARb, PRO% and FUNC'' or more than once 1n
any of Èhese lists.

As will be seen later (ttReturning Values f rom FuncÈlonsr'), the


chosen descrlptfon of data control in Pascal wí1l sometimes result in
the same name appearing twlce in a known 11sÈ, once 1n the RI{ part and
once in the RO part; consequenÈly, expresslons of Èhe form

(name) of KNOIIN.

may not necessarily yteld a reference to a single entry in the glven


known l1st, and hence care should be exerclsed in thelr use' to avoid
the introducËion of ambiguities.
I(nownlists wfll always be added to the boEtorn of the plctorlal
representaEions of data control when lnt.roduced, and since blocks in
Pascal are enÈered and left ln a last-1n-first-out order, lÈ 1s clear

r04
Èhat Èhe known llst of the currently executlng lnstance w111 always be
boÈtommosE l-n a slngle column of known llsts'

Now, each of the d.aÈa conËrol features of Pascal listed above will
be treated in turn. For the sake of consistency in the varÍous
algorfÈhmlc descript.lons, sÈandard meanings are assumed for the
followlng names:
. ttcalledtt is Èhe name of the lnstance belng entered,

. trcaller" is the name of the instance r¡hich caused the creatLon of


trcalledtt by calllng lt,

. t'definltion'r is the name of (the definitLon of) the block of whlch


Itcalledtt ls an instance, and

. ttdefinertt is the name of Èhe lnstance whlch contains the definlng


entry for ttdeflnition", and hence i-s the most recently created
lnsËance of Ëhe block which fnmediately textually encloses
rrdef Ínitlonr'.

Lo'ca1 Declarations

!ül-thin lnstances of the block in whÍch they are defined' the


.f,ollowlng kinds of access apply to ldentlflers belonglng to the varl-ous
classes:

R['l accessible: variables

RO accesslble: tyPes, constants, labels, functions'


procedures, scalars

Ihus, in thefr defining instances, variable identifiers occur 1n


the Rtr{ l1st, and identifiers of all other classes occur in the R0 list.
(NoËe tha¡ to have RO access Èo a procedure or function ldentifier is
1nÈerpreEed as permission to call ÈhaÈ subprogram' removlng Ehe need for
a separaÈe ttexecuËett kind of access . ) I'urthermore, transmission of
access in Pascal follows the prlnciple of non-l-ncreasi.ng privilege, and
so the only identlfiers v¡hlch will ever appear ln the RI^I list w111 be
those of varlables.

105
The actlons taken by Èhe evenE descrlbing the data control effect
of local declaratlons are simply to lnsert a deflnlng entry for each of
the locally declared names , in elther the RI^I ltst or the RO ll-st,
dependlng on lts class. Ttris event ls

L = { for each n ln LOCALcalle¿ @


case class(n) of
varfable:
lnsert (n,RWca1l"6, D) i
tyPe, constant, label, function' procedure, scalar:
lnsert (n rR0""11"¿ rD)
end )

Notice, ln partlcular, thaÈ Èhe identl-fier of a procedure or


function is defined 1n the block which textually encloses its own block.
Examples of the data conÈrol effect of local declarations can be
observed in the plctorial representations of data control strucEure
presenÈed Ín subsequenÈ sectlons, especlally those shown in Flgure 4.32.

Value Parameters

Those sections of the formal parameter l1st of a Pascal subprogram


which are not prefíxed by a keyword (such as 'tvarrr, see the dlscusslon
on varlable parameÈers), conslst of so-called ttvalue parameÈers'r. This
data control feature of Pascal is descríbed by the follo!'ling event:

V= { for each f in VAl"alled @


I a <- actual(f of VAL"oUed) i
lnsert (f ,RWcall.¿rD) i
1f (no!. (a ln KNOW""lls.)) or (class(a) =functlon)
then [ 1f not ( (a) tn KNOW""tt"r)
then lnsert( (a) ,RO""11"r'D) i
link(f of RWcalled, (a) of R0ca11er, RO) l
else l1nk(f 9! RW.,11s¿, a of KNOltrNcaller, RO) I )
As explained earller, a formal value parameter is regarded as an
implicltly deflned variable local to the block Ín whích tt is deelared'
which 1s initialízed to the value of the actual parameter; Thus, a
deffning engry Ls created tn the RI^I list of the block belng entered, and
the name of the formal parameEer ls set fn 1t (see the penulÈimate I1ne

106
of Èhe above definltion). Once Èhls entry has been lnserted, 1t must be
connected via an RO link to Èhe actual paraueter entry, to aIlor¿
initlallzatlon of the implicltly defined loca1 varlable. There are'
hor¿ever, t$ro cases r¡hlch require specLal attention (if neither of these
occur, then the formal parameter enEry ls simply linkecl' vfa an R0 link'
to the actual parameter enÈry); Ehese speclal cases are:
the actual parameter to a formal value Parameter
name correspondÍng
ldentffter need not itself be a stngle identifier (1t rnay be any
expresslon of Èhe appropriate type) or 1È may be a standard
ldenÈifier (such as ttfalse", see Flgure 4.31) 1n either case,
there may be no enÈry ln Èhe known list of the calling instance
which contains the act.ual parameter name, and

even if the actual parameÈer name is a slngle identifier, 1t may be


the identlfier of a functlon, ín which case it fs important to
slgntfy tha¡ a call on Ëhe functfon ls íntended (rather than the
transmission of the functlon name see the laÈer descriptlon of
functlon parameters).
In both of these casesr'a special kind of deflning enÈry ln the Ro
l1st of the call1ng instance is used as Èhe actual pararneter enÈry: one
whlch contains a parentheslzed verslon of the actual parameter name. For
éxample, lf the expression "xfy[ rnlere Ëo be given as an actual value
paralueter, then an actual Parameter en¡ry conÈainíng the name "(x+y)tt
would be used. These names are parenthesized to distlnguish them fro¡n
other deflnlng entrj-es and to save posslble confusÍon between' say, an
actual paramet.er expresslon rrl rr and a Iocally declared label
rll rr . An

entry containing the parenEhesized actual paramet.er is created if one


does not exlst and then an RO tlnk is esÈablished between formal and
actual parameter entries. Ttre primltfve predicat.e rrídentlf iertr will
re¡urn the value ttfalse" when applled to an ldentlfler enclosed in
parentheses; lt ls assumed that actual parameter expresslons wlll not
already be enclosed 1n a (redundant) Palr of parentheses'
The above nethod of handll-ng these sltuaEions may lead to these
entries belng present ln known lists long after the block fnsLance Èo
which Ëhe value parameter sras passed has terminated. To delete these
enËries on the terminaÈion of the called block instance would noE be
dlfflcult ln the case of Pascal, although lt would add to the conplexiÈy

107
of the effect of block exft (which currenÈly has the sole effecE of
deletlng the. entlre known l1st for the l-nstance whl-ch 1s ternlnating);
deletlng these entries is more dífflcult ln the case of ACL, since lt is
possible for one of these entrles contalnÍng a parameterized name to
have more than one llnk leadlng to lt. In vierp of these disadvanEages'
Èhese entrfes r¿ill noE be deleted, and their occasional presence ln a
known l|sË after their usefulness has ceased, will be tolerated.

Any identlflers appearing in a parenthesized expresslon introduced


1nËo a knor¿n li-st are lnterpreEed according to the appropriate entries
ín that known list. Thus, the ÍnÈroductlon of thls speclal entry in the
above cases accurately reflecÈs Èhe notlon that the expresslon ls
evaluated in the calling block, and access to the result of Ëhis
evaluation is allov¡ed to Lhe called bl-ock.
The program fragment shown in Flgure 4.19 will be used to
lllusÈraEe the data control effect of value Parameters. Figure 4.20(a)
shows the da¡a control structure of the execut.ing fragmenÈ lmrnediately
after an instance of the procedure ttq", also called ttqtt, has been
created; as in the other data control structure representatlons to be
glven |n lllustrating the lndivldual data control features of. Pascal'
only those known llst entries r¡hlch are speclfically of fnterest are
names. NoËice the defining entry ln the RW
,shown with thelr containlng
l1st of rrqrr for the local varlable t'altt, and another, thls time in the
RO list, for the local consËant identif 1er.
t'a2". Once Èhe lnstance rrqrr
has called procedure rrprr to creaÈe an lnstanCe ttPtt, the data control
structure depl-cted tn Figure 4.20(b) resulÈs. The procedure call has
caused the creation of defining entries in the RW list of the new
instance for each of t,he formal value parameters, and the creatlon of a
defintng entry Ín the RO lÍst of "q" for the one actual parameter name
not already 1n the known list of rrqtr. Furthermore, the formal-acÈual
paraìneter correspondences are shown by the three RO línks which have
been established.

108
Drocedure (f I: Tl;f 2zT2;f3: T3);
p

besln .. . en4; iof p)

D rocedure q;
consq a2 = .. . i
var al : T1;
begtn .. . p(al ,a2ra1+a2) end; {of q¡

Flsure 4.19 A Pascal Fr agment lllustratlng Value Parameters


q

*al *al

*a2 *a2
¡t (a 1+a2)

_t_ ¡tf
I
I
I
*r2
L- *f3

(a) (b)
FÍgure 4.20 Data ConÈrol Structures Occurring durLng the Execution
of the Fragment of Flgure 4.19
Note that the access privilege to Ehe actual parameter entries '
granted by "q" í-s, ln each case, consistent l^¡ith the principle of non-
l-ncreasing privilege; the access privilege to the first actual parameter
corresponds to the binding pair (RI^I,RO) and that to the oÈher actual
parameters correspond to the binding pair (R0'RO). Notice also Ehat' in
this slnple example, the acËual parameter entrles are all deflnlng ones;
if any \dere non-defining enÈrles, then the link from Èhe correspondlng
formal parameter entry would lead Eo a (deflning) entry in a known list
other than that of the calling lnstance.

Varlable ParameÈers

Sect,lonsof the fornal parameter llst of a Pascal subl:rogram whlch


are prefixed by the keyword "vart' consist of so-called ttvariable
parameters'r. The effect of thls data control feature of Pascal is

109
described by the event:

R= { for each f in VAR"alled do


I a <-actual(f of VÆ"alled)i
Lnsert (f , Rf{""11"¿, N) i
llnk(f of RWcalled, a of RW""ller' Rlr) )

A formal varlable parameter name ls regarded as sËanding for, or


referrlng to, the corresponding actual Parameter, whÍch must be a
variable (and thus nusE occupy an entry ln the RtrrI l1st of the calling
l-nstance). Thus, a non-defining entry 1s fnserted ín the RW lfst of the
fnstance being entered, and thf s ls llnked via an RI.I l1nk to Ehe
corresponding actual parameter entry; thls slgnifles that the calling
fnstance has Rll access, under the formal parameter name' to the acËual
parameter, which 1s also (RI^I) accesslble in the calling lnstance. Of
course, if the actual parameter entry is a non-definíng oner "llnk" will
establlsh a 1lnk dlrectly to Ehe entry lndlcated by the link exrending
from the actual parameter entry. It is clear that the 11nk esÈabllshed
fn the above definition fs conslstent with the prlnclple of non-
increaslng privilege, since 1t corresponds to t.he binding palr (RI'I'RI^I).

Flgure 4.21 shows a program fragment whlch wtll be used to


illustrate variable parameters. Figure 4.22(a) depicts the structure of
'án lnstance of procedure rrqrr and Flgure 4.22(b) lllustrates the daÈa
control effect of thaÈ lnstance calling procedure "ptt, Ín so far as the
slngle varlable parameEer of ttp" i" concerned. Thls effect is to set up
a non-deflnlng entry, contalnlng the forual parameter namer in the RW
lfst of the called fnstance, and Èo establlsh an RhI llnk from this enËry
to the actual parameter enÈry, ttatt, in the lnstance ttqtr.

procedure pt¿ar_ f :T);


besln ... enc!; {of p}
D rocedure q;
var a:T;
bestn ... p(a) ... end; {of q}
Fieure 4.21 A Pascal ÏragmenË lllustratlng Varlable ParameÈers

110
*¿ *6

(a) (b)
Figure 4.22 Data Control Structures Occurring durlng the ExecuÈlon
of the Fragment of Figure 4.21

Procedure and Functlon Parameters

Those sections of a Pascal subprogram's formal Parameter l1st


prefixed by "p-roced,tr." contain Èhe names of procedure Parameters, and
those prefixed by "frnctiqn" give the names of functiolì, parameters. The
data control effect of these parameters ' whlch are grouped togeÈher
because of their slmllarlty, is deflned by the event:

P= { for each f fn PROC."t1.¿ do


- t a<-acÈual(f of PROC"rllud)i
tnsert (f , RO.*11"¿' N) i
llnk(f of Rocalled, a of Ro"rller, RO) l;
for each f in FUNC""1t.U do
I aêactual(f of fUNC""11.¿)i
lnsert (f ,ROca1l"¿, N) ;
link(f of ROcalled, a of Ro"rller, RO) I )
A formal procedure or function pârameter identifíer stands for the
name of the proeedure or functlon referred t,o by the corresponding
actual parameter, in much the same way as a formal variable Parameter
Ldentifier stands for that of the variable referred to by tts actual
parameter. ConsequenËly, each of the loops ln the above definition 1s
rather simtlar to Ehat. contained tn the definltíon of the event R: a
non-defintng entry ls lnserted in the R0 llst of the block lnstance
bel-ng entered and the formal parameter name ls set Ln 1t, and then an R0
11nk is establlshed from thl-s entry to the actual parameter entry, whlch

111
must be tn the part of the known list of the calling lnstance. Agaln,
RO
the 1lnk established 1s consl-st.ent wl-th the prlnciple of non-lncreasing
privileger the relevant blndlng palr being (RO,RO).
The program fragment of Ffgure 4.23 conÈalns examples of both
procedure and functlon parameters, and Figure 4.24 depicts some aspects
of the daÈa conÈrol structure v¿hlch night be exhiblted by a progran
conËalnlng thls fragment, before and after an insÈance of procedure "q"
ca1ls procedure ttp". Fi-gure 4.24(b) shows Ë\.to non-definlng entries
inserted into the RO ltst of Ehe called instance, whlch contain the
formal parameter names, and are RO linked to thelr respectlve acËual
parameter entrles, in this case located in (the Ro ltst of) the calling
ins tance.

procedure p (procedq¡e f p; f unctl-on f f : T) ;


begin ... end; {of p}
procedure q;

procedur:e a p; begin ... end; {of aP}

function af:T ; begln ... end; {of af}


begtn .. . p(ap,af) ... end; {of q}
Fiqure 4.23 A Pascal Fr agment Illustrating Procedure and
Function Parameters

*ap *aÞ
*af I
I
*af -t
I

I
I
I

I
I

I
I
L fp I

ft _)

(a) (b)
Ffgure 4.24 Data Control Structures Occurring durlng the Executlon
of the Fragment of Figure 4.23

LT2
Scope Rules

Slnce the lists LOCAlcalled, VAlcalled, VARcalled' PROCcalle¿ and


FUNCcaUed are disjolnt from one another in the case of a legal Pascal
program, the event.s L, V, R and P may be allowed to occur l-n any order
when computing the data control effect of entering a partLcular Pascal
block. Once the effects of all of Èhe above events (l-ncludlng any null
effects) have been evaluated, then the compuÈat.lon of whieh identifiers
are fnherlted ínEo t'calledtt from Ehe rnosÈ recently created instance of
lts textually enclosing block (that lsr trdefinerr'), can be carried out;
thLs computation 1s the effect of the evenË S. For reasons whlch will be
explained 1n the next subsectlon, the evenL F (corresponding to the
return of a function's value) must have lts effect evaluated after all
of L, V, R, P and S; Ehe partial ordering on these evenÈs implied by the
above discussion ls suromarfzed by the precedence graph shown ln Flgure
4.25 .

Fleure 4.25 Tt.e ParElal Orderlng on the Events Comprislng the Data
Control Effect of Block Entry 1n Pascal

The effect of the event S is glven bY:

S = { f or each n 1n RWd.f irr., 3o


ii not (n in KNOW.*ll"¿) and class(n) # f unction then
I insert (n,RWcall.¿,N) !
link(n of RW""lled, n of Rlf¿u¡arr"r, RW) l;
for each n ln Rou"ttrrut -ùo-
Íf not (n ig KNON"rll.d) and ldentifier(n) then
I l-nsert (n,ROcall"¿, N) ;
ltnk(n of RO"aIled, û of Rod.ftrr"r' Ro) I )

113
Any ldentlfiers lnherited vla the scope rules stand for items qrhose
definlng entrles occur ín the kuovrn lists of lnstances oÈher than
ttcalledt'. As with the other cases of 'rsËand-inrr idenÈlfiers discussed
prevlously (variable, procedure and function parameters), a non-deflnlng
entry ls fnserted in the same part (RW or RO) of the known llst of
t'calledtt as the correspondlng entry resldes 1n the known list of
t'deflner", and the ldentlfier by which the ltem is known in ttdefinerrr is
lnserted 1n this neï{ eritry. The two enÈrles are then llnked using a link
of the same kfnd as Ëhe part of the known llsts to which they belong.

The deflnitlon of S contalns two loops: one whlch scaris Èhrough the
RhI l1st of ttdeffnertt and another which scans through lts RO list. Not
all names present ln the RI^I 11st of "definertr, but not in the known list
of 'rcalled", are inherlted - the method used for modelling the return of
functlon values (see later) lncludes the lnsertion of a deflning entry
in the RI4I list of Ëhe function lnsËance, and Ëhe name in this entry
should never be inherited by a textually enclosed block lnsEance. This
l-ntroduced definlng entry, in fact, holds the funcLion ldentifler' and
hence the Èest for r'¡hether to lnherit a name from Rl,trU"fLner includes a
test. for ¡¿hether the name'1s that of a function. (Recall that the
legttírnate enÈry for the function entry will be in the RO llst of the
functlon lnstance, if at all.) In scanning Ehe RO list of ttdefiner",
ánother exception must be remembered: any enËrles which have been
Ínt,ro<luced into this list because t'deflner" has called subprograms wlth
actual value parameters which r+ere noE slruple identlfiers (see earlier
dlscusslon) should noE have Èheir contents inherlted lnto ttcalled".
These entries are excluded from the actlons of the second loop 1n the
definition of S via Èhe test "ldentifier(n)", which will fail in the
case of any name surrounded by parentheses.

Nottce that the definitions of R, P and S show very clearly the


similartty of the data control effect of, on the one hand, variable,
procedure and function parameters, and, on the other hand, access to
variabl-es, procedures and funcÈions vla the scope rules. The differences
between these È\ìro groups of data control features are also emphasized:

(a) paraneters are used to transuit access privilege from the calllng
to Èhe called instance, whereas, 1n the case of the scope rules,
this transmission is from an instance of a textually enclosing

rr4
block to an insÈance of the lnmediaÈely textually enclosed block'
and

(b) pararneÈers admlt the posstblllly of an ltem being knorvn by


differenü names 1n the trùo instances between which Eransmission
of access to it occurs.

This demonstrates the ablllty, also observed wlth Ëhe sequence


control model, of models such as thls one to facilltate the comParison
of programming language feaÈures, both v¡ithin and between languages'
Figure 4.26 consists of a Pascal fraguent which v¡111 be used to
Lllustrate the effect of Èhe scope rules; for the sake of sirnpliciÈy'
the calling block is also that which immediately textually encloses the
called block (that ls, "deffner" and "callertt cofnclde ln this case) '
Figures 4.27 (a) and 4.27 (b) depict the data control structure
inmediately before and afÈer procedure rtqrr is called from withln an
lnstance of proced.ure t'p", respectívely; the ldentlflers of the varlable
ttvtt, the Èype ttTtt and the procedure ttqtt are lnherited into the instance
ttqtt, Whereas Èhose of the label trltr and the constanE ttctt are noË, belng
already present in the known list of t'qtt hrhen the event S is evaluated.

label 1; const c = ;

type T = , varv:T;

{of q}

begin q(c) ... end; {of p}

Fl-sure 4.26 Pascal Fr agment Illustrating the Scope Rules


^

115
P

*l *l
rtg *c
*T
I
*T -l
* ,!q -{-r
rl
ll
ll
lt
tl


L *c Ir
¡l
¡l
tl
tl
ll
ll
*l lt
T -Jt
q ____l

(a) (b)
Fieure 4.27 Data Control Structures Occurrlng durlng the Executlon
of the Fragment of Ftgure 4.26

Some special mention must be made of the tnheriÈance of names into


the rnain program block of a Pascal program:
(1) it 1s convenlenÈ to regard the mafn Program ídentifler as bel-ng
defined 1n a flctltlous block which surrounds the maln program
block; however, thls idenEifler is never lnherlted lnto instances
of the maln Progran block, and so recursion at the program leve1
is noE possible' and
(r1) rrstandardtr identifÍers are also regarded as belng defined in the
fictltious block menf-íoned above, but these can be inherlted inËo
the mafn program instance, and, via Èhat lnstance, lnto other
fnstances; to sâve having large knov¡n 1ists, these sËandard
ldenÈlflers \^till not be inclurled in knorn¡n lists unless an
lnstance transml-ts access prtvllege to ít by some means other
than scope rules - this will not happen very often' since it 1s
not uncommon for standard procedures and functions to be
forbidden as actual procedure or functfon parameters (for
example, ln 867OO/87 700 Pascalt13ll and Pascal 6000-3.4175J), and
there are no standard variables; however, for example, a boolean

116
constant as an acÈual value parameÈer w111 cause the lncluslon of
tt (true) tt or tt(f alse) tt in a def lning entry ln the calllng
lnstance's knovrn list, because of the deflnitlon of the event V.

Retu rnlne Values from FuncÈions

An lnstance of a Pascal functlon can only ret,urn a value provided


Its deflnitlon ldentlfier l-s (RO) accessÍble in the instance; for
example, the functfons shown in FLgure 4.28 cannoE return values,
whatever statements appear in their blocks. Thus, the event descrfbing
Èhe data control effecË of returnLng a functlon's value must be
evaluated after all of the events L, V, R, P and S have been evaluated,
at which polnt it will be clear whether or not the function ldentifier
Ís accesslble tn thls lnsÈance of the function (this precedence relation
Ìras mentloned earlier and fs shown in Flgure 4.25). This data control
effecÈ will be null 1f the instance betng entered is noË ËhaE of a
function, or if the functlon ldentifier ls not accessible.

functlon f 1: T1
vdr f L;TZ;
begin ... end; {of ff}
f unction f.z(f 2: T2) : Tl ;
begln .. . end; {of. f.2}

Fleure 4.28 Ex amples of Pascal Functlons whlch Cannot


Return a Value

On entry of an inst.ance of a functlon which can return its value' a


special deflnlng entry ís created in the RII list of the lnstance' to
hold Ehe value of this instance of the function, as thls value ls belng
built up; this entry is not quite an lmplicltly-defined variable' as in
the case of a formal value parameter, since it.s value cannot be read
(any such at¡empt fs lnterpreted as a recurslve functfon call), only
written. The obligation of the function instance to wriËe Ehe value of
thls wrlte-only varlable lnto the call1ng instance on terminatlon l-s
lndicated by establlshing an RI{ ll-nk frorn the introduced entry to the
ghole of the call1ng lnstance (that ls, to no entry ln partlcular)' The
data control effect of the obligatlon to return a function value ls
thus:

117
F = { if class(deflnltlon) =functlon and
follow(deflnlt,ion of RO"alled) = definltlon of ROUuftner then
I lnsert (def lnttlon rRWcall"¿,D) ;
lfnk(def lnitlon of RW."ll.¿, Ì¡hole of KNOhrN"aller, RW) I )

whlch lncludes an example of a foru of entry not. encountered before


("rho.fe. of <ltst>") r¿hích has the obvÍous meanlng; a link to the ¡.¡hole
of an lnstance 1s depicted in the picEorlal representaElons as a l1ne
leading Ëo the base of the corresponding known list. Notlce that' for
functions tha¡ can return a value, the functlon ldentlfler wl-ll aPpear
twlce 1n the known |1st, once (a deflning entry) in the RItt l1st and once
(a non-defining entr/) 1n Èhe R0 llst.
A more precfse descrlption of the data control effect of returnlng
the value of a funcÈion would be possible by:
(a) f.n¡roducing a I^IO list for funcElon LnsËancesr to hold the wriEe-
only varlable 1n which the function value ls bullt up,
(b) havtng a special entry tn the known llst of the caller,
contalning Ehe expresslon which lncludes the functlon call, and
(c) using a tr{O lfnk to Joln the above tno entrles, indicaEing thaE
the functlon inst.ance only has sufftcfent âccess prlvilege to the
- entry described Ín (b) to copy the functíon result 1nËo lt.
It 1s thought thaE the extra complexity wroughË . on the model by
these changes is not warranted, in vler,¡ of the facE that ft ls only
needed for a üore preclse descriptlon of thts one feature of Pascal.

,A,s an example of a Pascal functlon vhich can reÈurn a value'


consider that fn Figure 4.29. Ffgure 4.30(a) shows the data conErol
st.ructure durlng the execution of the fragment of Figure 4'29,
immedlately before the functíon ttf" is called from withln an instance of
the procedure "q", which was called from an instance of procedure "P",
rrftr is
and Figure 4.30(b) depicts the situaÈion lmmecliately after
called. NoÈe thaf the known l1st of the function lnstance contaÍns tlro
occurrences of its own deflnitlon ldentlfier - the RI^l accesslble one
belng llnked Eo the callfng lnstance "q", and the R0 accessible one
l-inked to Ëhe deflnLng entry, in "P", for the function's definltion
l-dentlf ier.

118
Drocedure p;

functlon f:T;
begln end; {of f)

Drocedure q;
begin .. . f ... S!4; {of q¡
begfn .. . q ... end; {of P}

Fisure 4.29 Pascal FragmenÈ Contalning a Function


^

r- *f *f
T
I
I
*q - --r
I
I
I
I
I
I
I
I
I I

I I
I I
I I
I
I
I
L_ f. f I
I
q q

L- r.
q __l

(a) (b)
Ff-sure 4.30 Data Control St.ructures Occurring during the Execution
of the Fragment of Flgure 4.29

A Conplete ExamÞl.e

In thls sectfon the execution of a Pascal program wlll be traced by


givlng complete representatlons of 1ts data control structure (ttdata
conÈrol snapshots'r), unlike the partlal ones used so f.at, and thus the
combined effects of the varlous data control features w111 be
demonstrated. The program to be sÈudíed 1s shown ln Flgure 4.31.

119
progran p (outpuË);

consÈ two = 2; var b : lnteger;


functlon f (b: boolean) : lnteger;
begln
1f b the-n f := two*f (false) else f := 3

end; {of f}
procedurq x(var. p l: integer);
begln p1:= f(crue) end; {of x}

begin x(b) end. {of p}

Flgure 4r11 4 ConpleËe Pascal Program

Figure 4.32 provides a trace of the data control behavlour of the


prograu, by depíctlng the data control structure after each block entry.
FÍgure 4.32(a) represents the situatlon afÈer the main program "p" has
been entered; the known list of Lhe lnstance "ptt contains the names of
the four locally declared items of the main program, but not the name of
the maln progran ltself r Dor of any of the standard identlfiers
mentioned. The main Program then cal1s procedure rrxrr and the data
control effect of this call is shor¿n 1n Flgure +.32(b); Ehis effect is
eomposed of the lndivtdual effects of a varfable parameter and the scope
rules. [Flgure 4.32(b) clearly demonstrates a vlolation of the prlnciple
t'p" iS
of dlsjointness, discussed in SectÍon 4.3.f : 'rbrr of the irrsl-ance
ttb". I The
RIt accesslble in the lnstance "xt' under the two names "pltt and
lnstance rrxrr then calls f unctlon rrf rr gfvlng rise to the data control
structure of Flgure 4.32(c); Èhls function fs recurslve and so the
subscripted name "fl" is used for the lnstance creaËed. The effecÈ of
entering the function instance 1s the combined effect of the value
parameEer (lncluding Ehe creaËion of a speclal entry in
ttxrr for the
actual parameter "true", which, being a standard idenÈifÍer' T{as not
already ln the knorrn list), the scope rules (notlce, 1n particular, that
ttb" of ttp" í" noÈ Ínherited) and the fact that thls function can return
tttruett, a
a value. Since the Value of the actual parameter to ttfltt was
recursive call (with t'false" as the actual paramet.er) takes place, which
results in Ëhe data control structure of Flgure 4.32(d); the effect of
thls block entry 1s s1m1lar to Ehe previous one.

L20
*b *b
* Ewo * two -l
*f
*¡¡
*f
*¡¡
ìttt
rl
I
I

I
x l1 I
l¡ I
l¡ I
b I

ttJo -i I J
f - -¡J
x I

(a) (b)

*b *b
*Èwo -1 *Èvo I
--'l
*f -t *f
rt¡¡ -tir rt¡¡ a
I
I
¡l
tl I

x ll x I
rl I
I rl I I

tl b I

¡l __!
tvro -f1 à I

f --|-t f --¡-ì
x -ri I
x I

-
I
It ( I
Èrue
r
I
* ( true) I
I
I
I
I
I
I I
I I
I f I
I
I Í. I
I I I

L *b I L *b I

*f I
I
*f I

tlro -l -J
J
two
f
--r- -1
I

r
x -J x
r
I
* (faIse)
I
I
Í2
I
L *b
*f
Èflo
J
f
x

(c) (d)
Fisure 4.32 Data Control StrucEures 0ccurring durlng the Execution
of the Program of Figure 4.3 I
Slnce the actual paramet.er to Ehe funcElon instance 1s trfalset' in
the second case, that lnsËance ("f2") then termlnaLes, eausing Ehe
deletion of the known l1st labelled ttf¡t'. Next, the oÈher functlon
lnstance termlnates and lts known list ls deleted, followed by Èhat of
the Lnstance trxrr, and finally that of the rnafn program lnstance.

r2l
4.3.3.3 Exp liclt Scope Rule Schemes

One area of da¡a control 1n programmlng languages 1n whl-ch there


have been a number of recent developments 1s that of expllclt scope rule
sclremes, whlch were mentloned briefly 1n Sectfon 4.3.1.4. Some proposed
expll-cit scope rule schemes will be compared ln thl-s sectlon, and the
basls for this comparlson will be Ëo classlfy then as to qrheÈher or noÈ
the following perml-ssions and agreements need Èo be explicitly stated:
(a) declarant i nhe-rltor oermlsslon. whl ch 1s permlsslon by the block
fn whl-ch an item is defined, for other blocks to access Èhe ltem'
(b) lnheritor /lnheritor oermission. whtch l-s permlssion bY a block 1n
r¿hich an ltem ls accesslble (other than tts definlng block) ' for
other blocks to access Èhe itemr and
(c) lnheritor agreement' whlch ls agreemenË by a bl-ock that lt wishes
access to an ltern whlch it is permltted to access.

In the case of expllcit sËatements of the f Lrst tr.lo klnds, Èhe


permlssion granLed may be speclflc or general; a specific statement
gran¡s access permlssl-on to 'a staËed set of blocks, Ì,Ihereas a general
statemenÈ grants thls permlssion to any of Ëhose blocks which would have
access permlssion under irnpllclt scope rules. Ttre resulÈs of describing
'Various languages and language proposals on the basis of these
characÈeristlcs are displayed ln Table 4.3, in whlch rrlrr stands for
rrlmpliciÈtt, rrErr for ttexpliclttr, rrGrr for ttgeneral expllcitrr, rrsrr for
rrspeclfic explicit'r, and ttNtt for rrnot allowedtt.

L22
Table 4.3 The Characteristlcs of Varlous Statlc Scope Rule Schemes

Language or Declarant/ Inheritor/ InherLÈor


Proposal Inherltor Inherftor Agreement
Permlssl-on Perulssion

Algol 60 tfl2l I I I
DUkstra [36 ] I I E

I.lulf and Shaw[166] G or S? N E

Gannon [48 ] S N E

KLeburtz [83] GandS GandS E

McGra¡,¡ t105l S s I
I I I
ASPEN t 157 ] I I I
G s E

Euclld IBBJ G I I
I I E

The llne descrlblng Algol 60 reguires no explanation and 1s


lncluded for completeness, and to facflitate fts comparison with the
more expllclÈ schemes; the scope rules used 1n Pascal are riot described
ln Table 4.3, sLnce their characterlsÈics are Ldentical to those given
for Algo1 60. Dljkstra proposes Ëhat, enumeration of a blockts I'texÈual
contextrr be achleved by adding expllcit inheritor agreemenË to A1gol's
scope rules. l.Iulf and Shars's proposal of I'mutual agreement between
creator and accessort' corresponds to cornblnfng expllcit declaranE/
lnherltor peruissÍon wlth expllclt lnheriÈor agreement; horvever, I'Iulf
and Shaw make no comment on whether the former should be speclflc or
general. Since, under hlulf and Shaw's proposal, transmisslon of access
1s solely a maÈter between declarant and lnheritor, an inheritor is not
pernlEted Lo grant access permlsslon to another block. As Gannon's
proposal attempts to gÍve a speciflc form to the ideas of l^Iulf and Shaw,
lt ls not surprlstng Ëhat their descriptlons in Table 4.3 correspond
closely; as shown 1n the table, Gannon chose spectfic, rather than
general, expllclt declarant/inheritor permisslon. The proposal of
Kieburtz is the first in the table to require expllcit statements in all

t23
three columns; furthermore, his proposal allows a block which has access
to an l¡em to permÍÈ lt to become accesslble (with certaln klnds of
access) 1n speciflc fnner blocks, and Èo also permtL lE Eo become
accessible (probably with a different kind of aceess) in all- other
blocks known to that whfch already has aceess'
and proposals contain not only some form of uore
Some languages
expliclt scope rules, buË also make use of (fufly) lmpllclt scope rules.
For example, McGrav's descrÍptlon of Èhe data control facllities for a
language conÈalning concurrent processes lncludes a 'rrestrlctf'
sta¡emenL. If an item, accessible wlthln some block, ls mentloned in a
restrlct statement ln that block, then it is made accessible only ln the
fnner blocks named in that staÈement (thls corresponds to the flrsÈ set
of enÈrles ln the table)i if, however, the ftem is not mentioned in any
restrlct staËemerÌts in the block, then its accessLbÍllty 1n lnner blocks
is subjecÈ to a default set of (impllclt) scope rules (the second set of
entrles fn the table). In ASPEN, the normal- Algol 60 scope rules aPply
to procedures (the first set of entries), buÈ tt |s also possible Èo
deflne ttpackegst', which are used to compose data abstractions, and
access wtthln packets, to ltems deflned ln other packets, follows the
scheme described in the second seÈ of entries for ASPEN.

. Flnally, Euclid 1s a progranming language 1n whlch two different


forms of expliclt scope rules coexisË; these are descrÍbed in the two
sets of entries shown in Table 4.3 and are, respectively:
(1) an ltem described as ttpervaslvet' at lts declaraLion is then
accessible throughout the range of Èhat block (redeflnltion of
Its name in that range is not permitted), and
(il) 1Ëems, accessible in Ëhe irmediately enclosing block' can be

explicitly Itirnportedttinto a block (in a slmllar manner Èo

Dfjkstra's proposal).
A number of the proposals for explicit scope rule schemes described
1n Table 4.3 allow various kinds of access to be specified' For example,
ttvar" and "readonlvtt
Euclid, whlch ts based on Pascal, distinguishes
access, and Wilcox descrlbes eight 'fcurrently recognized" kfnds of
access for ASPEN (and the classes of identlfíer to whlch each kfnd is
appllcable) .

L24
Notice that, although Èhe set of data conErol sÈructures
expresslble vla any of Ëhe kinds of more explclt scope rules ls still
rest.rlcË.ed, conslderably rnore such sLrucÈures are possible than wÍth
Algol's scope rules. For example, l.lulf and Shaw's complaint that
ttoverlapping definitions" are noÈ expressible (see Sectlon 4.3.f.4) has
been overcome in all cases: the various data ltens to be shared between
subsets of the set of procedures can be declared globally to all of the
procedures, but then access only allowed in Lhose procedures in which lt
ls required.
In his proposal for more explfclE scoPe ru1es, Kleburtz also
lntroduces 'rnamed cells" to allo¡¿ the data control for a grouP of
fdentffiers to be speclfied eollectively; such a feature would possibly
help to reduce the verboslty of programs written in a language with
expllcit scope rules. In Kleburtz's system, 1t is also posslble to
partitlon such a cell 1nËo smaller ones when it l-s lnherlted into lnner
blocks.

4.3.3.4 Previous CorouÈfne Faclllties


As already indicated in the Introduction to Èhls sectlon, prevlous
coroutlne faclliÈ1es have not generally been LnnovaÈlve as far as their
data control aspecL is concerned. In fact, programming languages with a
coroutlne faclllty have mostly borrowed Eheir data control features'
without change, from other languages.
A particularly primitive seÈ of data control features Ís provlded
in Sfl-/2 t38l and lcon[58], both of which have a corouÈine faclllty; Èhls
set of feaÈures consists siuply of the abflity to declare an l-dentlfier
to be efther "globalttor I'local", whlch does not allorv Èhe expression of
a very wÍde range of data eontrol structures. SJ,L/2's global declaration
Ls a low-level feaËure, resembllng the COMMON block of Fortran[3] and
the global vector of BCPL[128], i-n that lts use lnvolves knowledge of
the posttion of quantlties ln a global storage area; Èhe corresponding
declaraËion ln Icon merely slgnifies that Ëhe identlfler is accessible
tn all subprogram lnstances.

a number of nev¡ ideas in


One prograrnming language whlch lntroduced
the area of data control, fn addltion to lts fnnovatlons fn sequence
control (already discussed aÈ sone lengÈh), is Sinula. Data control in

r25
Slmula has thaE of Algol 60 as Lts sÈarÈ1ng point: the nesting of block
deflnltlons (lncludl-ng Lhose of classes) ln a Simula program results ln
the use of A1gol 60's scope rules in the lnterpretation of names. SÍnula
procedures and classes may both have parameters; parameter transmlsslon
to a class lnstance occurs at the time that ttre lnstance is created,
rather than at any other time (such as when a ttresumett or rrcallr' is
executed). The possible parameter transmlsslon modes for a Slnula
procerlure are value (call by value), reference (call by reference) and
narne (call by nane), whereas for classes only the fLrst two of these are
avallable.
Apart from the precedlng data control features, which all follot¿
A1go1 60 reasonably closely, there are two other daÈa control features
in Sirnula whl-ch are quite novel: prefÍxlng with a class identlfler, and
remote accessing of class attrlbutes. Ttre ablllty to prefix a class
definitlon with the ldentlfler of another class allows the constructlon
of hierarchfes of classes, in whtch the atËributes of one class may be
used ln Ëhe definition of anoEher lov¡er down the hierarchy; prefixing a
block (that is, an anon)¡mous block) wÍth a class ldentlfier allows the
concepts deftned fn that class to be used 1n the block. Tkre abllity to
access the aÈt.ributes of a class instance from outslde thaÈ class
(t'remote accesslngtt) 1s provided in Simula via'rremoÈe identlflers'r
'(uslng expressÍons of Èhe form ttl.atr to access the attrlbute ttatt of the
fnstance rrlrt) and "connectlonrr (similar to Pascal's t¡1th statement); 1n
fact, because of the lack of a mechanfsm fn Sfunula for passing
paråueters to an instance after its creatlon, remote accessing 1s very
useful when wrlElng coroutlne programs 1n the language. A dlsadvantage
of Slmulats remote accessfng ls that it encourages wLde lnterfaces
between subprograms and also that it ls noÈ possible to prohibit access
to an attrlbute of a class by other instances outside that class.
PalmetI17I has recommended Ehe additlon of a "hidden'r speclflcation to
Sfmula, to glve a progranmer the abllity to lndicate thaE certaln
attributes of a class are not to be accessible from outslde the body of
that class; a nodifled form of Èhis proposal has been incorporated into
at least one lmplemenËation of SlmulatlTl. A number of other languages
wlth a coroutine faclllty, such as 2.PAK[107] and TELOS[89], have
adopted the remote ldentifier form of remote accessing Ëo enable access
Eo coroutine aEtributes, buÈ none of these has also lncluded a means of

L26
protecting such attrlbutes from unwanLed external access.

Apart from the abfllty to use remote accessl-ng to refer to Ehe


parameters of a coroutlne Ínstancet TELOS contains a number of other
lnterestlng data control features:
a trcapsule" (which consËitutes a daÈa abstraction faclllty) must
expllcitly rrexport" ttty identiflers whtch are to be known outside
1r,

parameter transmlssion modes avallable are the value and varÍable


parameters of Pascal, plus "Readonly" (RO reference) parameËers,
parameter transmission to coroutine lnstances befng at instance
creatlon time,
functlons may return any assignable value' raÈher than being
restrÍcted Èo scalar, subrange and pointer tyPes, as ls the case ln
Pascal,

those TELOS features for manipulatlng coroutine instances are only


aval-lable 1n certain klnds of subprogram (generally I'overseers"),
and

rrcontextrr manlpulationfacfllties, which allow the consÈruction of


a context tree and the speclficaËlon of Èhe context ln whlch a
staÈement l-s to be executed.

The basts of the coroutine facfllty ln SL5 [62] is the decomposlÈion


of procedure lnvocatlon into the separate actíons of the creation of an
envLronmenÈ for this lnstance of the procedure, the binding of actual
parameter values to formal parameter names for the instance, and the
resumption of the executlon of the activatlon. Ttre second of these
actLons represents a data control feaEure, and separatÍng 1t from the
other trvo admits the possiblllty of resumlng (or cornmencing) the
executlon of an insÈance before the forual parameter names have been
bound Eo values, wfth posslbly disastrous consequences. Another aspect
of data control 1n SL5 1s that 1t uses dynamlc scope rules: lnheritance
of an ldentlfler, if 1t occurs, ls from a creator to Ehe created
lnstance, and the lnÈerpreEat.ion of an ldentlfier can be regarded as
involving the examLnatl-on of a "creation hlstory lree'r, as descrlbed by
Britton et â1. t2t1. Moreover, the declaratlon of an ldentlfier speclfies

L27
ft to be elther t'publle" or ttprivate", and only the f ormer klnd of
identifer can be l-nherited from iÈs deflning block. SL5's other data
control features lnclude the ablllty to transmlt values on the execution
Of ttresumett and trreturnrr StaEements, and the ablltty to uSe remote
accesslng to refer Eo Ehe ldenËlfiers of oEher envlronmenËs (lnstances).
The dynanlc nature of lts data control features, particularly the
dynamlc scope rulesr ls conslstent wlth SL5's dynarnic approach to
aequence control (see Sectlon 4.2.3), and it widens the gap between the
textual struc¡ure of an SL5 program and lÈs structure durlng executfon.

4.3.4 Data Control l-n ACL

4.3.4.1 Introductlon
The slgnlficance of Èhe groupfng of corouEines and generators
resulting from the progranming methodology described 1n Chapter 2 ls a
data conÈrol sfgnificance: 1t reflects "maximaltr data sharing relation-
shlps among program components. Thls maxlmal sharíng relationship ls the
princlple of opaqueness, also discussed in that chapter: access Ëo an
item ls restricted to Ehose subprogram units comprising the sub-
hierarchy encompassed by the subprogram ln whlch the ften ls defined. It
Ls clear then that data conÈrol plays an important role in the
prograuming methodology descrlbed in Chapter 2, and that 1t ls important
that the data control structures Benerated as a result of applylng the
methodology should be accurately expressible tn ACL'

To have a certain kind of access to a structured variable in ACL


íuplles that that kínd of access has also been obtained {o aLL of the
componenLs of its structure; however, Ëo obtaln the R access right for a
polnter variable 1s sufficÍent permÍssion to be able to rnodify the
dynarnl-c varlable to whlch it points (but not, of course, to modify Ehe
value of the pointer variable ltself). It would have been posslble to
deslgn ÀCL 1n such a way that the notlon of access to a pointer l/as
dlstlngu1shed from access to the object Èo which lt points, as lt 1s in
the proposal of Kieburtz [83], buÈ tl'rl-s departure f rom Pascal \¡ras noE
thought Ëo be Justlfied Ín vler¡ of the major aim of this language
deslgn: the provlsfon of a coroutine faclllty.

T28
The data control features of ACL will, of course, be descrlbed
usfng the dat,a control model, wíÈh the asslstance of l¡hich they \ùere
designed. Not surprislngly, these descrlptlons r¡111 be slmilar in many
respects Èo those of Èhe daÈa control feat.ures of Pascal (see Section
4.3.3.2). Identiflers are used 1n ACL to refer to all classes of ltems
to which they refer 1n Paseal, and they are also used to refer to (the
defLnltlons of) coroutlnes, generators and generator functlons (the last
of whLch l-s a kind of subprogram unit to be explained shortly); as in
the descriptlon of Pascal, labels are regarded as idenÈffiers. The
prlmÍtive
class (n)

is notr extended so Ehat iÈ evaluates to one of rrvariable",


ttconstantrt,
tttypatt, ttprocedurett, t¡functlontr, ttlabeltt, ttscalartt, ttcoroutlnett,
Itgenerator", or rrgenfuncrr (the latEer standing for generaEor functlon),
depending on Ehe class of the name rrnrr' an expresslon whlch selects a
component of a structured vartable (such as "a[1].rtt) ls regarded as
havÍng the class "varl-able'r, whereas all other expressions (for example'
ttal+a2tt and ttf (xry)tr) have class ttcortstanttr.

Oneof the other primltives used in the descrlption of data control


1n Pascal wfll also be used here; lt ls

actual (e)

which evaluates to the name of Ehe actual parameter corresponding to the


formal parameter contained ín the entry "ett (¡'lhich is an entry 1n a list
of formal parameter names), for the block entry belng described'
As ln the descripEion of Pascal, record field (and variant)
identlfiers r¿ill not be included Ín Ëhe known lists of ACL Programs, and
the with staÈerent will not be described. As a consequence of Ehe
omlssl-on of a description of the with statement, known lists will only
be assoclaLed with lnstances of main programs, procedures, functíons,
coroutlnes, generators, and generator funetions; furthermore' changes ln
the data control structure of an ACL progran are confined to block entry
(PC) and exit (PR) for the maln program, procedures and functlons, and
to l-nltiallzatlon sectlon entry (IC) and exit (TI) ' and main section
entry (CTTGC) and exit (MRTGR) for coroutines, generators and generaÈor
functions.

r29
The asslgnment of names to known llsts ln the descrfption of data
control ln ACL {s stmllar to Ehat used 1n Èhe description of Pascal: the
deflnl-tlon ldentiffer of the subprogram to whose instance t,he known 11st
corresponds 1s used, and subscripÈs are used to distlngulsh between
nultfple instances of the same deffnltlon, where urultiple instances
occu¡o In the ptctorial representatlons of the data control structure of
ACL programs, the bottommost known ll-st can be assumed to be that of the
currently executlng instance, unless another ls explicitly tndlcaËed.
Onceagaln, the following names wlll have standard meanings in the
data conËrol descriptlons:
. rrcalledtt is Èhe name of the insÈance belng entered,
. trcallertt is the lnstance whose acÈlon caused Èhe entry of "calledtt
(through the former executlng PC, IC, CT or GC)'

. t'definltíonrr is the name of (the definl-tion of) the block of which


rrcalledtt is an instance, and

. "defÍner" ls t.he name of the lnstance whlch contains the deflning


entry for "deflnitlont'' and is the lnsÈance of the block whích
1 'nedtaÈely text,ually encloses ttdeflnitlon" which ls llnked to
ttcalled" by Ëhe shortest. sequence of caller and master links.

4.3.4.2 Scope Rules

An explicLt seope rule scheme hras chosen for ÂCL; thls declsion was
made slnce such schemes allor¿ the descriptlon of the maximal data
sharlng relationships of Èhe princíple of opaqueness, whlle allowing the
expression of more complex data sharing arrangements within the
resÈrlctions of this princlple (such as those described for the solution
of the Telegrams Problem presented 1n SecÈiot 2.4). The scope rules of
ACL are statlc ones, because of the design goal of a close
correspondence between static textual structure and dynamic run-time
structure for ACL programs.
As illustrated by the discussÍon of Section 4.3.3.3' there ls
conslderable varlety ln the expllc1t scope rule schemes which have been
proposed to date, and in the cholces available to Ehe deslgn of such a
scheme. Examinatlon of prograns wrltten uslng the varlous scherres shows

r30
that those r¿lth a hlgh level of expressiveness also tend to be verbose,
whereas those r¡hlch are succinct (such as A1gol 60's lmpllclt scope
rules) do not allow Ëhe expresslon of a sufflciently wlde range of data
control structures. Uslng the classlflcatlon system ernployed fn the
comparfsons of Sectlon 4.3.3.3, the compromise between succfnctness and
expressiveness adopted for ACL can.be descrlbed as:

o genêral expllcit declarant/lnheritor permission (ttGtt),

. Lnpllclt lnheritor/lnherftor permlssion ("Itt), and

. expllcit inheritor agreement (t'Et').

In other words, when an identffier is lntroduced (tncludlng


subprogram and formal parameter ldenttflers), an lndication is glven as
to whether or not Èhis ldentifler may be lnherlted lnto an lmmediately
Ínner block; sueh an lnner block must expllcitly lnherit the ldenÈifier.
Any ldentlfler which has been inherlted into one block may be
(expllcitly) inherited into another block trhich ls lmmedÍate1-y fnner to
that one. An identifier is always accesslble ln the block ln whlch it ls
l-nÈroduced (deflned).

In additlon, each statement of expllcit lnherltor agreement in ACL


specffies the kind of access ¡shich that block is to have to the item:
'either Rl.{ or RO access. Furthermore, ACL adheres Èo the prlnciple of
non-lncreaslng privilege discussed fn Sectlon 4.3. 1 . I r and so an
ldentlfler can only be RI,l inherlted fnto an lnner block 1f 1t ls RI^I
accessfble ln the outer block; simllarly, an identlfier can only be
inherlEed lnto an lnner block at aLl lf 1Ë ls accessible 1n the outer
block.

Conbining the prl-nclple of non-Íncreasing prtvllege with an


expllclt scope rule scheme can lead to situations ln whlch an identifier
is (explicltly) inherited through a number of levels s1mp1y so tlìaÈ the
ldentifier is accessible at two widely separated block levels. In
particularr lf standard ldentlflers (for example, those of standard
procedures and functions) ruere to be regarded as being defined in some
flctitlous block which surrounds every program' then these names would
often have to be lnherlted Èhrough a nurnber of block levels so thaE the-y
could be used in a deeply-nesÈed lnner bloclc. Consequently, standard
ldentlfiers in ACL receive speclal treaÈment: they are accesslble in

131
every block, and they have their standard meanlngs 1n all blocks in
which Èhey are noË deffned to have some other meanlng; standard
ldentifiers may not be expllcitly lnherited inÈo a block. As with the
description of data conÈrol in Pascal, known lÍsts in the description of
ACL programs do not. contain standard identlfters unless they are defined
to have other than thelr standard meanlng, or are required as actual
parameters. One parEicular need for lnherltlng varlable ldentlflers
through a number of levels in programs vrritten in languages r¿lthout a
coroutlne facillty (such as Pascal) is obvÍaÈed Ín ACL: it is not
necessary Èo use global. variables Ëo communlcat.e between different
l-nstances of the same procedure or functlon, since t.he subprogram can be
wrLtten as a generator or generator functlon in ACL, and the varlable
declared loca1 to lt (with the aÈtendanE increase ln security) . In fact '
experience with ACL has shown that siËuations do not often arlse ln
which 1t is necessary to ínherit an identifler through block levels ln
whlch access to the ltem 1s not really required.

NoElce, in partÍcular, Èhat the definltlon identlfiers of


procedures, functlons, coroutlnes, generaEorsr and generator functions
are all introduced (defined) in the block irnmediately ouEer to thelr own
blocks (bodÍes), and Chat tf access to the deflnitlon ldentlfler of such
a subprogram is requlred wlthin lts body (say, to enable a procedure to
'call ltself recurslvely), ft musÈ be explicitly inherited.
In order to descrÍbe the preceding facets of data control 1n ACLt
uslng the data control model, the following three lists (any or all of
which may be ernpty) are assocfated with every block fnstance, "bt':

(a) LOCA\: a list of the names declared locally to the block; thl-s
ltst includes the identlfiers of procedu::es and functions
declared 1n the block, and those enumeraÈed in any scalar tyPes
declared 1n type or variable declarations in Èhe block,

(b) INHROO: a I1st of the ldentlfiers declared to be inherited lnto


the block ¡víth R0 access, and
(c) INHRhIS: a llst of the Ldentifiers declared to be l-nherited into
the block wlth RW access.

r32
If rrbrt is a maln progrâm lnstance, Lhen boÈh INHROS and INHRI'I6 are
empËy for a legal A,CL program, since there is no block outer to an ACL
main program block.

Entrles 1n all lists of names are nolil regarded as havfng an


addiËlonal property: whether the name contalned in that entry 1s private
or herltable; only heritable names may be inheriÈed fnto inner blocks.
In the case of known lists, this "heritabllltyrr property is regarded as
orthogonal to that of r¿hether the enLry ls defining or non-defining.
The predicate

prlvate(e)

evaluates to tttrue" lf the entry tte" contains a prlvate identlfier and


to ttfalsett otherwise. An entry containing a privaÈe name ls also
referred Èo as private, and sirnllar1-y an entry containing a heritable
name 1s called heritable.

When a name 1s lnserted -into a llst, the entry which ls to be


created to hold the name must no\t be designated as elther private or
herLtable. Thus, the primitl-ve whlch performs llst lnsertlons is
exÈended; it ls now

insert(nrL,k1rk2)

which creates a nert entry 1n the list "L", the entry belng deflning or
non-deflnlng depending on whethet ttkltt has the value rrDrr or
rrNrtr and

prLvate or heritable dependlng on wheÈher the value of "k2tt is rrP'r or


rrHrr .
Èhe name rrnrr Ís then set into the ne\{ entry. For example,
rrl-nsert (*rR% ,DrH) " creates a def ining, heritable entry ln the RO list
of the instance ttbttand sets the name ttxttinto lt'
Names will be presenË 1n private or heritable enEries in LOCA\ r
depending on the lndication of their heritability given with thelr
declaraÈion. Label identifiers must be declared private in ACL; by this
sinple mechanism, global jumps are prohibited in ÀCL, while loca1 jumps
(whose meanlng ls much clearer from the program text ln those languages
r,rhlch allow both) are stil1 perrnltted. All scalar identifiers are
regarded as heritable, lrrespective of the heritabillty of the
corresponding type or variable identifier, for reasons which will be
explalned shortly.

133
Local Declaratlons

The kind of access applyfng to ldentfflers in lnstances of the


block ln whlch they are deflned depends, as |t does ln Pascal, on that
ldentlfler's class:
Rl,l accesstble: varlables

RO accesslble: tyPes' constants, labels, functions'


procedures, scalars, coroutines t
generators generaËor functlons
'
Notlce thaÈ RO access to a procedure or funcÈion identifier 1n ¡1'CL
fmplles, as 1t did ln the description of Pascal, the ablllty to call the
corresponding subprogram. Similarly, RO access Ëo a coroutine, generator
or generat.or functlon definttion identlfier in an ACL prograur lmplles
the ability to creaEe instances of Ehat subprogram; creatlon of such
lnstances also requires RI{ access to the lnstance variable ln which the
instance is to be stored. To call an lnsEance of a coroutine' generator
or generator function (uslng CT or GC) requires only the R access right
to the lnstance varlable, and so elther Rtr'l or R0 access to Èhat varlable
fs sufflcLent.
The event describlng Ehe data control effect of local declaraElons
'iakes place at block entry in the case of the maln Programt procedures
and functions, and aË inittaltzatlon section entry for coroutlnes,
generaÈors and generaÈor functlons; lts deflnition is as follows:
LD { for each n in LOCALcalle¿ @
[ 1f private(n of LOCAJ,"alled)
then k <- rrPrr else k <- ttHtt;
case class(n) of
varlable:
lnserË (n rRWcall"¿, D rk) ;
type, constant, label, functlon, procedure'
scalar, coroutlne, generâtor, genfunc:
lnsert (n rROcalls¿, D, k)
endl )

The result of this evenÈ ' as wl-th the corresponding one ln the
descripÈion of Pascal, is the lnsertlon of a definlng entry (in this

134
case, tt fs also necessary to speclfy whether lt Ls prfvate or
herltable) ln etther the RW l1st or the RO l1st of the lnstance belng
entered, depending on the class of the identlfler, for each of the
ldentiflers ln LOCALcalled.

RO Inh rltins Declaratlons


The inherltance of scalar (enumerated) types received special
attention in the design of ACL; one goal \Jas Lo avofd forcing a
programmer to explÍcitly lnherit each of the scalar idenÈifiers
coûstitutíng a scalar type to be accessible in a block, and another r'Ias
to avoid a partlcular anomaly of Pascal. Ttre flrst goal was achieved in
ACL by havlng the expltcit inheritance of a type identlfier also cause
the (irnpllcit) inherltance of the identlflers defined in any scalar
types ¡,¡ithin the correspondíng tyPe structure; ln f act, expllclt
inheriÈance of scalar identffíers ís noÈ permitted in ACL. Inpllcit
inherltanee of scalar ldentifiers also occurs ln a number of other
situatlons: for example, 1t happens when a varlable whose type involves
scalar ldentlfiers ls (expllcitly) inheriËed, when a functlon or
generator functlon ls declared to return a Value of such a type, and
when a formal parameter is declared to be of such a ËyPe. It is noIÀI
clear why all scalar ldentifiers are regarded as heritable Ln ACL.
The above-mentioned anomaly with scalar types 1n Pascal is
lllustrated in the prograu fragment of Figure 4.332 ln the outer block,
the varlable rrv'r is of ËyPe rrTrt and may be asslgned any of Ëhe values
,tatt, rrbrr or rrcrr. In the inner block, however, one of these values (rrbtr)
is masked out by the decl-aration of a local variable of the same name'
and Ehe varlable rrvrr (which is accessible ln thls block vla the scope
rules) can only be assigned the values rrarr and rrcrr. Oae night argue,
therefore, that the type of "vtt in the inner block fs effectively
T, (a'c)

and consequently that Èhe vartable does not have the same type. ln the
tr.fo blocks (that ís, its tyPe is dynamf c) . Programs exhibiting thls
behaviour tend to be dlfftcult Eo understand, and can contaln confusíng
errors (for example, the statement "v:= b" in the lnner block of Figure
4.33 would result l-n a type confllct error).

135
_!ype. T = (arbrc);

g v:T;
procedure p;
var b:integer;
begln ... end;
begln end

Flsure 4.33 A Pro gram Fragnent lllustraLlng an Anomaly with


Scalar Types 1n Pascal

Thls anomaly has been avolded in ACL by dernanding that the scalar
identifiers (inpllcltly) fnherfted lnto a block be distinct from all
other Ídentifiers known i-n the block; consequently, 1f a scalar tyPe 1s
known in a block, each of lts idenÈiflers wfll also be known and will
have the meaning of denoÈl-ng one of rhe values of Èhat type'

Another prlnltlve 1s added to the daÈa control model for the


descrlptlon of scalar types tn ACL:
enum(n)

evaluates to a ltst (possibly empty) contalning the scalar identfffers


{nvolved in the type corresponding to "ntt, If the latter is a Eypet
varlable, formal parameter, functlon or generator functlon identifier;
1t evaluates Èo an empty list if rrnr' Ís any other kind of name. Thts
primltive has the additlonal property that it wfll not evaluate Ëo the
same scalar identlfler twice ln the same lnstance enËry (which rnay be
composed of the effects of several events) this is to Prevent
duplicate occurrences of these scalar identifiers 1n the instance's
known list.

Another problen ln Pascal (mentioned in SecÈ1on 4.3.3.2) is also


overcome 1n ACL: the definítlon identifler of a functlon or Senerator
functlon must be (RO) inherited into lts own body (that ls,rrdefl-nftion'r
must be present ln INHRO.alled when 'tcalled[ is a function or generator
functlon lnstance). Thus, fË is not posslble to construct functÍons or
generator functlons in ACL which cannot return a value because of lack
of access Ëo the deffnitlon name. (Recall Flgure 4.28, whlch contalns
two Pascal funcÈlons r¿htch are unable to return a value for Èhis

136
reâson.) As thls ldentifler ls RO lnherlted into an ACL functlon or
generator functLon lnstancer âr lmpllcltly-deflned local varLable to
hold the value to be returned by this instance (simllar to that in the
descrlptlon of {ata control 1n Pascal) has 1ts name, whlch ls the same
as Èhe deflnltl ,, l-dent.iflerr inserted into the RI^I ltst of the lnstance.
This enËry |s nog llnked to any lnstance aÈ this stage (see later).

The evenÈ describfng the effect of RO inherltl-ng identlfters (which


occurs at block entry for procedures and functlons, and at
lnitlall-zatlon secÈlon entry for corouÈlnes, generators and generator
functlons) can nor¡ be def lned:
IRO = { for each n in INIIROcalle¿ @
I lnsert(n rRocall.¿, N'H) ;
case class(n) of
type, varlable:
I lfnk(n of ROcalled, n of KNOWNUeflner' RO);
for each e in enum(n) do
I lnsert(e,ROcall.¿rNrH) i
l1nk(.e of ROcalled, e of RO¿.ffner' RO) I l;
constant, procedure, corouÈlner generator:
[ l1nk(n of RO"rrred, n of RO¿"¡trr.r, RO) ];
functLon, genfunc:
I ff n = deflnltíon Ëhen
I lnsert(nrRWcall.OrNrP) ;
for each e in enum(n) do
I lnsert (e,ROcalls¿rNrH) i
l1nk(e of ROcalled, e of RO¿.f1ner' RO) I l;
lfnk(n of RO".tred, tr of RO¿"¡roe., R0) I 1 )
By the prínciple of non-increaslng prlvilege, all identifiers
present fn INHRO"alled must also be present in either the R0 l1st or the
Ri^f 1lst of "deflnertt, and must be heritable in the approprlaÈe l1st;
consequently, no labe1 identlf iers will be present 1n INRocaued.
Notice that each value of "e" is one of the scalar identifiers of a type
known in ttdefiner" (the return type of a functlon or generator function
1s interpreted in the context of the encloslng block) and hence, because
of the restrictlon agalnst the masking out of some of these scalar
identífiers, it must be present It R0d.flrr", (scalar identlfiers are

r37
treat,ed as Èhose of constants ln both A.CL and Pascal). Notlce also that
the irnplicltly-defined vartable local to a function or generator
functfon lnstance, whfch holds the value to be returned, 1s prlvate to
that. l-nstance.

RI{ Inheritlns Declarations

The even¡ resultfng in the RI,/ inherltance of identiflers lnto the


block instance "called" from the lnstance lrdefinerrr, which again occurs
at block entry for proceclures and funcÈions, and at lnftlalization
section entry for coroutines, generators and generaEor functfons, has
the following definltlon:
IRI,I = { f or each n in INHRI,trcalle¿ @
[ Ínsert(n,RWca1l.U rN,H) ;
l1nk(n of Rll""11ed, r of RI^IU.trrr.r, Rtr{);
for each e in enum(n) do
I insert(e rROcall.UrN'H) ;
l1nk(e of Rocalled, e of RO¿"finer, RO) I I )

The prlnciple of non-lncreaslng prlvilege lmplíes that a1l


identiflers present in INHRI^I"alled must also be (fn herltable entries)
fr RWd.ffrr"r, for a legal ACL program.
In Euclid [88] , tr,ro ttbinding condlÈionsrr may be used when
rrlmportlng" (expliciEly ínherltlng) a variable: rrvartr (eorresponding to
and ',readonly" (RO access) ; ho\.lever, a dif f erent binding
RI,tr access)
condftion ("log"t") applies when importing constanÈs. The vlew of data
conErol described ln Sectlon 4.3.1 has allot¡ed a more consistent (and
slnpler) approach to be taken Ín the deslgn of ACL: 1f the R right is
required for any class of item (and an fnterpretatlon must be glven for
some classes, such as procedure ldentiflers) , then this can be obtafned
through one kind of R0 inheriElng declaration.

Flgure 4.34 traces Ehe changing daËa control structure of an ÀCL


program, and illustrates the effects of the events LD, IRO and IRI{. The
effect of some local declarations on the known list of a block Ínstance
tfoutert' is shown in Figure 4.34(a); a prlvaEe type I'Tfr is deflned to be
rtbrr and rrcrr' Ttre f our
a scalar type r^¡hose possible VAlues are ttatt,
ldentiflers all go lnto definlng entries ln the R0 llst of 'router", but

138
only rrTrr is prlvate. (In the pfctorlal representatfons of known llsts, a
private name l-s pref txed by a sharp ttlltt' lf an enÈry 1s definlng and
prlvate, the pref |x tr//*'r ls used. ) Two varlables, "vl" and "v2" " are
rrTrr) and their
also declared loca1 to'router" (they are both of tyPe
ldentifiers are placed ln definlng entrles ln the RW 11st of the
l-nstance; both of these variables are declared to be herltable. As shown
ln Ftgure 4.34(b), anoËher lnstance (t'inner") ls then entered; in facE'
this is an lnstance of a block whlch is declared lmrnediately ¡,¡ithin that
corresponding to "outertt. Thls nerìI instance lnherits the ldentffiers
"Vlt' and "v2", the ftrst wlth RW access and the second with RO access;
iË ls possible for "outertt to lnherit these identiflers because the
deftnitlon of "innertt is textually nested immediately within that of
t,outertt, and because rrvlrr and ttvztt are heriÈable. Since the inherited
vartables are of type "T", thls causes t.he Lnpliclt Ínherttance of the
ttinnertr has R0
scalar i-dentifiers ttatt, rrbrr and ttc". Notice thaE because
access to the variable "v2", the latEer identlfter is 1n the RO Ilst of
"inner" and its entry 1s llnked v1a an RO link to the (defining) entry
containing "v2" ln Èhe RI^l l1st of "ouËertt, thus establishing a data
control strucËure which cannot be constructed in Pascal' The known list
of "ínner" also contalns a definlng entry for a local' prlvaÈe constant
named rtxrr.
ou ter ou ter
*vl *vl
*v2 *v2
T
l¡xT lrxT
*¿ *¿ I
*b
*g
*b
*g
ir -l
-r- 1-
lt I
lt I
rt I

lnner ll I

vl tt I

L_ rl I
v2 rl
Jl
I
I
a
I
b _ _.1
I

c J
/l*x

(a) (b)
Fleure 4.34 DaEa Control Structures lllustrating the Effect of Local
and Inheriting Declarations ln ACL

139
4.3.4.3 Parameters

Parameter transmlssion may be associated with any of the sequence


control operatlons of ACL which can be used to "callt' (raÈher than
'rreËurn from") an lnstance: PC, IC, CT and GC. In the case of PC and IC,
the parameters are transmitted Èo an lnstance created as a result of the
operâtlon and are referred to as ttinitializatLon parametersrr; on Ëhe
other hand, CT and GC Pass control to pre-existlng instances and
ItcontlnuaÈ1on
parameters associated wlth these operaÈions are called
parameters". It ls clear, Èherefore, that proeedure and function
definitlons ln ACL have one formal parameter list, as they do in Pascal'
but thaÈ coroutlnes, generators and generator functions have ttlo such
llsts: an "Ínltialization formal parameter lisÈ" and a rtcontÍnuation
formal parameter list't. Because parameter transmission in ACL is always
assoclated with calling an lnstance (atthough the formal parameter list
may be ernpty), it is not possÍ-ble (as it ls 1n sL5, for exauple) f or an
instance to conmence execution before formal Parameter names have been
bound to values.

Correspondence between f.ormal Parameter names and actual parameter


values ("arguments") is lndicated ln ACL using the poslÈ1ona1, rather
than keyword, notâtion; thls was motivaEed by a desire to follow Pascal,
because there ls
,except where there I^7as a good reason for departure, and
some confusion over the accesslbillty of formal Parameter identj-flers
when using the keyword not.atlon (since they must be accessible in Èhe
calling lnstance to be used in the actual parameÈer list) ' The number of
actual parameters musE always be the same as the number of formal
parameters;lt is not posslble, for example, to omit some actual
continuatlon parameters Eo signify Lhat they should retain thelr former
values.

In choosfng the parameter transmisslon modes of AcL, a major


crlËeríon was that a Programmer should be able to choose between Rl'l and
RO access to the actual parameter: ln other words, the choice between
protecting the actual parameter from change, of allowlng it to be
changed, in Èhe called instance. For example, such a choLce is available
ln Pascal, wiËh its varlable and value parameters' but not ln Fortran'
whlch has only call by reierence parameters. Furthermore, cal-l by
reference and call by value have an advantage whlch r¿as mentioned in

140
Section 4.3.1.5 and whlch can norù be restaEed in terns which cover both
lnitiallzatlon and contlnuation parameters: for these transmission
modes, l-nterpretatlon of actual Parameter expressions occurs at the Èime
thaÈ conrol is transferred to Ehe instance concerned, and that
lnterpretatlon reualns current unÈil exí-t from the lnstance (whieh may
be a permanenE or temPorarY exlt).

In fact, there are three parameter transmission mechanisms


avallable in ACL: RtrI reference (also called "modifiable") parameters, RO
reference ("seen") Parameters' and value Paraneters' The flrst Ewo of
these offer a prograutrer the sinple choice between RI'l and R0 access to
the actual parameter, and are complementary to the Rtr'I and R0 inherftance
features of ACL; value parameters hTere lncluded in ACL largely because
of the argumenls put forward in thelr favour by Amnann[4] ' particularly
Èhat they siurplify the prograrnmlng of cerÈaln problems, and that they
offer the cholce between copying and not copying (especlally 1n a
language with RO reference parameters). Once the decision to include R0
reference parameters r,¡as taken, the inclusion of RO value Parameters'
simllar to the "const" parameters of Mitchell and WegbreiE (see SecÈion
4.3.1.5), \,{as not thought to be justlf led, 1n vlew of thelr lftnlted
ut111ty.

For the descrlptlon of the paraneEer transmisslon features of ACL,


a further slx lfsts of names are 1nÈroduced, the first Ehree of whlch
are associated vsith instances of procedures, functlons ' coroutlnes '
generators and gefierator functions, and the lasË three of which are only
assoclated wlth instances of coroutines, generators and generaLor
functlons. These lists are:
(a) ISEENb the formal seen Lnitiallzatlon parameter names for the
ilb il,
instance

(b) IMODIFO: the formal modtflable inlttalizatl-on parameter naues for


the lnstance ttbtt,

(c) IVALb: the formal value initlalizatlon parameter names for the
l-nstance ttbtt,

(d) CSEENb: the formal seen conÈinuatlon ParameÈer names for the
Ínstance ttbtt,

141
(e) CMODIFb: the formal rnodlflable contlnuaËlon parameter names for
the lnstance ttbtt, and
(f) CVALb: Ëhe formal value conËlnuatlon ParameEer names for the
fnstance trbtr.

Ihe events for lnltlalizatlon parameters clearly occur at block


enËry for procedures and functtons, and at lnltiallzaÈlon sectlon entry
for coroutines, generaËors and generator functions; events describlng
the effect of contlnuation parameLers only occur at maln sectlon entry
for corouÈlnes, generators and generator functlons.

RO Reference (Seen) Parameters

Ttre actual parameter corresponding to a formal seen Parameter must


be a declared (not sÈandard) variable, procedure or funcÈ1on name' a
consËant identifler, or an explicit constant; ln particular, expressions
of a general nature (such as those allowed as actual value parameters)
are not allowed as actual seen parameters. The transmlssion of a
procedure or functlon ldentifler as an RO reference parameter provides a
facillty simllar Ëo the procedure and functlon Parameters of Pascal,
r^¡tthout the need for speclal transmission modes.

The effect of seen initlalizatlon parageters is described by:

IS = { for each f 1n ISEENcalled do


I a <- actual (f of ISEENcalled);
1f prlvate(f of ISEENcalled)
then k + rrPtt else k <- "Hrr;
insert (f ,ROcall"U, N rk) ;
for each e 1n enum(f ) do
I insert (erROca]_l.U,NrH) ;
l1nk(e of ROcalled, e of ROU.fíner' RO) l;
1f class(a) =varfable
then link(f of ROcalled, a of KN0\a11er, RO)
else [ lf not (a ln RO""Uer)
then [ lf not ( (a) in RO"ull.r)
then inserË( (a),R0caller,DrP) i
ltnk(f of ROcalled, (a) _9.f. Rocaller' RO)
else llnk(f of ROcalled, a of RO""ller, RO) I )

L42
The types of formal parameter ldentifiers are lnterpreted in the
context of the block inmedlately outer to Èhe deflnitlon of the
subprogram concerned; hence' if the tyPe of a formal Parameter involves
scalar fdentlfiers, these ldentiflers w111 be presenÈ in the RO list of
the instance "deff¡errr, from r,¡hich they are (lmpllcitly) inherited into
the RO l1st of t'called". Ttre test on the class of the actual parameter
name ls necessary because an actual seen parameter which ís a variable
may reside ln elther the RW llst or the RO llst of "callert', and it ls
not, possible to sftnply use "llnk(..., a of KNowNcaller' ...)rrslnce thls
leads to an arnbigulty ln the case that "callertt ls an instance of a
ttatt, ín which
functlon or generator functlon r^rhose definition name 1s
case there will be entrles contalning the Ttame "a" in both the RI'I and RO
lists of "callert'. Slnce standard constant Ídentifiers and expliclt
constants are allowed as actual seen Parametersr lt may be necessary to
insert a parenthesized version of Ëhe actual Parameter exPression ln the
RO lLst of the calling l-nstance (as was also the case 1n the descriptlon
of Pascal's Value parameters) because the actual parameter'
parenthesized or not, is not already Present ln that list; notlce thaÈ
the entry lnto whlch such a parenËheslzed actual par:ameÈer is placed 1s
a deflning, private one.

The event for seen contlnuaÈlon parameters 1s:

CS = { for each f 1n CSEENcalled do


I a êactual(f of CSEENcalled);
1f not (f in KNOW""U"¿) then
I tf private(f of CSEENcalled)
then k ê rrPtt else k <- ttHtt;
lnsert (f ,ROcall"U, N,k) ;
for each e 1n enu¡o(f) do
I insert (e,ROca1l.U, NrH) ;
llnk(e of Rocalled, e oli RO¿.flner, RO) I l;
if class(a) =variable
then link(f of ROcalled, a of KNOlrrNcaller' RO)
else [ lf not (a _1n Ro"rll.r)
then [ 1f not ( (a) in RO""ll"r)
then insert( (a) ,Rocaller,D,P) i
llnk(f of Rocalled, (a) of ROcaller, RO) l
else ltnk(f of Roealled, a of RO""ller, R0) I )

r43
whlch differs from the event IS only ln that fornal parameter
identifiers (and any associated scalar ldentlflers) are only inserted
1nÈo Èhe RO list of "called" if they are not already present' In fact,
all of the identlfiers for conti-nuatLon seen parameters are added to the
RO list of ttcalledtt on the first occasion that such parameters are
rrcalledil
transmitted (that is, the first tlne that the main sectlon,of
is entered), and no such additions are made on any subsequent occasions
that the maln sectlon ls enÈered. Note that the "llnk'r prf-mitive has the
side-effect of eraslng âny exfstlng llnks out of an entry when
establishing a link from that enÈry.
One (noÈ uncommon) sltuation in which seen lnitlalization
parameters prove particularly useful is thaÈ in whlch two lnstances of
the same coroutine definition are required Eo pass control back and
forth between each other. The way in which the necessary mutual
references between Èhe two lnstances must be established in some
languages wlth coroutlnes is lllustrated by Èhe Simula fragment of
Flgure 4.35, which is taken from 176). The formal parameter of the class
trArr is bound to the value "none" rùhen the flrst lnstance of thls class

is creaÈed, a reference to this instance belng stored ln the variable


ttxtt; Èhe formal parameter ls bound to a reference to the first lnsËance
rshen the second lnstance 1s created. Finally, the value of the formal
'parameter ln the case of the first instance ls redeflned to be a
reference to the second instance (by assigning the value of che variable
ttytt to the formal parameter, uslng remote accesslng)'

ref (A) xr yi
class A(other); ref (A) other;
begln ... detachi ... resume(other); ' " end;

x:' ngll A(gon.); y:- new À(x); x.other:- y;


Flsure 4.35 A Slnula Fragment Ill-ustrating Èhe EstablishmenE of
Mutual References between Instances

The daEa control structures shown fn Figure 4.36 demonstrate how


mutual references can be established in a simpler fashion wlth the seen
inltializatlon parameters of ACL. Conslder an ACL Program in which tv¡o
instance variablesttxttandttytt, and a coroutlne t'Att are defined in Èhe
sane block; the coroutine has a seen initiallzatlon paraneter, called

r44
t'othertt. Now, an Ínstance of Èhe coroutl-ne (labelled'[lt'in Flgure
4.36) is creaEed by an lnstance of Ehe deflning block (call thls
lnstancettoutertr), passing the varlablettytt as the actual seen parameLer
rrxrr (remember
and sÈoring the newly-created instance ln the varlable
that lnstance variables contain instances, rather than references to
then); Ehe result is shown ln Figure 4.36(a). Control then returns Ëo
,toutertt whlch creates another lns tance of the coroutine (ttA2" ) , this
rrAlrr) as the
tine passing the varlable rrxrr (which contalns the lnstance
rryrr
actual seen parameter, and sËoring this new lnstance 1n the Varlable
(to whlch the lnstance "Altt has access); the sl-tuation after these
actions have taken place is depf-cted fn Flgure 4.36(b), in which the
lnstance trAZ', ls currently execut.i-ng. Thus ' ACL allows the mutual
references to be established Ín two clear sÈePsr 3s opposed to the
clumsy method which must be ernployed fn Slmula'
outer outer

x x --- - - -1

v v

Al A2
Al

other other other - -

(a) (b)
Figure 4.36 Data ConÈrol Structures Illustratlng the Establishuent of
Mutual References between Instances in ACL

It fs the sensitlvity of an RO reference parameter to changes in


the value of an actual Paramet.er varlable whlch is belng ernployed in the
above example, and thls ls one of lts main advantages over RO value
rrconst'r parameter)'
parameters (such as Mítchell and llegbreit's

RI{ Reference (Modlf iable) Parameters

Only variable names are legal as actual rnodifiable parameters ln


ACL (as is the case wlth actual varlable parameters 1n Pascal); in
additlon, an actual modifiable parameter name must be RI'I accessible ín
the call1ng instance, because of the princtple of non-increasing

r4s
prLvl-1ege.

The event which deflnes the effect of modlflable lnftl-allzaElon


parameters is:
IM={ for each f in IMODIFcalled do
I a+actual(f of IMODIFcalte¿)i
Íf private(f of IMODlFcalled)
then k <- rrPtr else k <-ttHtt;
lnsert (f ,RWcall"U rNrk) ;
f or each e l-n enum(f ) do
I lnsert(e rROcall.UrN,H) ;
lfnk(e of ROcalled, e of Ro¿.finer, RO) l;
lfnk(f of RW"alled, a of RW."ll.r, RW) I )
and the event for ruodtfiable contlnuatÍon parameters (l¡hich 1s called
rrCM'') dfffers from ll"f only 1n the way that CS dlffers fron IS: entries

for formal parameter names (and assoclated scalar ldenÈlflers) need only
be lnserted in the known l1st of the instance
ttcalled" on the occaslon
of the first entry to lts main sectlon. Since this 1s the only
dlfference, the deflnítlon of CM is not presented here'

L46
Value Parameters

The evenÈ deflning the effect of value lnltlallzaElon parameters 1s

as f ollol¡s:

IV = { for each f in lVAlcalled do


I a+actual(f of IVAL""11"¿)i
lf private(f of IVÆ""ll.d)
then k <- rrPtt else k + t'Htt;
LnserÈ (f , RW""ll"U,D, k) ;
for each e in enum(f ) do
I lnserÈ (e ,R0ca11"¿, N,H) ;
link(e of ROcalled, e of R0¿"finer, RO) l;
1f (-æ! (a in KNOWNcatler) )
or (class(a) = functlon) or (c1ass(a) = genfunc)
then [ 1f noE ( (a) in KNOW"rU.r)
then lnsert( (a) rRO""11.rrD'P) i
l1nk(f of RWcalled, (a) of ROcaller' RO) l
else ltnk(f of RWcalled, a of KNOI^tNcaller, RO) l )

which 1s similar ln many rtays to the defintElon of the corresponding


event (v) in the earller descrlptton of Pascal. In partlcular' a par-
entheslzed version of the actual parameter name 1s fnserted into a
,defining (prtvate) entry ln the RO l-lst of the calling instance
(trcaller") 1f thaÈ name is not. already present 1n the lnstance's known
llst or 1f the actual parameter is a functlon or generaÈor function
fdentlfier (generator functfon calls have a similar synÈax to function
calls) .

The deflnition of the event for value contlnuatlon parameters


(whlch Ís called "cv") is simílar to that of IV; ln fact, lt dlffers
from Èhe above definltion ln the way thaÈ CS and CM differ from IS and
IM, respectively: the insertÍon of entries for the formal parameter
names and associated scalar ldenEífiers occurs only once for each
fns tance.

Amatter whlch requires further s6mment concerns the transmission


of a continuation parameter, using any of the transmisslon mechanísms'
to a subprogram (coroutine, generaEor and generator functton) instance
whlch has an lnfrastructure, ln the sense thaE tt ls caterval or lt has

L47
a subordlnate seË of procedure instances. If a forrnal Parameter of one
oL iÈs component instances was last bound to one of Ëhe formal
contínuation parameters of the subprogram, then subsequent transfer of
conÈrol Eo the subprogran wlll lead to Èhe rebl-nding of the continuatlon
parameters, and this ralses the questl-on of whether the parameter of the
componenË inst.ance should also be rebound to the ner¿ acÈual parameter
value. In fact, thls questlon can be extended to cover cases where Ëhe
formal parameter of the component lnstance was also last bound to the
formal parameter of some other component, and so on. Because of the
translent si.gnifLcance of inÈermediary ldentifiers ln the data control
model (see the discussion of Section 4.3.2), and since value parameters
are asslgned their values only at the tlme of parameter transmisslon, 1t
1s clear that such "secondary rebindingtt does not occur with any
transmlsslon mode in ACL. Flgure 4.37 depicts a sttuatlon of the kind
descrlbed above; ln Flgure 4.37 (a) ' rrBrr is a suspended coroutlne
Ínstance r.¡ith a subordinate procedure lnst.ance "Ptt. On the last occasion
ttrt' of the instance
that con¡rol $ras transferred to rrB'r, the varlable
"Att Í¡as supplied as the actual parameter corresPonding to the formal
ttPtt was called,
nodiflable parameter 'tx"; when Èhe procedure instance
rrxrr of ttBtt\n¡as given as the actual parameter corresPondlng Ëo the formal

seen pararneËer I'y" of the procedure. In this way, ât R0 link r¡Ias


established f rom "ytt of rrPrr Ëo rrrrr of "Att; although
ttxrr of rrBrr was used

as an Íntermedfary fn the esEablishment of this link, no record is kept


of this fact. Figure 4.37 (b) shor¡s the result of the suspended instance
ItBttbelng re-enEered, thls tlrre wlth t'stt of rrAtr as Èhe actual parameter
tty" of
correspondÍng Èo 'rx'r; notice, 1n particular, that the ltnk from
rrPtr to rrrrr of rrÀtr is unaffected.

148
A A

rt¡ It¡
*g *g

x x

P P

(a) (b)
Fieure 4.37 Data ConÈro1 Structures Illustrating the Reblnding of
Contlnuatlon Parameters in ACL

The above questlon ls discussed at some length by Vanektl49l ' slith


respect to an implementatlon of generators (which he calls 'rhierarchlcal
coroutinesrr); the sÈartfng point for hís discusslon 1s the (lnplictt)
'assumpËion Ehat the deletlon strategy ls to be used for storage
associated with all procedure instances' Under thts assumptlon, Vanek
concludes that 1t ls necessary Èo reblnd procedure parameters l-n
ttÊyp"
situaÈions such as thaE in Fígure 4.37 to avold vlolatlons of
safetytr; these occur since a generator lnstance may reÈaln a reference
(vta a reference paramet,er) to a variable local to a termlnated
procedure lnstance, even though the activation record for that instance
has been <teleted (since the deletlon sÈrategy 1s being used) and perhaps
the prevlous actual parameter variable has been overlald wlth another
variable of a different Eype, belonglng to a different procedure
instance. Thfs lfne of argument then leads Vanek fnto the complexity of
ttdouble lndirectlontr and the need to introduce concepts such as
I'nonrebindable"
"absolutely rebindable'r, ttpotentlally rebindablertand
(slnce double indi.reetlon must only be used Lo access parameters 1n
those cases where secondary rebinding ls necessary) '

r49
4.3.4.4 Returnl V alues from Subproqrams

In the language INTERLISPt146l and 1n the proposal of McIlroy[106]'


1t Ls posslble for an operaElon transferrlng control Èo a coroutlfie to
evaluaÈe to a value. In ACL, however, the abllity of sequence control
operations to evaluate to some value ls llmíted to transfers to those
subprograms whlch have an obllgatlon to return to the point of call
(as
rrreturnedt' vrhen control
lt 1s tn pascal); i-n these cases, the value is
returns. Thus, ACL has forms of both procedures and generators (called
rrfuncÈlonstr and "generator functlons", respecË1vely) which return
values, and these are textually distlnguished from the forms r¿hich do
not return values; the sequence control behaVtour of functions and
generator functlons l-s identical to thaÈ of procedures and generaÈors '
respectively, and so it has only been necessary to distlnguísh Èhe
former from the latter when discusslng data control' The syntax of
functton and generator function calls in ACL is the same as Èhat of
function calls in Pascal, and these calls both occur in expressl-ons (see
Ëhe descriptl-on of the syntax of ACL, later 1n thls thesls) ' The
pseudovariable method of reÈurnlng a value ls used in ACL: Ehe value to
be returned is bullt up durlng the executlon of an lnstance by roaking
asslgnmenÈs to the subprogram ldentifier, which 1s guaranteed to be
accessfble (see SecÈion 4.3.4.2').
The dat.a conÈrol effecÈ of functfon and generaÈor function values
tn ACL will nor¿ be descrlbed uslng the data control model, adopting Ehe
same scheme as was used in the description of functlon values ln Pascal:
an RI{ l1nk is establlshed from an lmpllciËly-deffned local (write-only)
variable of the instance concerned to the enÈlre known llst of the
call1ng lnstance. Thís descrlpEion scheme has some unsatlsfactory
aspects, already mentloned in relation to Pascal, but its use is
continued for reasons which were glven earlier. The data conÈrol event
concerned 1s:

FV = { if (class(deflnltion) =functÍon)
or (class(definition) = genfunc) then
link(definitlon of RW"rll.¿, whole of KNOWN"aller, RI{) }
and this evenE ls regarded as occurring at block entry for procedures
and functions, and at main seCtlon entry for coroutines, generators and
generat.or functLons, although lt has a null effect 1n the case of

150
fnstances of procedures, coroutines and generators' FurÈhermore, 1t is
nor.f necessâry to sÈate a partlal ordering wtth respect to the events
occurrlng on entry to a procedure or funcÈlon lnsÈance: Èhe effect of
the event IRO musÈ be computed before thaE of the event FV, or else an
aËtempÈ may be made to es¡ablish a link from a non-existent enÈry
(that
of the pseudovariable for a funcÈion lnstance, which is inserted r'rhen
the functlon identlfier ls inherited). Such a Partial ordering 1s not
necessary in the case of generator functlons ' sifice the pseudovariable
entry ls lnserted as part of initlaltzaËlon sectfon entry and the
establishment. of the link occurs at maln sectLon entry.
Before discussing Èhe actual return of a value to the polnt of
call, lt must first be stated that a generator function instance in ACL
may only execuËe an MR operatfon when Èhe masÈer and caller varlables of
Èhe instance colnclde; slurllarly, the terminatlon of a generafor
functlon instance can only occur \rithout. error in the same
circumstances. this res¡rlction, whlch clearly iurplies that MR and GR
operaÈions in generat.or function lnstances have the SAme sequence
control effect, means that 'rreturning fromtt a generator functlon is
always accompanled by the transmission of a va1ue, maklng the operatlon
of this kind of subprogram easier to understand' This restriction does
not appear to be too severe, ln the llght of the llkely uses of
'generator functions.

Thus, 1t 1s on the executlon of a PR operatlon that function


lnstances actually reLurn their value, and generator function lnstances
do so when they execute elther a GR or l{R operatÍ-on' NoÈlce thaÈ
generator functlon lnstances do not return a value on exit from their
lnitiallzaÈion sectlons (that 1s, on executing a TI operaÈlon) '

4.3.4.5 Summa Res trictions and Disciollnes

The various evenÈs in the description of daÈa control in ACL all


occur at block entry; the kinds of block entry, and the events which
occur in each case, are summarlzed ln Table 4.4. Notice that ânY, or
all, of the events assoclated wtth a parÈ1cular block entry may have a
null effeet.

151
Table 4.4 A Surnmary of the Data control Events for ACL

Kfnd of Block EntrY EvenËs Occurring

main program bl-ock entry LD

procedure and funct.ion block entry LDTIRO'IRI^I,


IS, rM,IV, FV

lnltlallzat.lon section entry for coroutines, LD, rRo, rRI^I,

generators and generator functlons rsrrMrrv

main section entrY for corouÈlnes, cs ,cM, cv, Fv


generators and generaÈor functlons

For a given block lnstance "btt, the names conÈalned ín all of the
lists assoclaEed with that instance by vlrtue of declarations in the
program texÈ (that is, lists such as LoCA\' INHRI'íb and ISEE\) musL be
dlfferent from each other; furthernorer ânY scalar ldentlfiers
lmplicltly inherlted lnto a block lnstance musE also be different from
those in the above llsÈs. Because of this restrlctlon' and Ehe absence
of lnplicit scope rules of the klnd found in Pascal, the only Partial
orderlng deflned on Èhe events comprlsing block entry in ACL is the one
gl-ven previously: í.n the case of block entry f or procedures and
.functions, the effect. of the evenE FV must be evaluated after thaE of
the event IRO for that block entry. This slmple partlal ordering 1s 1n
contrast to Ëhat necessary fn the descrlptlon of data control 1n Pascal
(recall Figure 4.25).
rrinstance referencett,
As part of the rrfnstancett, aS opPosed to
approach adopted in ACL (see sectlon 4.1), the copying or "clonlng"[89J
of lnsEances is prohibited. Consequently, value parameters must not be
lnstance varlables, nor may they contain lnstance variable's within their
structure; either of these klnds of value parameters r^rould lead to Ehe
copylng of Èhe instance(s) contained in the actual Parameter.
trextent" of
sínilar to the concepË of "reach" ln Algol 68 tl50l, Che
a maln program, coroutlne, generator or generator function is deflned to
consist of all of the Program text enclosed by its deflnlEion down !o,
but not includingr anY nesÈed coroutí-ne' generator or genelator function
definlllons; notlce thaÈ a given exlerrt may lnclude an arbltrary number

152
of levels of procedure and funcElon deflnlÈlons' In an attempt Èo
lncrease the correspondence between the sÈructure of the text of an ACL
program and the structure of l-ts master tree at run-ÈÍ-me, instance
varlables (and sÈructures containlng lnstance varlables) may not be Rf'I
inherited lnt.o a coroutine, generaÈor or generator functlon definitíon'
nor may they be passed as RI,I reference parameters. From the deffnltlon
of the IC operation (see Sectlon 4.2.4), and Èhe facÈ that Rtr{ access to
the appropriate lnsÈance varlable l-s necessary for instance creatlon' ft
l-s clear that the declarat.ion of an instance varlable always occurs
wlthln the extent of the deflnitl0n of the boss of any instance stored
ln the lnstance variable.
Furthermore, slnce RO access to a definitíon ldentlfier is required
both for the declaratlon of lnsÈance variables (recall that these
varlables are strongly typed) and instance creatlon, and slnee these
identlfiers cannoÈ be passed as Parameters ' all instances of a
corout.lne, generaÈor or generator function musE be created textually
wlthln Ëhe block ln ¡vhich the subprogram deflnítlon aPPears; this also
conEributes to a close corresPondence between Èhe statlc and dynamic
structure of an ACL ProgrâD.
However, the occurrence of lnstance varíables ln dynanic variables
between statlc and dynamlc
.can lead to a very poor correspondence
program structures; thts poor correspondence arises because of Èhe
possibllity of multlple references to dynamic varlables, and the fact
thaÈ RO access to a pointer is sufflcient to a1low the value of the
dynamic variable vrhtch it lndicates to be changed, among other reasons'
The possibility of lnstancê varlables ln dynamic varlables !'tas included
fn ACL because of its usefulness in certain sítuaÈions, and ln spite of
the fact that its use can lead to programs which are dtfflcult to
undersËand.

In addiÈ1on Èo the restrl-ctions detailed above, tt is worth


descrlblng a dlsclpllne which, where it can be employed, leads to a
partlcularly close corresPondence between statlc and dynamic program
structures:

avold instance variables in dynarnic variables'


. never lnherlt a corouÈlne, generator or generator functlon

t53
tdenÈifler lnto a coroutine, generaÈor or generator funcElon, and

. never inherit a Èype tdentl-ffer lnto a coroutine' generator or


generator func¡lon ff the corresponding type lnvolves an lnstance
type.

Adherence to this dlscLpllne will ensure that lnstances of a


deftnltlon can only be created 1n the same extent as that ln ¡^¡hlch Èhe
definition appears, and so the nesting relationships of definitlons of
coroutines, generators and generator functions r¿ill be directly
reflected in the shape of Ëhe master tree at run-time. IlnfortunaËely,
thls disclpline cannot always be followed (for example, 1n the case of
direct or indirect recursÍve deflnltion) and so 1t has not been enforced
1n ACL.

A subprogram lnstanc. t'll" is said Eo exhl-b1È "procedure-like"


behaviour if, when it is called by some other lnstanct "i2", conErol
riext enters the latter instance via a return from the former' There are
A number of \rtays in which genera¡ors, generator functfons and
l-nittalizing (coroutine, generator or Senerator function) lnstances in
an ACL program may not exhlbl-t procedure-l1ke behaviour. For example, in
the fragnent of a masËer tree depicted in Flgure 4'38(a), the generator
lnstance "Gtt has been called by the coroutlne instancertcltt, using a GC
-Operatlon; now, 1f the lnstance rrG'r executes a CT operatlon to transfer
control to 'rC2rr, whlch Ehen executes an l-fR operation, the situatlon
shown in Figure 4.38(b) results. Thus' conlrol has returned to the
calling instance ("Cltt) by a route which does not involve the called
lnstance (rtctr) returnLng control to l-t'

(a) (b)
Flsure 4.38 An Ex arnple of a GeneraËor not Exhlblting
Procedure-like Behaviour

L54
In ACL, procedure-llke behavlour 1s enforced ln the case of
generator functlons; this is necessary slnce calls on generator functlon
Ínstances occur, ln general, aS part Of expreSSlon eValuatlon and so lt
ls essenElal to ensure that control returns to Ehe caller as a result of
the generator function instance executlng a GR or MR operation' or as a
result of it termfnating, and thereby contributl-ng a value to the
expression evaluatlon in progress in the caller. Thls behaviour is
enforced using a run-Ëlme checking scheme descrlbed in Chapter 6 ' The
possibllity of using cornpile-tlme enforcement of data control
restrlctions to prevent situaÈions such as that in Flgure 4'38 arising
was Ínvesttgated but, partlcularly in view of the actions whlch may be
taken by procedures and functlons, it was found that this approach 1ed
both to a very complex se! of restrictlons and a large amount of
elaborate compile-time checking. In contrast, the run-time scheme
adopted is both sirnple and efficlent, adding l1tt1e to the run-Elme
overhead of an ACL Program.

Procedure-like behaviour is not enforced for generators and


Lnlt1allzíng instances in ACL. In facÈ, as already demonstrated in the
solutlon to the telegrams problem presented in Chapter 2, lt can
someÈimes be useful for generator instances not to be bound to behave ln
a procedure-like ûanner (such as node 2 in Flguîe 2' 1) ' However, caller
'variables are only set to I'n11" on Èhe execuÈ1on of a GR or TI operation
(see Sectlon 4.2.4.3), and hence generators and lnitializing generaEor
functions whlch do not exhlblt procedure-llke behavlour become
effecÈively "dead" since they cannot be called, their caller variables
being already in use. A1so, although it ls not prohiblted for any
sequence control operation to be executed in, or on behalf of, an
lnitializlng coroutlne, generator or generator functlon lnstance' lt 1s
recornmended tha¡ neither GR nor ìfR operations be so executed' and tha¡
directed transfer operations with targets outslde the subtree wlth the
initl-alizit'tg ínstance as its rooË should also be avolded 1n
lnftiallzation sectlons (and in procedure and function lnstances where
the operation is executed on behalf of an lnitlaLLzlng instance), 1f
possible.

Apart frou belng able to transmlt lnstance varlables of the


strongly typed kind as (RO reference) parameters in ACL, the language
also allor,rs a programmer to speclfy that a parameter 1s an lnstance of

r55
any coroutine, generat.or or generator function definttion whose
conÈlnuatlon parameter llsÈ has a parElcular
ttform" (see Chapter 5)'
This klnd of weakly Èyped instance Parameter ls useful in the
parameterization of some subprograms whlch Ëransfer conÈrol to
prevlously created lnstances of more than one deflnÍtl-on.
FÍnally, note thaE violations of the prLnciple of opaqueness can
occur in an ACL program through the use of pararneters. Although the
princfple 1s not. enforced in general, the resErlctions stated when
in¿roducing the sequence conËrol operaËions of ACL make lt clear that lt
Ls enforced in the case of Eransfers of control: a direcËed transfer of
control is only legal 1f the princlple of opaquenesg would allow the
Lnstance varlable containlng the target lnstance to be accessible to the
lnstance executlng the transfer of control.

156
CHAPTER 5

THE SYNTAX OF TIIE LANGUAGE

5.1 Introductlon
A full descrlptlon of Ehe syntax of ACL 1s gl-ven ln Appendix A'
usLng the same kind of 'rsynEax diagrams" used to descrlbe Èhe syntax of
PascalintT5l.AsinthelaËterdescripÈionrsomeofthenon-terminal
syrnbols used in syntax dlagrams in Appendix A are noE defined by another
syntax dlagram, but raÈher consíst of a generic non-Èermlnal symbol
whtch 1s defined by a syntax diagram, qualified by a context-senslËive
"remarkt'. For example, the symbol "definlElon identifíertt,
which aPpears
in the syntax dlagrams for "type" and "sequence conÈrol operaEionrr'
refers to an itidentlfier'r which has been introduced as the name of a
coroutlne' generator or generator functlon, by appearlng after the
tt or ttgattlttt"tt in a trdeflnÍng
reserved word ttcorollE:llllqtt, ttggat"E
'declaratlontt.

Appendlx B contalns a number of ACL programs and an examlnation of


those programs gives some ldea of the naÈure of ACL's syntax'

5.2 Declarations
There are three kinds of declaration in ACL: defining declaratlons'
lnherlting declaraÈlons and forward declaratlons, only the first and
last of whlch occur in any form ln Pascal; furthermore' ACL is unlike
Pascal in that lt is not necessary that the declaration of all labels
precede that of all constanEs, nor Èhat the laEter must precede the
declaration of variables, and so orlr within a particular seE of
declaraÈions. The followlng ordering is, however, lmposed on the
declaratlons appearing at the head of a partlcular block: an identifier
may not be used in a declaration untÍ| it has ltself been declared'
Thls

ensures that the declaratíons at the head of a block can be undersÈood

157
via a single scan, and also means that the language lends itself to one-
pass compilation.

5.2.L Def in ine Declaratlons


These declarations deflne new fdentifiers for use wlthin a block,
and posslbly withln enclosing blocks. As a consequence of the expliclt
scope rule scheme adopÈed in ACL, all definlng declaratlons must include
an lndication of the herltabtllty of the ldentlfier belng deflned' This
ttEit"t.tt ot
indicatfon is in the form of either of the reserved words
rrheritab il
, which have the obvlous meanlngs'
subprogran definltlons 1n ACL, lncluding Èhat of the maln PrograE'
have stmilar forms to those in a Pascal Program: Ëhey consist of a
headlng, which may include a Parameter llst, a declaraËion part, and a
body. Procedures, functions and the main program have one kind of body
(called a "blocklt' in the syntax dlagrams), and coroutlne, gefierator and
generaÈor funcËion definltlons have another (a ttblock2"); this
dlfference arises because of the manner in whlch the TI operation
ÍnÈroduced in Chapter 4 is rePresenËed syntactically 1n ACL' Ilnlike the
other sequence control operaÈions, the TI operation is represented by
dlvidlng the body of a coroutl-ne, generator or generator function
deflnltfon lnto two texÈual sectlons: the inltializaÈ1on section and the
rnaLn secEion, which were mentioned in the previous chapËer' Ttre fírst of
these, which may be omitt.ed, is brackeÈed by the reserved words
trfnitbeeintt and t tElteút,, whereas the latter secEion is enclosed in the
tt¡*inrr and
same kind of brackets used to delimit a ttblockl" (that is,
ttendtt). The TI operatton ls lmplicit before the flrsÈ statement of the
maLn section, and hence omiÈtlng Ëhe initiallzatlon secÈion lmplles that
this operatlon {s Èo be execuËed immediaÈely that control enters Ehe
subprogram for the flrst tiue. The syntactic rePresenÈaÈlon chosen for
the TI operatlon glves a clear textual separation of L¡It'laLlzatlon
actions from the remalnder of the actions of a subprogram, unllker sâYr
the sltuaÈlon ln Simula.
The syntax graph for "typ." in ACL dlffers from the corresponding
one in the definition of the synt.ax of Pascal only in Ehat the instance
data structure ('rinst.ance of ...") is now Present. IncorporaÈlng the
Lnstance data type into ACL in thls partlcular I'tay means that other type

158
constructors may be apPlLed to it, maklng Possible structures such as
arrays of lnstance varlables and lnsÈance varlâbles as flelds in record
structures.
Another difference beÈIüeen the syntax of ACL and that of Pascal is
the fact that "nil" Ís a predef lned constant l-n ACL, as 1t l-s ln at
least a number of the lmplementations of Pascal, whereas the syntax
dlagrams for Pascal glven fn [75] show it as a reserved word, and one of
the alternatives for an ttunsl-gned constantrr'

5.2 . 2 Inheritlns DeclaraEi.ons

Inherltl-ng declarations represent the expl1cít lnheriLor agreement


part of the expllclt scope rule scheme described ln chapter 4; this kind
ttg!!|tt, indicating RW
of declaratlon starts with Ehe reserved word
lnheriÈance, or wlth t'seen", denotlng RO i-nheritance. Apart from the
identifier belng lnherlted, there are a number of candidates for other
lnformatlon t.o be specified in lnheriting declaratlons, such as the type
of inherited variables. In vLew of the facE that the expllclL scope
rules of ACL will, ln general, mean longer Program texts when compared
with an equlvalent Pascal program' 1t rlTas declded to require the
speclflcaÈion of only the class of an lnherited tdentifler (whether it
to
_is that of a constant, variable, procedure' or whateVer), in addition
the ldentlfier itself.and the klnd of access requlred in the block
concerned. TtrÍs signLficantly improves Èhe readablllty of programs'
wl-thout a slgnlflcanÈ further increase Ln their textual length'

In accordance with the design decislons ouÈllned fn Chapter 4, the


(RO) inherítance of labels and the RI{ lnherltance of identiflers other
than those of variables are excluded by the syntax of ACL.

5.2.3 Forward Declaratlons

A forward declaratlon may be used in an A'CL prograu to announce


that a type or subprogram deflnltlon identifler is to be deflned (using
a deflnlng declaration) later, aE the sane block level as the forward
deelaraElon. All forward declarations in ACL commence wlth Èhe reserved
word "forr.rdtt and Èhus are clearly distlnguished from deflning and
lnheriting declaratlons, unlike the situation 1n Pascal, where they are
elther an anomalous form of subprogran defi-nltion r¡hose declaratlon part

I59
ttforward" or they
and body are replaced by the predeflned identlfl-er
occur irnplicltly (1n the case of some pointer Eype definitions see

later). Tfhe purpose of forward declaratlons in ACL is to allow the


specl-ficatlon of cerÈaln data structures, mutually recursive procedures
and functlons, and certain relationshlps between members of a set of
coroutlne, generaËor or generator f.unction lnstances.
Forward declaratlons in ACL require the speclficaEion of some
informatlon ln addltion to the identlfier concerned: in all cases ' its
cl-ass and herltabillty must be specÍfied, and, depending on lts class'
some further informatlon may be required. In the case of a tyPe
fdentifler' no addiEl-onal ínformation ls required'
BeËween fts forward declaration and its definlng declaration' a
forward declared type ldentifler rnay only aPPear in the definitlon of a
poinËer type (the second llne of
tttyP." in Appendix A). Furthermore' Èo
enable the use of one-pass compllation, such e forward declared tyPe
ldentlfier, or any identifler denoting a type which ts defined in terms
of such a forward declared type ldentl-fierr mâY not be lnherited inÈo an
l-nner block, nor may it be used as Ëhe tyPe of a Parameter in a
parameter llst.

In the case of the forward declaration of a subprogram definition


'ldentifler, the "form" of Ëhat subprogram's parameter 1|st(s) {s glven,
as well as the identífíer iÈself and its heritability; ln addltlon' ff
the subprogran concerned 1s a function or generator function, the type
of the value returned is also speclfled. The 'rparameter form" provided
wlth the forward declaratlon of a subprogram l-denttfler contains only
the types and transmlsslon modes of each of the parameters, in order;
thfs information is sufficient Eo allow the one-pass compilation of
language feaLures involving Ehe transmlssion of parameters to instances
of a forward declared subprogram, with Ehe same level of compile-time
checklng as with those whose definltlons have already been encountered'
The goal of one-pass compilation l-s also the reason for the restrictlons
on the posslble uses of forward declared type tdentlflers prior to thelr
definltion.
The differences between the approaches Èo forward type ldentiflers
adopted tn ACL and Pascal is illustrated by the fragments presented in
Figure 5.1; that in Figure 5.1(b) ls taken directly from t75l' In Figure

160
5.r(a), the ACL verslon, the type "persontt is announced by belng
declared forward; lt is then used 1n the deflnltton of the type "llnk",
ttperson". In the Pascal
and then the latter ls used ln the deflnltlon of
versLon, glven ln Flgure 5.1(b), the type 'rl1fik" is firstly deflned in
terms of the unknol¡n ldentlfier rrpersonrr; Pascal makes an excePËlon of
the rule that tdentlfiers must be declared before they are used, for the
case of a type l-dentlfier used tn a polnter tyPe deflnition, regarding
Ít as havlng been lmpllcitly declared forward, 1f that is necessary' The
second line of Figure 5.1(b) then contalns the definltlon of the ËyPe
ttperson,t in terms of "linktt. Sone dlfflcultles which arise in Pascal ,
partlyasaconsequenceofitslnpll-cltforr.rardtypeldentlfiers'will
be dlscussed shortlY.
forward privaÈe tYPe Person;

private tYpe llnk = fPerson;


person = g! ... next: lfnk "' end;

(a)

type link = fperson;


person = record ... nexE: link "' end;

(b)

Fl-gure 5.1 Speclfylng Recursively-deflned DaËa Types


tn ÀCL and Pascal
Similarily, the example used by Jensen and Wfrth to illustrate
rnutually recursive proeedures and functlons 1n Pascal is reproduced in
Flgure 5.2(b), wLth the ACL verslon of the same prograu fragment in
Flgure 5.2(a). Ttre provision of the parameter form with the forward
declaratlon 1s an aid in the process of understanding the verslon
wrltten in ACL, as 1s Ëhe fact that the full speciflcation of the
parameter llst of a subprogram must be given with its definition, and is
checked against the parameter form glven ln any forward declaration; the
Ímportance of both of these aids increases as the textual dlstance
between the forward declaratlon and Lhe definition increases'

161
forward herltable procedure Q(value T);

herl-tab1e procedure P(p¡fva.ce. value Y:T);


seen var a; procedure. Q;
besin Q(a) end;

heritable procedure a(p:-ivate value x:T);


seen var b; orocedure P;
begfn P(b) end;

besln P(a); Q(b) end.


(a)

procedure Q(x: T); forward;

orocedure y:T);
P(

besin Q(a) end;

Drocedure Q; {parameters are not rePeaÈed}


besln P(b) end;

bestn P(a); Q(b) end.


(b)

Fteure 5.2 Specifying Mutually Recurslve Procedures


l-n ACL and Pascal

5.2.4 A Difffcul tv of Pascal .A.voided in ACL

Consider the Pascal fragmenE depicted in Flgure 5.3(a), in which


the definitlon of the type "4" lnvolves a reference to a tyPe identlfler
rlBrt, for whlch there ls both a definitlon at the outer block l-evel and
one at the lnner level, the latter belng after its use in the deflnition
of rtArr. This sltuaÈ1on is discussed by tr'IeLsh eE al' [156] and they
outllne aË leasÈ two posslble interpret.atlons in such cases:
(1) the outer definltlon for rtBrr ls used in the deflniÈion of 'h",

and

(2) an error has occurred, since 1t is the inner definltion of


rrBrr

whfch applles, but this definition occurs afÈer the ldentffier's


use in Ëhe definition of |tAtt'

L62
The flrst of these Lnterpretations ls used ln sone lmplementatlons
of pascal and is adopted by l4latt in his descrlptl-on of Èhe context-
sensltlve syntax of Pascaltr54l, although (as polnted out by welsh et
al. ) thls interpreEatlon ts precluded by the descriptlon of Pascal ln
Èhe ttReport" in [75], since 1t would mean that an ldentifler can have
more than one "associatl-on'r within the procedure or function ln which it
1s declared (deflned). Ttre second 1nÈerpretatlon 1s not easily
implement.ed in a one-pass eonpller, and does not seem to have found
favour among the lmplementors of Pascal'

type B = ...i type B = ...i

procedure P orocedure P;
type A = g!ry. [f ..10] of B;
B = ...i
begin end;
(a) (b)

Fieure 5.3 Tr,ro Pascal Fra gments lllustraÈing Situatlons


Subject to InterPretation

Furthermore, as illustrated by the Pascal fragment in Figure


5.3(b), the first ínterpretaËion above works agalnst, the facillty,
'described earller, for lnpliclt forward type ldentlfiers ln polnter type
deflnltlons; 1f the flrst interpretation is applled to Figure 5'3(b)'
rrlBl' cause an
the outer def initíon of 'rBrr is used, rather than havlng
rrBtr whlch 1s then
i-mpllclt for¡,rard declaratlon for the ldentlfler
satÍsfied by the later deffnition of that ldenÈifier' Some

lmplemenLatlons of Pascal use the fírsÈ lnterPretation ln cases such as


rrBrr 1n
Flgure 5.3(b) and this leads to the anomaly that the meaning of
rrlBr' ln Flgure 5.3(b) can be changed by deleting the def inltion of rrB'r
ín the outel: block. OÈher implementatlons of Pascal, and the descriptlon
of the language given by I^IaÈt, make an exception of a type ldentlfier in
a polnter type definltlon and use the fÍrst interPretaÈion only if the
ldentlfler is not deflned aÈ the level of the polnter type definltion;
this results fn a dlfferent klnd of anomaly: lt means thaÈ two seeningly
sfmllar program fragments, such as those |n Figure 5.3, are regarded in
qulte dlfferent ways by the conpller.

163
Becauseoftheexplicltscoperuleschemeusedinthelanguage'
none of these questlons of lnterPretation, and the consequent
dlffl-culties, arlse ln ACL: before a type ldentlfi-er may be used in any
type deflnltíon, it rnust ltself be either defined, inherlted or forward
declared at that block level, thus maklng lts assoclation perfectly
clear.

5.3 Parameters

The formal parameter listof a proeedure or functlon in ACL appears


after the deflnition idenLifier, as 1t does Ln Pascal' The
initlaltzatlon and continuation parameter lists assoclated with
coroutlnes, generators and generator funct-lons also aPpear after the
appropriate definition ldentlfier; Ehe lnltlaltzation parameter llst is
preceded by Ehe reserved word "inlEtt and the contlnuation list by
"gq". Either of these parameter llsts may be omltEed, 1n which case
the identifying reserved word ls also omÍtted'

The herttabitity of each formal parameter identlfier must be


specifiedr âs with Lhe defj-nitlon of any neür ldenEifiers, and the
tt-pr.ittlg" ot
transmlssion mode must be glven; the former is lndicated by
rrherltable" (as in definlng declarations) and Èhe latter by one of
t' (RI^I ref erence parameters), and
.t|"..g" (RO ref erence parameters), "Iodif
rleluerr (value parameËers), Notice that there is no default parameEer
transmlsslon mode, as there 1s 1n Pascal; 1Ë rtas felt that rrith three
alternatives lt shoulcl always be necessary Èo lndlcate which hras
lntended. The reserved r¿ord "modiftt was chosen for RI^I reference
parameters, ln preference to the "vartt used 1n Pascal for the sane
transmisslon mode, to emphaslze the slmilarity between its data control
eff ect and Lhat of RI,f tnheritance (wTrich also uses "modif "); likewise'
.ttg=gt' is used for a parameter transmlsslon mode and a statement of
lnherÍtor agreement whlch have similar effects'
The type of a formal parameter may be specifled in one of a number
of ways:

siruply as a type identlf ler, r^rhlch ís then interpreted in the


context of the enclosing bloclc level'

as Èhe reserved word ttprocedurerr or "_funç!.roqtt folloq¡ed by the forn

L6¿+
of Èhe subprogram's paraneter list (such as would be glven ln a
forward declaratlon for the subprogram) and' 1n the case of a
functlon, the type of the value returned; thls ktnd of parameter
type 1s used when a procedure or function ldentifl-er 1s being
transmitted and can only occur legally in conJunctlon with the RO
reference transmission ruoder and

as one of the reserved \üords ttcorouÈ1nett, ttqeneraÈorrr or


ttg"tf
*."tt

followed by the form of a cont.lnuation parameter list and, for


generator funcElons only, the type of the value reÈurned; this kind
of parameter tyPe, called a rrgeneral lnstance ParameÈert" slgnifies
that the corresPondÍng aetual parameter may be an instance of any
subprogram of the approprlate class (coroutlne' generator or
generator f unction) rrrhose continuaÈl-ori Parameter llst is of the
specifled foru and, if 1t Ls an instance of a generator functlon'
whose return type is the same as that of the formal Parameter;
because of varfous restrictions stated elsewhere' thls Parameter
type fs also only legal in combinatlon wlÈh the RO reference
transmlssion mode. (An example of a general lnstance parameter is
to be f ound i-n Section 8.4 of Appendtx B')
The informatlon required by these parameter tyPes 1s sufflcient in
each case to permlt complete checking of Èhe compaËíbllity of formal and
actual parameters during compilatlon (l¡hich ls more than ls posslble in
some comparable situaÈlons 1n Pascal) and to allow one-pass compllaÈl-on
of subprograms havlng these parameEers.

5,4 Statements

The stat.ements of Pascal are all Present 1n ACL' with some


additions; the latter mainly result from the lnt.roductlon of the extra
sequence conËrol operatfons described Ín Chapter 4. In A'CL, only
variables whích are not instance variables üay apPear on Èhe left-hand
side of assignment statements; function and generator functlon
deflnition identiflers may also occur there' slrice the pseudovarlable
neÈhod is used to return values frorn both of these kinds of subprogram'

A procedure call 1s denoted ln ACL uslng the same notatfon as that


used in Pascal: the procedure ldentifier followed by an argumerit (actual
parameter) llst; a funct.lon call occurs as the result of speclfylng a

165
functlon Ldentlfier and an argument |lst ln an expression (at the
ttfactort' level). Procedure and functlon return (the PR operaÈ1on) occur
lnpllcltly on control reachlng the flnal "endt' of Ehe appropriate
subprograrn def lnLtlon.

Instance creaÈion (Èhe IC operatlon) bears a syntactlc slnflarity


to asstgnmenE: it consists of the instance variable, a "becomes" synbol
(tt:=tt), Ëhe reserved word ttcrggtett, the approprtaÈe def inition
tdentlfler and an argumenÈ ltst providing the actual initiâllzation
parameter values. The CT operaÈÍon, and the GC operaÈlon when applled to
tt@ttor
a generaÈor lnstance, are represented by the reserved word
ttd", respectlvely, followed by the approprlaÈe lnstance varlable and
an argument lÍst glvfng actual continuaÈlon parameter values; callíng a
generaËor functíon lnstance (also a GC operaÈion) l-s achieved by giving
the approprlaÈe lnstance variable and an argument list ln an expression,
agaln at the level of "factor'r.

The GR and MR operatlons are represented syntactlcally by


I'exitr',
staÈemenÈs consisÈ1ng sinply of Èhe reserved word "r"tttg" or
respecÈ1vely. The terminaÈLon of a coroutine' generaÈor or generator
function lnstance occurs lmpllcltly as a result of control reaching Ehe
flnal t'end" of the corresponding definitlon'

5.5 Predef l-ned Pro cedures and Functlons

There are a number of procedures and functions whlch are predefined


1n ACL, but are not Present ln Pascal:
ttclock" fs a functlon, without Parameters' which evaluates to an
integer value equal to the central Processor tlme, in milllseconds,
used so far by this Job; Èhis functlon is also described in Chapter
13 of [75],
trcurrent" is a funcÈion w1Èh one instance Varlable as a parateter
and lt evaluates to "true" íf the lnstance in the varlable ls the
currently executlng one, and to rrfalserr oEherwlse,
trdeletett is a procedure r¿ith a slngle instance variable parameter
and lt sets Ehe value of thls varlable to'rno_instancett; this
actÍon may, or may notr have storage management consequences (see
Chaprer 6),

166
rrhaLtr' ls a parameterless procedure whlch stoPS program executlon
and results in a post-mortem dump being printed'

is a procedure, also wlthout Parameters' whlch prlnts a


,,heapmaptt

representatlon of the currenÈ utlllzatlon of the heap area; thls


procedure was also present Ln Pascal 'It'[104] and the
representatlon prlnted ls slmllar to the "memory maptt or
"checkerboard" described by Knuth[85],
,tnone"1s a function whÍch takes a sl-ngle instance varlable as a
parameter and it eValuates Èo 'rtrue" 1f the value in thaË lnstance
ttfAlsett oEher\dise, and
varlable is ttno lnsÈancetr, and to
. ttpmdtt is a parameEerless procedure which slmply PrlnÈs a post-
mortem durnP.

In addition, two of Ehe predefined procedures described by Jensen


and l{lrth have different definitions in ACL:

. ,,nerr,, Èakes a slngle poinÈer varlable as ít,s parameter and


allocates a dynamic variable which 1s sufficiently large to
accornodate a11 posslble combinations of variants of any record
structures withln lts ÈyPe, and then seËs the pointer variable to
indicate the allocated variable (the version of "new" described for
Pascal Ln [75] nay be supplied with Èag field values whlch are Lhen
used to minimize the storage allocated, consistent r¿ith the
varlants corresponding to the supplled tag field values), and
. ttdispose" also takes a single poÍnter variable as its argument (the
verslon 1n t75l also takes tag fleld values) and sets Ëhls variable
ttdelete", thls assi-gnment
Ëo the value "nil'r; as with the procedure
mâY, or may not, have storage managetent iurplicatlons'

In view of the approach Ëo data control adopÈed in ACL' and


partlcularly because of the princlple of non-lncreasing access and the
notion of RI{ access, it ls necessary for varlables passed as certain of
the acÈua1 parameters to some predeftned procedures Eo be Rtr'l accessible
1n Ehe calling block. Table 5.1 contalns a suÛrmary of Ëhe predefined
procedures for which thls is true and the Parameters concerned; for
example, t'dispose(p)" ís only allowed if the pointer varlable "P" is RI'l
accesslble aÈ Èhe point of call, which can clearly be determined at

L67
comPfle-tlme.

Table 5.1 Predeflned Procedures 1n ACL Requlrlng RI'l Access


to Actual Parameters ,

Procedure Parameters for whlch RII Access J-s Requl-red

delete the slngle Parameter


dlspose the sfngle Parameter
netr the slngle ParameËer
Pack the thlrd Parameter
Put the slngle Parameter
read, readln all except the ftle (if speclfl-ed)
rewrlte thé sfngle parameÈer
unpack the second Parameter
write, wrfteln the flrst ParameÈer, l.f lt ls a f1le

168
CHAPTER 6

THE IMPLEI,IENTATION OF THE LANGUAGE

6. 1 Overvle¡¿

The programmlng language ACL has been implemented using Pascal'P"


a portable imPlemenLaËion of (most of) Pasca1 described by Norl et
al. [115], as a base; Pascal'P' conslsts of a pair of Pascal programs:

a compller, producing object code (call it "P-codett) for a

hypothetical stack computer, and

an lnterpreter, slmulaEing the stack computer by lnterpreting P-

code.

As a preliminary step Eo test the feasibility of uslng Pascal'P' as


the basis of a processor for ACL, the former was flrst nodifled so thaE
all actlvaÈion records were allocated on the same heap as dynamic
variables. In this lmplementation of Pascal, called Pascal'Il', there is
no run-time stack, although each actlvatlon record conEalns a "local
stackrr used for expresslon evaluatlon and for passing parameEers to
predeflned procedures and functions. The results of Èhe Pascal'H'
experiment, whlch is descrlbed Ln detail 1n [1041, ltere:

(l) pascal.P" deslgned for lts portabllity, is easlly modifled and'


furthermore, the cornpller/lnterpreter separation allows a flne
adJustment to be nade to the balance between actlons performed
durlng cornpilatlon and those at. run-time' through careful design
of the lntermedíate code, this adjustment belng more faclle 'than
is posslble vrith a compÍler, a run-time system and a (ftxed)
target comPuÈer, and
(2) the run-time efficiency of Pascal'H'1s sufficlenEly good Èhat it
Ls feasible to lmplement ACL Ín such a líay that all actlvation
records are allocated on the heap, even those for subprogram

169
instances 1n a program which l-nvolves no coroutlnes, and the
latter program can be expected to execute almost as effj.clently
as lt would with a stack-based lmplementation'
During the lmplemenEaEion of AcL, another advantage of Pascal'H'
emerged: 1Ë ls a useful staglng polnt from which to begin an implemen-
tatlon of a language, based on Pascal, contalning coroutines' This is
because Pascal'I1', lts lntermediate code (called "II-code") and Íts
hypothetical computer (the "heap computer") represent a form of the
activation record roodel wlth local stacks and conÈlnuatlon polnts, and
whlch is sufficient for the description of the run-tlme behavlour of
both Pascal and ACL. Although tt is true that the intermedÍate code 1n
the processor for ACL (which will be referred to as "C-code") contains
extra instructl-ons and its activaEion records have additional fields (to
ttactlVett), the basic model is
lmplement concepts such aS ttmâstert' and
the same as that which underlles Pascal'H"
The processor for ACL was developed fromPascal'II' using the nethod
of sÈepwise ref inemen¡ [159J , whlch I¡Ias also used as the basis of the
development of Pascal'P' by Arnroann [5 ] . The developmenE of the A'CL
lnterpreter was a process of nodlfying the Pascal'H' lnterpreter'
whereas the ACL compiler r¿as built frou scraÈch, and Èhen relevant parts
of the Pascal'H' compiler were borrowed as needed; developing the ACL
comptler by altering Ëhe Pascal'H' compller was noÈ feaslble since some
of the features of ACL made lt deslrable for the ACL compiler to have a
structure qutte different from Ehat of the Pascal'H' compiler'
The development steps used, whfch differ ln slgnlficanË ways from
those used by Ammann, are shol¡n in Flgure 6.1. The flrst sÈep was the
lntroductlon of Ëhe addltional syrnbols required by AcL and the
productÍon of a new symbol scanner. In the second step' the compiler was
altered to process the declarations of ACL and a revised syrnbol table
organizaÈlon rùas introduced Èo coPe w1Èh ACL's expllclt scoPe rules;
thls step also lncluded the analysis of the forrnal parameter llsts of
subprograms. Then, in the thtrd sEeP ' the compiler r'tas altered to
anaLyze the bodíes of blocks and the varlous staEements of ACL; this
st.ep also lnvolved the fntroductlon of objecÈ code generatlon 1n the
compiler, and the differences between C-code and H-code lead to a number
of changes ln the interpreter, as did the need to revise some aspects of

r70
the run-tlme structures. Thls thlrd step also lncluded the nodiflcaElon
of the compller so that the necesstty for a name to have the I{ access
rlght fn certaln sltuatlons 1s enforced, and the lncluslon ln the
lnterpreter of Ehe run-t.ime checklng necessary to ensure procedure-llke
behavlour for genera¡or funcElon lnstances. The result of the thlrd step
was a processor for ACL which correctly comptled and executed ACL
programs, but whlch dld not lnclude any storage management;
consequently, st.orage no longer needed during the executfon of a Program
\tas not avallable for re-use. The fourth and final steP ln Èhe
development of an ACL Processor was thaÈ of the introducÈion of a
reference count storage managenent scheme; durlng thls step' changes
were made to boÈh the compiler and the interPreter'

s¡rmbols

declarations

stat.ements

storage management

Ffsure 6. I Steps ln the Development of an ACL Processor


from Pascal'H'

The steps descrlbed by Ammann are: syntax tree' context-free


errors, compller tables, context-sensitive errors, address asslgnment'
and code generation. The reasons for the differences betr¿een Ehis
sequence and thaÈ ln Flgure 6.1 are that ln the latter case a Processor
Iras being developed from an exlsting one' and also thaË storage
management for ACL is not as slnple as it ls with Pascal.

L1tt1e more will be said about the first step i-n the development
process; one aspect of it whlch 1s of lnterest, however, is the facÈ
rr' It
that the symbol scanner in the Pascal'P' compi-ler treaÈs ' as a
co1on. Thfs expedfency \,{as presuroably adopted because 1n sltuations such
as frl ..2't, iÈ is only af Èer the second perlod has been consumed thât lt
rrl" rather
l-s clear that the scanner should return the lnteger constanË
Èhan a real constanE (such as tt1.O"); however, the Pascal'P' scanner

L7L
alrrays assuues on entry Èhat tt llas only one character ahead after
returning the previous syrnbol, and hence, before returnlng the integer
constant, the rr. . rr Ís converted to rr'
rr. Thls mearis Ehat the internal
rt..rr ln Pascal's syntax dlagrams |s
represenEatlon |n Pascal'P' of the
the same as thaE for ": "; that 1s, these Èlto symbols are not
dlstinguished. The symbol scanner 1n the AcL compller acts as a
rrI''2": ft
generator in the case of encounterLng a sequence such as
returns Ehe fnÈeger constant, but remembers the sÍtuation 1n which that
synbol was found and hence the fact that lt is two characters ahead of
the last symbol. Thus, on the next occasion that the scanner fs called'
it behaves ln a different manner to usual, reÈurnlng the symbol
corresponding to 't..r' buÈ not advancing Èhe input streaxo'

further detall w111 norü be glven on each of the three


Some
remainlng stePs ln the development process'

6 .2 DeclaraÈÍ-ons

Ihis step ln the process of lmplernentlng ACL' concerned not only


wlth the three kínds of declaration dlscussed ln the prevlous chapËer
(deflning, inheritlng and forward) but also with formal parameter lLsts,
involved only changes Eo the ACL compiler. Apart from the code necessary
to analyze Ehe syntax of these declaratlons, and to detect and recover
from conÈext-free syntax errors, the most importanÈ additions made to
the conpiler durlng this step hrere concerned with the implementatlon of
the expllclt scope rules and the resultant revision of the symbol table
organizatlon.

ïhe syrnbol table in the Pascal'H' cornpiler (which 1s identlcal to


thaÈ of Pascal'P') is a stack of ldentlfier trees, called "DISPLAYt';
each of these trees contalns elther the idenElfiers local to a
particular block or the field identlflers of a partlcular record type'
The reason for the posslbillty of having the latter kind of Lree on Ehe
DISPLAY stack is the marlner in which with sEatements are handled
by the
compller: as a record variable is encountered in a "r¿ith list", ÍÈs tree
of field identlfiers is pushed onÈo DISPLAY. For example, a wlth
staEement of the f orm 'lwith arbrc do ...'r would result in three further
ldenÈlfier trees belng present on DISPLAY for the duration of the
rrcrr
analysls of Lhe statement represented by "...rt, wlth the tree f or

t72
I'a"' An l-dentl-fler search in
aboVe that for rrbrr, whlch 1s above thaE for
the Pascal'H' compller Ínvolves examlnlng each of the ldentifier trees
on DISPLAY, startlng at lts top, stopPing the search lf the idenÈlfler
sought has been found or the botËorn of DISPLAY reached; the bottommost
ltem on DISPLAY ls always a tree contaínlng the predeflned ldentiflers
of the language. In this way, the implicit scope rules of Pascal are
correctly lmplemented, and predefined identlflers are treated as Lf'
declared in a block surroundlng the entire program'

The synbol table in the ACL compller, also a stack called


ItDISpLAytr, is sl_mllar to Ëhat used in Pascal'H', buÈ it diff ers in Èhat,
apart from trees of reeord field ldentlflers, its elements are trees
representlng the known lísts of the varlous block levels currently
actlve. Thls approaeh, whlch clearly has close parallels wtth the data
control nodel of chapÈer 4, involves having an entry 1n one of Ëhese
trees for each identifier known in the block concerned' The predefíned
ldentLfiers of ACL are held in a separate tree which is not an element
of DISPLAY. A known llst is pushed onto and popped from DISPLAY as the
analysls of that block is begun and flnlshed, respectfvely, in much the
same vJay as for the identlfier trees of blocks tn the Pascal'H'
compller. Sirn1lar1ly, the analysls of a wlth statenent in an ÀcL program
causes the appropriaLe fleld identifier trees to be present on the
'DISPLAY stack during Ehe analysls of the statement, as would occur in
pascal'H'; it l¡ould possibly have been more consistent for a wlth
statement to cause the construcÈion of an augmented known llst
contalnlng all of the ldentlflers accessible wiEhin the statemenE' but
ft v¡as decided not to adopt thls approach in view of tts relatlve
lnefficleney. An tdentlfter search ln the ACL cornpller starts at the top
of DISPLAY and examlnes each of the Ërees on Lt down to and íncluding
the first tree whlch is the known líst for a block; if the identlfier
\üas not, found during Èhis phase of the search, the tree of predefined
ldentiflers ls examlned.
The following deflnitÍons aPPear in the ACL conpller and describe a
node (the type 'ridenÈ1fier") 1n one of the trees on DISPLAY:

L73
tyÞe ctp = lldentifler;
alpha = EEgq arraY tl..8l of char;
accesskind = (readonly,readwrlte) ;
namekÍnd = (inherited,deflned) ;
ldentlf l-er = -packeg record
name: alPha; 111nk, rlink: ctP;
rlghts: accesskind; contParan: boolean;
case nkind: narnekind of
fnherlted: (defn: ctP);
deflned: (forwdecl, privaËe: boolean; )
' end;

All such nodes contain the characters maktng up the identifler


(only the first elght are slgnificant) and the pofnters llnking the node
fnto the btnary Ëree sÈructure; Ëhe node also contalns the access rights
of the ldentlfler ln the b10ck concerned and an fndicatlon of whether or
not thls is a formal contlnuatl-on parameter rârnê. The latter piece of
lnformatlon ls lncluded because of Ëhe manner in which access to
continuatlon parameters ls prevented ln lnLtíallzation sectlons: an
ldentifier search speclfles whether or not iË originaÈes from an
l-nl-tlallzation sectlon and lf it does Èhen an idenElfier whose
rrcontparamtt field fs tttruettis unacceptable as the result of the search'

A crucial atÈrlbuÈe of a node ls whether the tdentlfler is defi-ned


ln thls block or merely lnherited from some other block; If it is 1n-
(whose
heriÈed, a reference to the appropriate defining ldentlfier node
,,nklnd,, field has the value ttdeffned"), ln some other tree' ls the only
other informatlon requlred. A defining node conÈains' among oËher
thlngs, an lndícatlon of whether the identlfler Is private or herltable
(recal1 that all Ínherited identiflers are herlËable and hence this
lnformaÈlon was not necessary 1n the previous case) and whether this
ldenËifler has been forward declared and not yet defined'
I{hen the deflnlng declaraÈion for an identifler ls encounÈered'
that ldentifler may legally be either unknown or previously forward
declared (but not deflned); in the latter case' Èhe consistency of the
deflnitlon with the lnformation gtven in the earlier forward declaration
ttforwdecl" field for this identifier
ls checked and the value of the
node ls changed to "false". When a forward or inheriË1ng declaration
ls
encounÈered, the identlfler specified must be unknown ln the currenE
block. In the case of an lnherlting declaration, the idenEffler nust be

L74
present ln the knor¿n llst imnedlately below Lhe current one on DISPLAY,
and 1ts nod.e in that known list must be either inherlted, or defining
and herÍtable; also, the access rlghts at thls lnner block level must be
greater than or equal to those requlred by the inheriting declaratlon
being processed. Finally, the deflnlng node co which a llnk is
established as a result of this Ínheritlng declaration (which may or may
noË be tn the penultimate known l1st of DISPLAY) must represent an
ldentifler of the class speclfied in the lnherlting declaratlon and may
not be forward declared (but not yet defined) '
After an ldentifier search has been successfully completed in the
ACL cornpller, access rights information 1s always ava1lable in the node
returned by the search; however, if the iclentifler is an lnherited one,
it ls necessary to follow Èhe I'defn" pointer 1n this node to obÈain any
other information about it. In this respect, the ACL compller ls quite
different from the Pascal'H' compiler (and the Pascal'P' compller)' ln
which an identtfler search always returns a node sÍm1lar to a defining
node 1n the former.

6.3 Statements

The third step 1n the development of a processor for ACL was the
-first whlch involved the lnterpreÈer for c-code, sfmulatíng
the
operatlon of a hypothetical "coroutine compuÈer"' The structure of
st.orage wlthín this lnt.erpreter ís much Èhe same as that in the
Pascal'H'interpreter, which is descrlbed in detall fn [104]: there fs a
serles of tables holding those user Program constants whích cannoE fit
fnto lnstructlon fields (such as large integers, real numbers and sets) '
an array which contains Èhe assembled c-code lnstructlons, and an array
representing the heap area. There are also a number of reglsters 1n the
ACL lnterpreter, all buL the last of r,rhich are also present 1n
Pascal'H':
ttPC", the program counter, an index lnto the C-code array, gfvíng
the next instrucLion to be executed,
rrMAIN", indícaEing the (base of) the mafn program actívatlon record
wtthin the heap,
t'FP", the free l1st polnter, polnting to the flrst obJect on the

L75
free storage list wlthln the heaP,
ilAp,,, lndicatlng the currenEly executlng acÈlvatlon record (that
isr ln Ëhe notatlon of chapter 4, the actlvatlon record for
ttcurrenLtt),

of
"SP", the stack pointer, whlch gives the top of the local stack
the currently executing activatlon record,
whlch ls used to hold a re-ference t.o an acÈivaËion record
ilNTI¡JApil,

abouÈ to galn control, and whose purPose is mainly concerned with


paraueter transmlssion, and
[DYN", a register noE present ln Pascal'H', whích lndicates the
actlvatlon record for the coroutlne, generator' generaÈor function
or maln program lnstance r¡hlch most closely dynanically encloses
Ehe currently executlng instance; fn the notatl-on of Chapter 4'
DYN

tthead(current)tr.
indlcates the activat.ion record for

lhereglstersMAIN'AP,NEWAPandDYNallreferËoobject's
allocated on the heap, such objects being called "heap objects'r' Three

kinds of heap object can usefully be dlstinguished:


(1) dynamic varlables'
(2) procedure and functlon acElvatlon records, and

(3) coroutine' Senerator' generator functlon and main progran


acÈlvatlon records.
Each of Èhese kl-nds of heap object has a dlfferent internal
structure, or layouË, as tllustraËed 1n Figure 6.2. In all three cases'
the flrst locatton (the rT.c word") has a subsEructure deflned by the
following extract from the lnterpreter:
type RCword = -Packeg record
lock: (locked,unlocked) ;
count, length, descrptr, descrnum: address
e4;
The meanl-ngs of the varlous fields in this record will become clear
later in this chapter. For dynamlc variables (Figure 6'2(a)), Ehe
remalnder of Ehe heap objeet after the RC v¡ord l-s taken up by the space
required to store the value of the varlable' The ffve locatlons

L76
lnnediately followlng the RC ¡¿ord 1n both kinds of actlvation record
(Flgures 6.2(b) and 6.2(c)) hold Lhe same informatlon:
ttFVt', the functlon value field' holdfng the current value of the
pseudovariable If. this actlvaÈlon record 1s that of a functlon or
generator functlon instance, otherwlse it ls noE used,
ttSLtt, the statíc llnk, which lndicaÈes the activaElon record of the
approprlate instance of the block immediately outer to this one in
the program text'
trCALLERtr, finplementlng the caller l|nk 1n the sequence control
descriptions
'
rrLSPrt, pointing to the Èop of the local sËack wlthin this
activatlon record, ancl

ttCPt', Èhe continuation polnt, which indica¡es the lnstruction


wtthln Èhe C-code at which this instance wfll commence execution
when it next gains control.

RC word RC v¡ord RC word


FV FV
SL SL
CALLER CALLER
LSP LSP
CP CP

the parameter }IASTER


dynamlc Bectlon AIV
varlab 1e Á,CTIVE
itself local data
TOP

local stack parameÈer


sectlon
----+---- local data

local stack
+
(a) (b) (c)
Fleure 6.2 The Layouts of the Varl-ous Kinds of Heap Object

The LSp and CP fields of an activation record are noE kept uP to


date while that instance is executlng; instead, lt is the sP and Pc
regisEers whlch hold the approprlate values for the currently executing
rrtrr involves
Ínstance. A transfer of control to some target instance
flrstl-y storing the value of the SP reglster ln Èhe LSP field of the
currently exc-cuting instance (which nor¿ correctly indfcates Ehe Ëop of
its 1ocal stack), and then set.ting the SP reglster to the value stored

L77
lrttr' a sluilar sequence of
1n the LsP fleld of the targeË l-nst.ance
actlons fs followed with resPect to the PC regLster and the CP flelds of
the currently executlng lnstance and the instance "trr.
The resÈ of a heap object of the second kind (that ls, a procedure
or functlon actlvatlon record) consists of a sectlon for Parameter
values, followed by a section whlch holds Èhe values of l'ocal variables
and certain oËher quantitles (for example, the upPer bounds of for
loops), and concludes wl-th the local sËack for thls activation record'
Thls sequence of sections also occurs aË the end of heap objects which
are the actlvaÈion records of coroutines, generators ' generator
functlons or maln Programs, but in these cases an additlonal four fields
lntervene:
. TTMASTER", represenÈing the master variable 1n the sequence control
descriPtions '

. rtAIVrr, whlch contains Èhe address of Lhe location, 1n some other


heap object, holding the lnstance variable correspondíng to this
fnstance (instance varlables are f-mplemented by references to Lhe
approprlateactivatlonrecord);Èhisfleldi-susedtosetEhe
approprLate lnsEance varlable to "no-instancett when Ehe instance
terminates t

IIACTIVE'',whlch indlcates the actlvaElon record of the active


member of the group v¡hlch has this lnstance as its boss ' if
this
I'NILPTR'| (the
lnstance ls caterval, and has the value
ttno instancett) if this lnstance is
representat.ion of boÈh "n11" and
elementarY, and

record for the lnstance on


rrTOPtt, which polnts to the activation
top of Èhe stack of procedure and functlon lnstances associated
wlth this lnstance, and. hence lmplements the function "top"
dlscussed 1n ChaPter 4.

It should be clear from Ehe descrlptlon of registers and heap


object layouts that the manner in whlch the sequence conLrol operatlons
of ACL are lmplemented in the lnterpreter is related to their
descrlpElon, ustng the sequence control model, in chapter 4' In fact,
the corresponderrce beÈween the two 1s very close lndeed, Èo the exterrE
ÈhaË the interpreter contains t\,/o f unctlons "LIVEtt and 'tSUSPrr whose

178
definitlons are virtually transllËeratlons of those developed for the
sequence conËrol primitlves of the same names' and the implemerrt-aLion
of
lndivfdual sequence control operatlons \¡las derived in a more less
mechanLcal way from the appropriaÈe sequence conÈrol descrl-ptlons'
The

ease \^riËh which Èhls could be done noÈ only expedited this step ln the
process of frnplemenÈ1ng ACL, but also meant Èhat the implementation is
more ltkely to be conslstent wíÈh the language defl-nltfon' one polnt
regarding the translatlon of sequence control descripElons for use fn
the ÍmplementaÈfon rvhich requires clarificaÈfon 1s that the prfunÍtive
,,encl,, in these descriptions ls lmplemented by lncludlng ln the
approprlate c-code ínstructlon generated by Èhe compiler, the difference
between the (textual) level of Èhe subprogram in whlch the operatlon
occurs and that of the nearest texEually enclosing coroutlne, generator'
generator function or main program defÍnitton; the interpreter then
ttencl(current) " by
finds the actívation record intended by, sây,
following the speclfled number of static links, beglnnlng at the
currently executlng acÈlvation record'
Innediately prlor to any transfer of control rtlth ìùhl-ch parameter
transmlsslon may be associated, Èhe NEWAP register conLains a reference
Ëo the target lnstance, as Ls also the case in Pascal'H' (where such
transfers of control occur only as a re-sult of procedure and function
calls). Thls allowed the scheme used in Pascal'I1' for the transmission
of actual parameter values to also be used in the ACL processor: the
cornpller sirnply generates C-code insÈructions whlch sLore Èhe calculated
values in locations w1Èhin the activation record indicated by NEWAP' at
the offsets corresponding to the appropriate formal parameters' A mlnor
dlfflculty, slmllar to one encountered when wrltlng Pascal'H" occurs if
the evaluation of an actual Parameter expression lnvolves a functfon or
generator funcEion call: the value currently stored in the NEWAP
register, indicatlng the target. actlvation record ln the transfer of
control r¿fth whtch the parameter evaluation is assoclated, will be
destroyed as a result of the call. The solutlon ls to push Ëhe value of
the NEI,IAP reglster onÈo the local stack of the lnstance exectrting the
orlginal transfer of conËro1, before executlng the function or generator
funcÈ1on call, and to restore the NEWAP reglster from that stack on
reEurn. Thts latter resÈoraÈion is complicated by the fact thaÊ a
funcEion oL- generator function inst.ance returns its value by pushing 1E

L79
onto lts caller's local sËack, whlch ls the same stack as the one on
whlch NEI{Ap 1s saved; thus¡ the C-code Ínstruction restoring NEI{AP rnust
lnÈerchange Ëhe Ël¡o values on toP of the sÈack before using the (ner^r)
top one to set the value of the NEWAP regisÈer, leaving the value
returned by the functlon or generator function on top of the stack'
As stated 1n Chapter explicÍt constants
4, constant ldenÈlfiers and
are pernitËed as actual seen Parameters; however, unlike variables,
these constanEs normally have no run-tl-ne existance and therefore they
occupy no locations in the heap to whlch references may be passed as an
acËual parameter value. Rather than treatÍng actual seen parameters
whlch are constants as 'T.O valuett parameters (with Ëhe attendant
compllcaÈions when a single formal seen parameter may have either a
constanË or a varlable as an actual Parameter) or allocatlng storage for
all constants , both named and expllcit, at run-tfme, f t Ittas decided
instead to allocate locaEions 1n the ttlocal datarr part of Èhe calling
actlvatlon record for any constants used as actual seen Parameters' The
appropriate value is set ln each locaÈlon and then a reference Ëo this
Iocatlon ls passed as the actual parameter, as it would Lf the actual
PArameter srere a variable.
Another part of the third steP in the development of an ACL
.processor was the enforcement,
by the compfler, of Èhe requirement that
the l^I access rlght is necessary lf a name is to aPpear 1n certain
conÈexts; specifically, an RI'¡ accesslble variable 1s requtred in the
following sltuations:
. an actual parameter correspondíng to a formal modifiable (RlI

reference) parameter of a user-defined subprogram'


. an actual to certain of
parameËer corresponding Ehe paraneters of
some predefined procedures (recall Table 5'1)'

. the conÈrolling variable of a for loop, and

the variable on the left-hand slde of an assignment or create


statement.

Since the syntax diagram for "argument listrr includes the syrubol
ttexpressiontt as an alternative for an actual parameterr some comments
will no\¡r be made on how the klnd of access Ëhat a block has to an

180
expresslon ls computed from Èhe access that lt has Èo the components of
the expresslon. If an expression consists sirnply of a slngle ldentlfier,
then the kind of access applylng Èo the expression is the same as that
applylng to Èhe identifier; lf, hor¿ever, âû expresslon conËains any
r+rr operator or a redundant
operators or parentheses, even a prefixing
set of parenËheses, then RO access applies. As fat as variables are
concerned, a block has the same klnd of access to the compon'ents of a
structured varlable as lt has to the variable ldentifier' For example'
ttall]
if "a" is the ldenElfler of an RW accessible variable, then 'b" is
also RI^I accessible, but " (a) " and "a [1] .b+3" are RO accesslble'
Dereferenclng a pointer varfable, whether 1È is RI^I or RO accessible'
always leads to Rl^l access to Ehe dynamic variable and its componenÈs;
for exaurple, lf |tprr denotes an RO accessible pointer variable, then
t'p1.ctt is RI.l accessible.

The final aspecÈ of the Èhird implementation step Lo be dj-scussed


here is the manner in whlch the lnterpreter enforces procedure-l1ke
behavlour for generat.or funct.ion instances. When an instance calls a
generaÈor functlon, the "locktt fleld of the calling acÈlvaEion record's
RC r,lord 1s set to "locked'r (and the calllng lnsÈance is nor'r said to be
rtlocked"). Trhe lock field of a newly-allocated actlvatlon record 1s set
to ttunlocked", and a return or exlt staËement execuÈed on behalf of a
.generator function lnstancer or Lhe termlnatlon of such an lnstance'
causes the lock field of the lnstance about to be enEered (which will be
locked at thls point) Êo be set to 'runlocked", slgnifying that there is
no outsÈanding call to a generator function instance' IJPon an exit
staÈement being executed on behalf of a coroutine or generator' a resume
statement betng executed, any instance terminating lts lnltiallzatlon'
or a coroutlne or generaËor instance becomÍng Ëermlnated, Ëhe lock field
of the activatlon record about to gain control is examlned' If thls lock
field has the value "lockedtt, Èhen this instance has prevfously called a
generator functl-on instance which has not yet returned; ln thls case'
the generator function instance ls not behaving ln a procedure-ltke
mannerr ln thaÈ control is about to enLer its caller by a means oEher
Èhan a return from iË, and hence a run-tlme error is slgnalled'

Clea::ly, it is not necessary to check the lock fleld of an


actlvatlon record about to gain eontrol as a result of a procedure call
or a create statement, slnce that activaÈion record is freshly

181
allocaÈed; the above scheme also lncludes t!ùo less obvious
optlmizatlons:
. lt ls unnecessary Eo check the lock fleld of an activation record
belng entered as a result of a procedure or function return'
because of the r.tay 1n whl-ch a proeedure or functlon lnstance fs
subordlnaÈe to lts dynarnlcally enclosing coroutlne' generator,
generaÈor functfon or main Program instance, and
rtgrr cannoË
A call on A genera¡or or generaÈor functlon lnStance
rrgrr
cause a locked instance Ëo recommence execution: the lnstance
must have been called earller, and slnce Èhe generator function
f-nstance that it then called has not. yeE returned, it is clear thaÈ
Èhe caller varlable of rrgrr is st1ll in use (since 'rg'r has not had
the opportunlty Eo reEurn Èo its caller) and so the subsequenE call
on ttgt'will not be permitted by the deflnltion of the GC operatlon'

This scheme co ensure procedure-llke behavlour for generaÈor


funcÈ1on lnstances is relatively simple and does not add signLflcantly
to the run-time overheads of the various sequence conÈrol operatlons '

6.4 St.orase Manaqement

By the concluslon of the thfrd ínplementatlon step, a coupleÈe


processor for ACL had been obtalned, which correctly courpiled and
executed ACL prograros. Hor¡ever, this Processor performed no reclamatlon
of storage whatsoever: heap obJects were only ever allocated' never
deallocated, and hence they were not avallable for laLer reuse' The alm
of the fourth implemenÈaÈlon step was Èhe introcluctlon of a foru of
sËorage management which would a1low the reallocation of storage no
longer needed for the purpose for which it was allocated.
It is ¡,rorth statlng at thls polnE that the inplementaEion of ACL
descrlbed here 1s experimenËal, 1n that it was neant to demonstrate the
feaslbtllty of lrnplementíng the language, to provide a test-bed for
f uture l-nvestlgations of prograrnming rnethodologles as they relaÈe
Èo

eoroutines, and to afford a startÍng point frorn whlch to experiment rtrith


changes to the language and Lts implementatlon. In factr ln relaËlon to
Iast polnt, it 1s the same interPretive execuÈ1on whlch boEh facllltates
changes to the processor and is also largely responslble for its slow

182
speed of executlon, which 1s probably sufflciently slow to make tt
unsuitable for any "production'r use. sl-m1larly, the storage management
scheme adopted for this lmplemenEation ls a general one, and 1s easlly
adapted to changes 1n the language; however, lt ls perhaps also Èrue
that thls generallty ls at the expense of some gains in efflciency r^rhich
would have been possible if more of the present form of resEricElons in
the language rirere Èaken lnto account. Some couunents are made in Ehe next
chapter regarding avenues which rolght be explored in an effort to
lmprove the storage manageuent; some of these avenues lnvolve imposing
further restrictlons at the language leve1'

The description of ACL clearly lnplies that storage management in


any lmplementation of Ëhe language 1s completely inpllclt (automatic) '
which fs the reason Èhat l-t r¡as possible to bulld a complete processor
for it which contained no deallocation of storage. The language conEalns
no feature whose definltion lncludes a deflnite statement regarding
ttdlspose" Ín ACL is
storage deallocation; for example, the deffnition of
ttnlltt, whereas the
purely in terms of set.tlng the polnter varfable to
pascal ReporttT5J contalns the definltion: "dispose(p) ... can be used
to lndicate that storage occupled by the variable referenced by the
pointer p is no longer needed". In the case of ACL' it 1s left entlrely
up to the funplementation to declde when tt is that a heap object'
.whether a dynamtc variable or an actlvation record' 1s no longer needed'

speclflcally, a heap object can be deallocated (lncorporated into


the free storage l1st) when the quantities it contalns are no longer
accesslble and, ff it 1s an activation reco-r--d' the lnstance to which it
corresponds can no longer gain control. The varlety of complex
sltuatlons introduced by pointers and dynamic variables, and

partlcularly by the posslblllty of instance variables in dynamic


varlables, demands relatlvely sophÍsticated storage management; the
choice \{as flnally made bet¡¿een a reference count system and garbage
collectlon. The former !ùas chosen over the latter because of lts
relatlve slmplicity and since 1t. ls expecEed thaÈ procedure and funcÈ1on
acÈlvaÈion records may well form a large proportlon of Ehe heap objects
reguested from the storage mallager. In mosÈ cases, these heap objecÈs
may soon be returned to free storage (when the procedure or function
returns Ëo its caller), a facÈ r¿hlch is easlly discovered by reference
counting; \.rith a garbage collection scheme, on the other hand, frequent

r83
and expensive garbage collectlons may become necessary' Another
advantage of a refereo.ce count scheme 1s the way 1n which it spreads the
sËorage manageüent overhead over the entlre executÍon of a Program' as
opposed to the \ray that a garbage collector generally requires large
amounts of processor tlme every now and agaÍn, causlng sf-gnlfleant
dlfferences fn the execuÈ1on Èfmes of seemingly slmllar programs'

The essence of reference count storage management is the


malntenance of a counE on the number of references to every object' this
count belng l-ncremented and decremented as varÍous operaÈlons occur
durlng the execution of a prograE. tr{hen an objectts reference counE
reaches zeto, the object is no longer required and can be deallocated;
before this is done, however, the reference counts of any other objecÈs
to whLch this object contains a reference are decremenÈed (and, in a
recurslve manner, these objects may also become deallocaEed).
To enable thls secondary reference count decrenenting to be
performed prl-or Èo deallocation, 1t is necessary for the lnterpreter Èo
be passed Ínformation concerning Ehe offsets of pointer and instance
varlables (includlng value parameters) w1Ëhl-n each heap object; the
compller generates code containing this lnformatlon for each dynamic
variable (along with the call to ttne$rtt) and f or each subprogram
,acLfvatlon record
(after the code for the body of the subprogram)' Each
lnstruction ln this code contains Èhe offset of the l0catlon 1È
describes and an lndicatlon of the ktnd of location; the latter may
fndicate a poinËer, an instance varlabler or an "overlay" location'
Overlay locations arlse because varlant records may cause the locaÈíon
occupied by a polnter or lnstance variable to be shared with sone other
type of value; thus, a polnter may be overlald with (that ls, over-
wrlËten by) an lnteger, or a pointer may overlay an instanee variable'
glving rlse to an overlay locatlon ln boÈh cases. It is not safe to
include these locaLions ín the secondary reference counÈ decrementlng
slnce they may well contain values r¡hlch are not legal values for a
poÍnter or instance variable, whichever is expecËed'
orrerlay locaÈions are included in the descrlpÈ1on transmitted from
the compller to the interPreter, slnce the informatlon ln this
descrlptlon ls also used to lnitlalize pointers, instance variables and
overlay locaÈlons to rtNILPTR!|, the representatÍon of both "nil" and

184
ftno_instancett. This lnitLaLLzatLon ls an essentlal part of the reference
count storage management scheme.
The inclusion of overlay locatlons 1n the seeondary decrementing
process would be possible Èhrough the Lntroductfon of a tag field
checkl-ng scheme, such as Èhat described by Flscher and LeBlancl'4z1 , to
ensure thaÈ the tag field value 1s always consisËenE r.¡lth the varl-ant
belng used. Changlng the tag fleld value would then lnvolve the
inftlalizatlon of any pointer or insÈance varlable fields 1n the variant
whlch has Just become current; the secondary reference counÈ
decrementing t¿ould also become more tedlous, since |t would then be
necessary Èo tesC tag field values to deËermine the current structure of
a record variable with respect to pointer and lnstance variables (and
the necessary informatlon to compute this structure ¡¿ou1d need to be
passed to the interpreter). For Ehese reasons, and others' lt ¡rlas
declded noÈ to introduce tag fleld checking into this lmplementation of
Ä,CL; the sole consequence of not includlng overlay locatíons ln the
secondary decrementing process is that SoItre heap objects are not
deal-located when Ëhey otherr.¡ise rnlght be. The lack of tag fteld checking
ttnetí" fn ACL
1s also the reason ÈhaÈ, unlike lts Pascal counterpart,
does not take tag field values as parameters; l-n the absence of such
checkingr it ls not possible to guaranÈee thaE tag fteld values other
'than those specified in the call to ttner¡tt will not be used, such use
possibly causing locaElons out.side Èhe dynamlc variable to be accessed'

I^Ihen a heap object is created for a dynanic variable or an


actlvaEion record, anoËher heap objecE ls also allocated at the same
time to hold a description of Èhe first object in terms of the posltions
of lts polnter and instance varlable (but not overlay) flelds' This
t'D-llsttt),
separate object, known as the 'rdescrlption list'r (or, simply,
conÈalns one entry for each polnter or lnsÈance varlable fteld in the
heap object wiEh l¡hlch it ls assoclated; each of these enËries gtves the
offset of the ffeld and the kind of referenee (whether a polnter or
instance variable) thaÈ |t contains. It is true that Lhe D-list could be
incorporated into the heap object concernedr sâY at the end of Ehe
obJect, but thls ¡,ras not thought Eo be worth the compllcatlons caused to
the code generation Parts of the cornpiler. Fi-gure 6'3 depicts an example
of a heap obJect and its D-l|st; no¡ice that both are va1ld heap
objects, heade-d try an RC word. These RC words have an internal structure

185
whlch was descrlbed earller, and whlch ls depicted in Flgure 6.3 1n the
manner:
lock count length descrpt,r descrnum

The 'rdescrpÈr" fleld in the object's RC word points to the D-list' and
the rrdescrnum" fteld gives the number of enÈries in the D-list' The only
other ftelds tn the RC word which have not yet been explalned are
ttcounttt which holds the reference count for thls heap object¡ and
ttlength" whlch conÈalris the length of Èhis object. The values of Èhe
lock fields of the heap objeet and its D-l1st are not shown 1n Flgure
6.3; also omltted are Èhe reference count for the heap obJect, and the
values of ttdescrptr" and "descrnumt' for the D-lisË. None of these values
are relevanL Èo this dlscussion. The reference counÈ of a D-l1sÈ object
is always one, since the only reference to it is in Ëhe heap objecE with
rshích 1t 1s associated.

7
I
3 I 4
2 ?
4 I
5 I

Fieure 6.3 An Example of a Heap Object and its Descrlptlon List


The D-llst in Fl-gure 6.3 specifles that there is a pointer varlable
aË offset 2 (that l-s, the third locatlon) in the heap object on the left
(which ts of length 7), and that Ehere are instance varlables at offsets
4 and 5. The reason for the field glving the kfnd of locatlon' depicted
Ín Figure 6.3 as "Ptt for pointer and "Itt for instance varlable, is that
1f, durlng the process of secondary decrementlng, an instance varlable
l-s encountered, then the reference counts of the actlvation records for
any procedure or functlon lnstances associaÈed wtth the indicated
lnstance ate also decrement,ed. This is done because the instance
variable 1n Èhe object about Èo be dealloca¡ed represents, recalling the
fact that the prlnciple of opaqueness is enforced for instances, the
only means by r¿hich those instances could ever execute again' Notice'
also, that the D-list object can always be deallocated when lts
assoclated heap objecE is finally deallocated, slnce ít r¡111 then be of

186
no further use.

The malntenance of the reference counts wÍIl be outllned' When


nov¡

a heap object ls lnitially allocated, lts reference count (the 'rcounttt


fleld ln lts RC word) is set to one. Àt the same time, the length of the
heap obJecÈ ls stored ln the "length" fleld of its RC word; this value
ls used by the deallocation routine at the end of the object's lifetime'
ttneÍItt or a create
The creation of a heap object uslng the procedure
stetement w111 overwriËe the prevtous value of the polnter or lnstance
t'n1ltt or
varlable specified;1f thls previous value ls other than
rrno_lnstancerr, the reference count of the indlcated heap object 1s
decremented prlor to storlng the neqr value i-n the variable' lhis
decrementing actlon, whlch also occurs ln a number of other siEuations
(see belovr), represents a potentlal source of problerns 1n the present
implementatlon, 1n the absence of tag fleld checklng: it is possible
for, say, an integer to be treaÈed as a polnter in this sltuaËion, with
possibly disastrous consequences as the decrementl-ng fs aEtemPted' Thus,
care has to be exerclsed in Ehe use of variant records wfth the presenË
implementation.

Pointer assignments and continuatlon value ParameÈers whleh are


polnters both cause a process of reference count decrementlng and
if the variables rrplrr and ttpztt in the
,lncrementing. For example,
assignment rrpl:= p2" are boÈh of tyPe Polnterr then the followlng
sequence of actions takes Place:

. tf Èhe value of rrplrr before Èhe assignment ls noE ttniltt, the


reference count of the object lndlcaÈed by lt is decremented, and
. if the value of trp2rt fs not "n11", the reference count of the heap

object indicated by lt is incremented'


InltlalizaE.Íon value Parameters (including value Parameters Èo
procedures and functions) cause only Ëhe reference count lneremenÈing
part of the above sequence of actions. On the other hand, calllng the
predefined procedure "di-sposett results in only the reference count
decrementing part. The assignment of structured variables containing
pointer flelds also causes reference count decrementing and
lncrementl-ng. In these cases, it is necessary for the compller to
generaÈe a descriptlon of the variable in terms of Èhe offseEs of these

187
pol-nter flelds, much the same as that used ln the cons|ruclion of D-
llsts; Èo remain consfstent v¡ith actions taken elsewhere, referenee
coun¡ decrementlng and incrementlng is a¡tempted in the case of overlay
locatlons.

A.call on the predeflned procedure 'rdelete" causes Èhe decrementing


of the reference count for the activatlon record of the lndicated
Lnstance, unless the supplled instance varlable has the value
rrno_instance" before the call. Since control can no longer find its way
into Èhe subËree whose root is thts lnstance, the reference counts of
any procedure or functÍon lnstances assoclaËed wlth Ëhls lnstance are
also decremented.
The Eerml-natlon of any subprogram lnstance causes the reference
counÈ of its actlvation record Eo be decremented; notice Ëhat when a
coroutine, generator or generator function termlnates, there will be no
procedure or functlon instances assoclated with it'

A shortcoming of the reference count scheme descrlbed so fat ls


that lt ls possible for a heap object to be deallocated vrhlle there are
st111 references in other 'objects (actually, ln other actlvaLlon
records) Èo ftelds wlÈhin lt as the result of (RO or RI^I) reference
parameters or wlth sEatements; Èhus, 1t is possible for one of Ëhese
ftelds to be accessed after the object's deallocation, íf one of those
acËivation records started executlng agaln. This kind of reference 1s
not usually taken lnto account when lmplementing Pascal, although
Fischer and LeBlanc do describe a scheme ¡¡hlch ensures Èhat dynamlc
varlables ln an executing Pascal program are not deallocated while 1t is
st111 possible to access thelr contents via reference parameters or wlth
statements. For ACL, the possibility of this kind of reference musE be
checked for all heap objects, not just dynamic variables' A scheme whlch
lncludes these references 1n reference count management for ACL will be
descrtbed in the next chapter; it has not been lncluded in the present
implementation of Èhe language, largely because lt is l1kely Ëo add
signifÍcanEly to the reference counting overhead and it r¡as thought that
thls extra burden l-s not conmensurate with the number of occaslons on
whích iÈ would save premature deallocatlon of storage' A better approach
Ls probably to devise a set. of restrictlons whlch l¡ould lead to these
references belng safely ignored in a large number of cases; this matter

188
1s also returned to Ln the next chapÈer'

Reference counting has two maJor disadvantages which are discussed'


for example, by Prattt12ll; these are lts failure to reclaim circularly
llnked collectlons of heap objects (these collecË1ons will be referrecl
to as ."rings of garbage"), and tl're hlgh cost of malntainlng ref erence
counts. The firsË of these refers to a sltuatlon l-n vrhlch a eollectlon
of heap obJects is such that members of the collection contaín
references to other members of the collection, so Èhat each member of
the collecEÍon has a non-zero reference count', but there are no
references from outside the collection to any of its members; thus,
alchough the objects Ín the collecti-on are no longer needed, their
non-

zeto reference counts prevent thelr deallocatlon. Thls situatlon is not


expected to occtrr frequently, although lt dld occur, for example, ln
an

earller verslon of the Lhlrd solution Èo Hammlng's problern, presented in


AppendlxB(FigureB.s).onesolutionËotheringsofgarbageproblemls
to perform mark-scan garbage collectlon whenever a heap allocation
requesÈ cannot be satísfied; thus, the sE.orage occupled by Èhese rings
can be reclalmed when it Ls really needed. supplenentlng reference
countlng with garbage collection in this way hTas consldered, but
f/¡as
tta
evenÈually rejected because, âs Elson PuËs lt ln I4t1, this is
comblnation often resulting ln lnefflcient overkill'r'

As to the other disadvantage of reference counÈlng, the cosÈ of


malntafnlng refererrce counts in the present lmplementation of ACL does
not appear to be excesslve ln relatlon to Ehe other actions performed by
the lnterpreter. ThLs cost can be expectecl to vary widely, depending on
the program concerned; however, to give some idea of the total storage
management overhead, when the collection of programs ln
Appendix B was
ffrstly run through the ACL Processor resulting from the Èhlrd
lmplementatton step, and then through thaE resulting from this fourth
step, the average lncrease ln lnterpretation tlme Isas only about five
per cent.
The algorlthrns used for the management of the free storage list'
which perform the actual allocaLion and deal]-ocation of heap objects'
are the same as those used in pascal'Il'; they represent the sftuation of
an address ordered free list, with strlctly flrst-flt allocation and
coalesclng on deallocatlon, Lf thls is possible. No attemPt has been

189
made to nodify these algorlthms to better suit the sltuatlon 1n ACL,
although soue co¡¡¡ments are uade l-n the nexÈ chapEer on how thls urlght be
approached.

190
CHAPTER 7

CONCLUSIONS AND FURTHER RESEARCII

7. I The Progra¡n¡aing Methodology

The programming rnethodology descrlbed ln thls thesls has


suecessfully extended Ehe notlon of hierarchical structure of programs
Èo those involving the more general transfers of conÈrol inplted by
coroutlnes. This rneÈhodology has been applled to a number of problems'
of varying slzes, and appears Lo be vl-able; experience has shor'¡n that
its appllcatlon often leads Eo a betEer solutlon struct.ure than would
have resulted from a top-down programming methodology which does not
lnvolve the general transfers of control associated wlth coroutines.
Furthermore, 1Ës use allows. Ehe avoidance of Ehe anarchlc structures
usually assoclated wlth coroutlnes.
Thls meLhodology nay well be usefully extended to the construction
of programs involving parallel processes (tnpl1cltly sequenced
coroutines), Èhus enabling the developmenÈ of hlerarchically structured
parallel programs.

7.2 T\e Lansuaqe Desiqn

Probably the most signiflcant contrlbutlon of this thesls is the


approach to language design vhich lnvolves the separaËlon of Ehe design
of the semantics and the syntax, and which employs speciflc semantic
models çithln the former to make comparisons betr¿een language features.

In thls approach, the design of the semantlcs of the language is


dlvl_ded into thaÈ of three of its aspecEs: data structures, sequence
control and data control. It is the fact. that the semantics is designed
before the syn¡ax r.¡hich ls a major factor in enabllng thls subdlvision
to be made; to design the syntax of any one aspect before the semantics
of the others 1s flxed encourages Èhe maklng of premature decisions (or

191
trsemantlcs
assumptl-ons) about the semantLcs of those other aspects' The
before synÈax'r dl-sctplLne also helps to avold arbitrary or uncortsclous
design decislons.

Ttredivlsion of Lhe design of the semantlcs of A.cL into the three


aspects caused a very signlflcant decrease 1n the complexlty of the
overall deslgn task; for example, lt allowed the relatlvely thorough
comparlson of various extstlng languages and proposals. Ttre Ëhree
aspects chosen were useful ones; in partlcular, they are largely
orthogonal: a deslgn decislon made ¡sithin one asPect was usually found
to be tndependent of design decisions made for the other two asPects'
The key to the language design method described and used in this
thesis is the employmenE of specific, hl-gh-level semanÈlc models' It was
through the use of these models that it was possible to make detailed
comparlsons between exisElng systens, and between alternatlves being
considered for inclusion tn ACL. The operatlonal nature of the sequence
conËro1 and data control models meant not only thaÈ descriptions in
terms of these models were particularly lucid, hlghlighting simllaritles
and differences between the features belng descrlbed, but also that
these same descripElons f¡rere easlly translated for use 1n the
lmplementatlon of ACL.
-TheexperienceofdesignlngAcLlnthl-sIn'ayhasclearly
demonsËrated the usefulness of semanLlc models in language desígn'
orlginally, it hras intended that some more general model, such as
axfomaÈic semantlcs, be used to descrlbe (the whole of) each of a number
of exisEÍng systems wf th coroutlnes, buL lt fìIas f ound that these
descrlptlons \{ere too complex to be able to elucldate the similaritíes
and differences between the systems being descrlbed' Speclfic models'
such as those used in thls thesis, seem to be more aPproprlate Èo the
needs of language deslgn, because of the way in whlch Lhey facllltate
the comparisons which are part of the deslgn Process'
A difficulty encountered in uslng this approach to language design
is one which has been found by others who have atEempÈed preclse
descrfptions of existlng programmi.ng languages (see, for example, the
comments of i,IatEtl54l). This difflculty arises because of the
nature of
past descriptlons of programming languages: the.y are usualJ-y lnformal'
often poorly structured, and (in the case of those studied in the course

L92
of the work descrlbed in thls thesis) always lncompleËe. In order to
produce the descrlptlons of ChapÈer 4r lt $Ias sometlmes necessary Èo
resort to experlmentaÈion wlÈh, or examlnation of, a partlcular
lmplementatlon of the language concerned, where such an lmplementation
was available; for example, experluentation wlth Pascal lrnplernentaEions
was necessary to complete the descrlption of thaE language's data
control features. In fact, discoverlng the semantics of the data control
features of a language hras generally more difficult. than finding out Èhe
semantícs of the other Ewo aspects; data control features are often only
ment,loned in passing in language descript.ions, or thelr descripEfon is
scattered wldely through the documentatfon available on Èhe language'
Even formal descriptions of programming languages, such as the axiomaËic
descrlptfon of Pascalt69l, have very llttle to say abouË data control
matÈers.

In splte of thls dífficulty, the approach to language design


described in thfs thesis appears to be useful as a general technique'
because it is rnethodlcal and because lt offers a means of making
Èhorough and unbiased comparisons of language features whtch highlight
facets of lnterest; thus its uËillzatlon would rePresenÈ a sígniflcant
lmprovemenÈ over the ad hoc meËhods of the past'

. It would be particularly interesÈing to aPply this Èechnique to the


problen of designlng a parallel process faclllty for an existlng
programming language; lt is l1kely that the models used in thts thesis
can be easily extended for use in thaE deslgn process'

The design goals set out ln Chapter 3 are met by the program-ing
language ACL. The coroutíne mechanism of the language follows closely
the notlon of groups presenÈed in ChapÈer 2, particularly htlth regard to
the manner in whlch such groups become suspended. This, along with the
language's powerful data control features, means that it provides good
support for the progranmlng methodology described in Èhat chapter'

Some care was taken in Ehe deslgn of ACL to ensure a close


correspondence between static and dynamlc program structures ' As shown
by the example programs in Appendlx B, thts objecttve has largely been
achteved, although iE would no doubt be fruitful to examíne the language
for further opportunltles Èo make this correspondence st111 closer' One
example is Ëhe presence of pointers and dynamlc varÍables in ACL, ln the

r93
same form as they are found ln Pascal; it nighÈ prove worthwhile to
replace these by a hlgh-level data structuring facillty whlch permlts
the construetlon of llsts and t.rees (such as the feaEures suggested by
I{oare[68] or JohnsonITTJ), ln terms of the extent to whlch thls mlght
conÈribute to a reduct.lon ln the gap between static and dynamlc program
structure.
ACLallows a wide range of Program structures Ëo be described' The
coroutine facl1lty lncreases slgniflcanÈly the number of sequence
conüroI structures rqhich can be descrlbed, and the data control features
lnclucled ln the language mean Èhat a large number of data control
s tructures can be expressed. The expresslve
poI\ter of ACL's daÈa
structuring facilltíes 1s roughly the same as that of the correspondlng
feaËures ln Pascal, which is high. In splte of the wlde range of
strucEures expresslble ln the language, the nurober of language features
present 1n ACL, but not ln Pascal, ls small'
Efflcient enforcement of all of the restrlctlons of ACL is possible
and has been lncluded in the lmplemenEatlon descrlbed in chapter 6'
Conclusions regarding Èhe implementatlon and possibilities fox lts
improvemenE, glven the Same language definition, are presented in
the
nexÈ section of this chapter. It rnight, however, be worEh consldering
,further language resËrictlons to allov¡ lmprovements ln
Storage

¡nanagement. efficlency; for example, Tf references Ëo


the local
quanttties of procedure and functlon lnstances (includlng value
parameters) \{ere not allo¡.¡ed to be passed vla (RO or RW) reference
pArameters to coroutines, generators or generator functions, l-t would
then be possíble to use the deletlon strategy for all procedure and
functlon activatlon records. However, the checking for this resLriction
must be performed at run-tlme and |s likely Èo be relatively expensive'
which may mean that rhe time saved in storage management may be
outwelghe.cl by that consumed 1n checking the resEriction'

ThepresentformofAcLreflectsadesiretogaínsomelnltlal
experience with the ideas behind iE, by using a language with few
resÈrictions. It is likely that thls experíence will point to areas in
whlch the language can be further restricted wíthouÈ lnterfering unduly
with the way 1t is used to solve problems. This, for example, 1s the
reason for not enforclng Èhe princtple of oPaqueness in the case of all-

194
l-tems in an ACL Program.

7.3 The Imolementatl-on

The concluslons resulËlng from the Pascal'Il' experlment, whlch were


presented 1n chapter 6, also hold for the lrnplementaElon of ÀcL using a
coropller/lntepreter scheme based on Pascal'P'3 tt lùas A reasonably
stralghtforward task to derive Ëhe ÀCL Processor from Pascal'H', and the
ef f l-clency of Ehe resultlng lmplementatlon \¡Ias good, eerËainly
acceptable for the experimenÈal lmplementaÈlon that lt is' Given Lhe
fact that the interpreter part of the ACL processor interprets a
relatively low-leve1 intermediate code, the execution speed of the
system |s excellent r, and seems to represent only a small increase over
that for comparable Pascal Prograns uslng Pascal'I{" As ís also true of
the comparlson betr¿een Pascal'H' and Pascal'P' (see [104]), the amount
of storage occupied by activaÈion records tends to be signlficantly
larger ln the ACL processor than wlth Pascal'P', because of Ehe
addltlonal fields required withl-n these activation records and because
of the use of a local stack scheme, whlch means that the maxímum space
needed by an activation record for temporaries ls allocaEed to iÈ
throughout lts llfetlne.

The r,üastage caused by the latter scheme could be elininated by,


qrhich
sÉty, uslng the method suggested by Bobror¡ and ÌIegbrel-t[ 19] , 1n
locations for temporarles are allocated as needed; however, thelr scheme
leads to the copying of the locations representíng an activatÍ'on
record's sÈack to some oEher part of store if |t ís unable to grorl¡ Past
1Ès present sLze where lt ls, because lE is blocked by some other
obJect. T'wo posslble dlsadvantages of Ehe Bobrow and wegbrelt scheme for
the inplementaEion of ACL are Èhat the amount of copying occurrlng may
become excesslve, and thaË Ehe "holestt resulgfng from this copylng
(which can only be reused through some auxillary nethod) nay lead Eo an
lnefflcient use of storage. To be able to Properly assess whether the
adoptlon of Bobrow and Wegbrelt's scheme r^rould be advantageous, it would
be necessary to perform some measurements on the storage usage behaviour
of some "typlcal" ACL Programs, much as has been done for SN0B0L4 by
Rfpley et al. ll29l.

19s
such measuremenLs would also provide lnformatlon r¿hich nlghr lead
to lmprovemenEs 1n the algorithms used to manage the free storage
list
1n the ACL processor, which are currently ldentlcal üo those ln
Pascal'H'. Hanson[60] has suggested a variant of the boundary-tag
algorithm[85], which ls said to be suited to the Ûânagement of coroutine
actlvation records; Ehe slmpliflcations that llanson has made to the
orlglnal boundary-tag algorithm are based on tqro assumptlons' Ihese
assumptlons are t.hat the d1sÈributton of actlvation record sizes l-s
semi-fndependenL of the parÈlcular execuÈlon of a given Program'
and

that the staÈlc and dynamic distrlbuÈlons of actlvatfon record sizes are
much the same. IÈ ís not clear that these assumPtions would be true
for
a naJoríty of ACL programs, and so this particular algorithro \^7as
rejected for use in the ACL processor. The lnvestigatlon of the validity
of these assumpEions, and hence of ühe suitability of Hanson's
algorithm, provides further motivatlon for carrylng ouË storage usage
measurenents for ACL Programs'

TherearetlüolmprovemenËswhichcouldbemadetothe
implementatlon of ACL described in chapter 6; the first of Ehese is the
fnÈroduction of tag fleld checking, which Ís possible by adaptlng Èhe
approach described by Fischer and LeBlanc 142). Tlhe second improvement ls
the extenslon of the reference countíng scheme to Ínclude consideration
'of references due to reference paramet.ers and with statements ' and a
method to achieve this (which 1s based partly on a suggestlon of
LeBlanctgol), will now be outlined. In thls method, a heap object's
reference count. is incremented on each occasLon that an actual reference
parameter (whether seen or uodifiable) which refers to some field within
the obJect 1s transmltted; sfmilarily, this reference count ls
increment.ed if a varfable 1n a with llst 1s found to have an address
located r¿lthin the heap object. At soue later tiue, when Ehe reference
to the partlcular fteld of the heap object is Êo longer currenL, the
reference counL must be decremented agaln. The polnt at which thls
should be done depends on the language feature involved:
. for with statements, it fs at the end of the statement concerned,

for l-nl-tiallzation reference parameters ' the appropriate tlme ls


the t.erminaÈÍon of the lnstance concerned, and

for conLlnuatlon reference parameÈers the decremehting should be


'

L96
performedonthenexÈtransferofcontrolwhlchlnvolvesthe
replacement of the parameter values vrith nehr ones'

In all three cases,1t.ls necessary to SËore the startlng addresses


oftherelevantheapobjectsacthetlmeofreferencecount
lncrementfng, for later use in decrementlng those same reference counts'
In the case of wl-th statements, this Ínformation can easily be stored in
the local data sectlon of the actfvatlon record of the lnstance
executlng the statement. For reference parameters' both inltializaËion
and contlnuatlon, allocate a sequence of locaÈlons (catl 1t the
t'R-lisEtt) also withln the appropriate activation
"reference list" or
record. Each entry in an R-list corresponds to one of thaÈ lnsEancens
reference parameters and contalns two fields:
. the ttoffseËtt fleld, glving the posÍtlon of the reference parameter
withl-n the activatl-on record, and
. the ,,address" field, lndlcating Èhe heap object contalning the

Iocatlon referred tO by the parameter's current value.


Inltlally,whenÈheoffsetfietdsareSetuP,alloftheaddress
fields are set to "NILPTRI'. on transmlssion of a reference PArameter
value, the old value of the address field of this parameter's entry Ín
the R-I1st ls examlned and if lt contalns a value other than "NILPTR"'
then Ëhe reference count of Ëhe lndicated heap object is decremented
(thls takes care of continuation parameters); ln any case, the address
of the heap obJect contalning the location fndicaÈed by the actual
parameÈer value is stored 1n the address field of the R-list entry
and

the reference count of the object is incremenEed. rt is expected that


Ëhls scheme for lneluding references due to reference parameters and
with statements would add signlficantly to the expense of storage
uanagement ln the ACL Processor, and hence ft rnight prove
frulËful Èo
investigaËe language restrictlons which r¿ould reduce this cost'

Flnatly, it would be lnÈeresting to attemPt the extenslon of tr{ang


and Dahl,s modelt152l to cover ACL. It has been extended by
saJanieuritl30l to prove propertles of a language proposal ínvolving
groups of coroutines (see Ehe description of this proposal ln Chapter
4); among Lhese properties ls "balancett, meaning that only one coroutlne
lnstance from a grouP is active ât any one time, all of the oEhers being

L97
suspended. sl-rnllarly, soffa and Llndstrorn[138] have rnodlfled the model
of tr{ang and Dahl to cover some extenslons Èo tbe features descrlbed ln
t152l i they then use the modlfied model to prove that
cerEaln r'law and
orderrr conditlons are observed by the extensLons, and to provlde a proof
of correctness for a sÈrategy for Ehe deletlon of activation records' It
ls this last applicatlon of l^Iang and Dahl's model whlch nlght be
partlcularly useful wlth regard to ACL' not so much to Plove the
correctness of the straEegy eurrently used to decide when heap obJects
are no longer needed, but rather to gulde its optlmizatlon and the
development of language restrlctlons whlch would allow simpler and
more

efftcient straregles.
In summary, thls thesls has provlded a framer^rork for prograrnming
wlth corouËlnes, through the descriptlon of both a programmlng
methodology which produces hterarchically structured corouËine programs
and a programmlng language which supports thls methodology and whích
has

been lmplemented. IE has also described, and demonstrated the utllity


of, an approach Èo language design whích allows a more methodical and
thorough approach to be Ëaken ln thls area'

198
APPENDIX A

SYNTAX DIAGRAUS FOR ACL

ldentifier letÈer

letËer

dlgtt

unslgned integer
dfglt

unslgned nr¡nber

unsigned lnleger dlgtt unelgned

unelgned constant
consÈanÈ ldentlfler

unslgned number

characÈer

constant
constanC ldenÈlfler

unslgned nunber

character

sluple type
type ldentlfler

ldentlfler

conB Èant constanÈ

r99
tyPe
sl.rnple

type ldenÈlfier

INSTANCE deflnlÈlon ldentifler

ÂRRÀY slmple type Èype

FILE

SET elnple Èype

RECORD fleld llet END

ffeld llsÈ

ldenÈff ler tyPe

CASE ldenÈlfier type ldentifler

cons tan t. fteld list

varlable
varlable ldentff

fle1d identlfier expression

fleld ldentlf

200
a ta Èement
unsiB¡ìed lnÈeger

non-insEance varlable

functlon l-dentlfler expresslon

BeneraÈor functlon fdentlffer

BEGIN atateDenÈ END

sloo THEN sÈatement ELSE 6taEenenÈ

sÈaÈement END
expresslon constanÈ

WHILE expressfon sÈaÈemenÈ

REPIAT s ÈaÈemenÈ UNTIL express lon

roR varlable ldenÈlfler expressfon

exPùesgion sÈaÈenent

varlable 6ta Èemefit

GOTO lnt

sequence control eraÈfon

201
arßumenÈ 1lst

lnsÈance varl-able

procedure or functíon tdentlfLer

exPre6aLon

facÈor
constanE

non-1nsÈance varlable

functlon ldentifler
lls t
fnstance vatlab

expression

NOT facEor

expresslon expresslon

terû
factor

* DIV MOD AND

factor

slmple expre8slon

tern

te¡r

202
expresslon
sfnple expresslon

Blnple expresslon

aequence control operatlon


LnsÈance varLable CREATE dêfinltlor¡ ldentlffer

argument lfst
RXSIJUE

Lnstance varlable argunenE llst


CÀLL

p!ocedure ldenÈlfler argument lL6t

RETURN

ParaEeter foro I

SEEN

( T,ÍODIF ameter

VALUE

psrameler fontr 2

coNl paraneÈer forn I

ParaneÈer forn 3

auetel forro I parameter forn 2


INIT

203
påraneter ÈyPe

Èype fdenÈffier

PROCEDURE
parameter form I

I'UNCTION paraneter form I type l-dentffler

COROUTINE
paraneÈer forn 2

GENERATOR

GENT'IJNC pêrameler fotm 2 type ldentlfler

pararDeter lLst

SEEN

PRIVATE
IIÍODIF ldenÈlfier
HERITABLE
VALUE

paraneter tyPe

lnherf tlng declaratlon

MODIF VAR ldentffier

CONST

TYPE

VAR

PROCEDUR,E

1d enÈ1f ler
FUNCTION

COROUTINE

GENER.ATOR

GENT'IJNC

204
block I

BEGIN s taÈement END

declara tlon

defl-nlng declaration
PRIVATE

HERITABLE

LABEL
unslgned lnteger

CONST ldentlfier constanÈ

TYPE ldentffler Èype

ldentlfler Èype
VAR

ldenclfier paraneter llsÈ block I


PROCEDURE

ldenÈif ler paraneter lfst type ldenÈlfier

COROUTINE
ident if1er INIT parameter list

CONT pararneÈer llst

l-denÈ1f ler INIT paraneter 11st

CONT parameEer llsl: e ldenclfler

block 2

205
block 2

II¡ITBEGIN státemenÈ lNITEND

declaraElon

BEGIN s EaÈement END

forward declaratlon PRIVAîE


FORWARD

HERITASLE

TYPE ldenclfier

PROCEDURE ldencifler paraneÈer forrn I

COROUTINE
identifier paraneter form 3

ION fdentifler p arameÈer form I type fdentlfier

fdenti fler paraneter form 3 idenÈlfier

declaratlon
deflnlng declaraÈlon

forward declaraEion

lnherltlng declaratfon

program

PROGRA}Í lden clfier identlfler block I

206
APPENDIX B

SOME ACL PROGRAMS

8.1 The leerams Problen

A solutlon to this problem was outlined in Chapter 2; a compleÈe


AcLprogranbasedonthatoutlfnelspresentedinFigureB.l.
Correspondences between the various 'tnodes" 1n the discusslon
of Chapter
in the
2 anð. subprogram definltlon and lnstance variable identtflers
rrlrr Ín Chapter 2
program, are summarlzed Ín Table 8.1; notice that node
variable
corresponds to Ehe maÍn program and hence there fs no insÈance
in ÈhaL câsê.
ttlBtt ls firstly
when the program conmences executlon, the instance
fíle ls
created; 1Ès lniÈ1allzaÈion section checks to see tf the lnput
(the rnain program
empty: 1f it 1s, LB sLgnals thls-,fact to iÈs creator
t'errortt to 'rtruett. If the lnpuc flle
by settlng the variable
.insEance) thls
ls not empËy, the main program then creates the lnstance'rET";
be used
l-llusÈraEes the way ln r¿hlch expllctt creation of instances can
only that
to advanEage, to l1nÍt the nuuber of members of a grouP to
number required aÈ a particular tlme. The inl-tiallzation
actions of the
trEl{'tr and'rPTr"
lnstance ET consíst slmply of creating Ehe instances
(whlch is deflned
forrulng the group based on the "sIord" data structure
aË the head of rrExtracÈTelegramst' in Flgure B'1) ' The IrLL:Ll.aLj-zation
t'EC'r, this group representlng the
sectfon of EI^I creaEes the instance
level of rhe characEer data sÈructure (the variable "chtt); the
lnstance

EC calls the instance LB to fill the buffer for the flrst tlme and then
ttcountt" keeplng
lnlttalizes rtchrr and a local lnteger variable, called
t.rack of Èhe element of the buffer last extracted' The inítialization
number of
actions of the instance pT consist of setting a counter on Ehe
telegrams processed to lts lnltial value of zexo' and creaÈing an
the current
instance of the generat.or funcEion whlch 1s used to compare
word viÈh the word "STOP", thls insEance being stored in the
lnstance

207
proqran Te legraos(1nPut' output) ¡

herltable const buffsize - I00;


tãiTurr.t I ar-Igl ll"buffetzel of char;
error : boolean;
privaÈe generator LoadBuffer¡
uodff var error, buffer;
seen congt buffslze;
prlvaÈe feE t' J: lnÈeger;
lnitbeÊln ( LoadBuffer ) thls fêct to the
{ tf lnput flte ls "tpty, '"" "error" Èo êlgnaI
creaÈôr of Èhls tnsEânce )
ff eof(lnPut) Ehen error:=true else 1:= I
lnlÈend;
begln
{ cont.Lnuè satlsfylng requesta to ftll che buffer untll the end of
Èhe fnPut flle ls encountered )
vhlle not eof(lnPut) ,do
begln
not eoln(lnput) -d9
-1b49
begin
r.a¿(¡.fftrtll); i:= 1 + l;
lf 1>buffstze then begln reÈurn; f:= I en4
e¡4;
readln( fnPu t)
end;
{ end of lnpur file reached: lf some lnPut has been read on thls call'
no error has occurred - blank f111 "buffer" )
1f f>I then
begln
-E:,=f to buffslze do bufferfjl z= ' 'i
return
end;
(endoflnputfllewasalreadyreachedwhenrequestedÈof111',buffer''-error)
errorS- Erue; exlE
end(LoadBuffer);
heri.table vaq LB : !E-Sg!-Sg of LoadBuffer;
Drivåte qenerator ExtractTelegEang¡
seen var buffer, LBI consÈ buffslze;
herllable consÈ maxword = 50;
var word : record
Iength : l..naxword;
chars: g¡¡ga Il"maxword] of char
end;
herlÈable funcÈlon ZZ?'Zfot¡ò ¡ boolean;
- SSCq jC!Sl&! ZZZZfotndi var word¡
ii-rtvat. var found : boolean; 1 3 lnteger;
beÊ ln
l'tth woid do
lf length=4
then
begln
found:= true;1:= l;
shlle found and (t < 4l iS.
_-!.e8,4
f ound= chars[1] -'Z'i Lz= 1 + I end;
ZZZZfound¿= fot¡ò
end
else
ZZZZnound':= false
endlZZZZfou¡dj i
Drivâte Penerator Extractllord;
seet var buffer, LB¡ const naxword' buffsize;
gg¡!!f var word;
herllable var ch : char;
Drfvate qenerator Extractcharacter;
seen var buffer, LB; consE buffslze;

Flgure 8.1 A Solutlon to the Telegrams Problem

208
nodlf var ch;
read fron "buffer"
ÞrivåÈe fgE counr 3 lnÈeger; { lndex of lasÈ character
)

lnitbeÊ,ln { ExEractcharacÈer }
call LB;
count:'l; ch:- bufferlcount] { assume buffslze Is aÈ leaat one }
lnltend;
begln
¡rhile true do
becln
count:- counÈ + l;
Lf count>buffsize Èþeq
-Þt"L SeU LB; cãäE:= t end¡
ch:- bufferlcountl ; relurn
end
end f-Ext.racÈCharacter ) ;
orlvaÈe var EC : instánce of ExÈractcharacter;
1 : fnteger;
const blank - "¡
loltbeqln ( Extractl'lord )
-EC:- create ExtracÈCheracÈer
fnf tend;
begln
whlle true do
beg,in
---I- O; wirlle ch=blank do call EC;
rrhlle (1<naxçord) and (chlblank) do .
-Þrgla {:= I + l; rcrd'charstll ¡- ch; call EC end;
word.length:= l; reÈurn
end
9¡!( ExtractWord ) ¡
herlÈåble vsr EW3 lnstance of ExtracÈ!'lord;
Drlvate q.enerator ProcessTelegran;
prlvate const llnelength = 120;
sordcounÈ' n' l: lnteger;
vtr t.l."otntr
anYoversLze: boolean;
seen functlon ZZZZfot¡d; var ElJ, wotd;
herltable Êenfune SToPfound : boolean;
grr!-Sgg!¡¡q STOPf ound; var word;. -
õtf""r" t.t sÈoPword : arrav ft"4l of char;
found: boolean; f: lnteger;
(
lnlrbegln STOPfound )
stÇT"tatf l:= 'S'; stopÍtord[2] t= '-"1'.i
stopword[3] z' 'O'i sÈoPe'ord[4]:= 'P'
lnltend;
besln
uhlle Erue do
begln
r¡lth nord do
lf length-4
then
begln
found:= true; l:= l;
r¡hlle found and (t 3 4) do
begln
f rund¡ = chars If I =stoPword [1] ;
1:- I + I
end;
STOPfound:= found
end
else
STOPfound:- false;
return
end
end(STOPfound)i
prfvate var SF: lnstance of STOPfound;

lnftbeqfn ( ProcessTelegram )
-fãI""ountt- 0; SF:- create SToPfound
lnltend;

Fieure B.l (conËlnued)

209
begln
:{LLþ true do
begln
telecount:o telecount + l; wrlteln('0');
r¡rlteln('0 Èelegram no' ' ,telecount:2); 0; n:= 0;
nrfÈeln; falee; wordcounÈ:-
"nyo.,".ãl"tt=
nhLle not ZZZZfottd do
begln
-Jf--(o+"o.d. I eng Èh+ I ) >l lneleng Eh
then begln çrlEeln; n:= word'len8Èh end
else n:= n * r¡ord'lengÈh + l¡
wrtte( " ) ¡
for J:=l tà word'length do vrlte(v¡ord'charslJl );
wotd.length>I2 Èhen anyoverslze:= true;
-flf not SF then wordcounc:= wordcounE * l;
gelL Elr
end;
wrlteln; wrlteln('0 number of chargeable words:"wordcount:5);
;!! anyoversize then wrlÈeln('+' ,' 't36" (aÈ least one of"
' whlch ls overlengrh)');
reÈurn
end
end TTrocessTelegran ) ;

Þrivate var PT : lnsÈance of ProcessTeÌegran;


lnftbegfn ( ExtractTelegrans )
---ru=
nttutt ExEracEword¡ PT:= create ProcessTelegram
inlÈend;
begln
call E!'l;
whlle not ZZZZlou¡d do
Pr; -se!l Et,t end;
-_¡cÊ'ls 9ÂU
return
.r,7-(-Eîr.t"tTeregÌams ) ;
privaÈe var ET : LnsÈance of ExÈrecÈTelegrams;
begtn ( maln Progran )
errors= false; LB:- creaLe LoadBuffer;
1f error
then
-îirceln(' enpty lnPut flle')
else
begln
ET¡= create ExtractTelegrâms¡
call ET;
[ã.toi !\gq wrtÈeln(' abnornal terminaÈlon')
end
end ( naln Program ) '

F1 re 8.1 (continued)

Table B. I Names lrr Flgure B'1 Correspondlng to Nodes

ln the Díscusslon of ChaPtet 2


Deflnltlon Identlfier InsÈance Variable
Node ln ChaPter 2

I Telegrams
LoadBuffer LB
2
ET
3 ExtracÈTe legrams
EI.I
4 ExtracÈllords
ProcessTe legram PT
5
EC
6 ExtractCharacter

2L0
varlable trsF'r; the subprogram whlch compares the currefit word wl-th
"ZZZZtt ls a function, Ehe reason for thls difference
being that SF holds
Èhe word'rSTOPrr 1n a local varl-able, whereas the function uses a
procedural represenEaÈion of the word
uZZZZtt
' After all of these
lnftlallzatlons are complete, the structure of the program is as shown
rrTrr is used to
l-n the master tree deplcted ln Flgure 8.2, ln v¡hlch
denote the maln program lnstance; at this polnt, control resídes 1n the
main program fnstance. Apart from the instance sF, whlch plays a minor
role and !¡as omftted from the discusslon of chapter 2 fox this reason'
thls master Èree closely mimlcs Ehe program structure shown ln Figure
2.1, and which l-s also evident from Ehe strucEure of the program text in
Figure 8.1.
I

2 3

4 5

Fiqure 8.2 The structure of the Program in Flgure 8.1 after the
Inltiallzation of lts Instances
Following these fnitiallzations, the insÈance ET is cal1ed by the
maln program which then calls EI^I to extract the flrst word from Ehe
buffer. This latter instance builds up words by sklpplng over blanks and
then storing non-blank characters ln the "\ùord" data structure (up to a
maximum of fifty characters) untll another blank character 1s
encountered; at Èhis point, Ehe length of the word is also recorded
r¡ithin lts representaËion. hlhenever the lnstance EI'l requlres another
character, lt calls on the instance EC whose task fs accomplished in a
relatlvely sinple manner: iÈ extracÈs characlers from the buffer until
the end of the buffer is reached, at whtch polnt iÈ calls LB Ëo have the
buffer refllled. Ì.Ihile this refilllng ls going on, the subtree with root
ET ls suspended, and the caller llnk of LB lndlcates ET; the successful

2LL
refllltng of the buffer results ln LB returnlng control to ET and
executlon contlnues wlthl-n EC. If the lnput flle is already at lts end
when LB Ls called, an error has occurred and LB firstly sets the
rrexiÈrr tO retUfn Contfol to
Vafiable "errortt tO "tfuett and then uSeS An
t'error" to
the maln prograu; the maln program uses the value of
dlfferentlate a normal reËurn of conÈrol via ET from this abnormal
return vla LB. This situation amply d'emonstrates the advantage of
dlstlngulshing between the GR (t'reEurn") and MR ("exltrr) operatlons'
Having regafned control from EI^I, the ínstance ET Èhen alternaÈely
calls pT and Ei^I unttl the word "zzzz" is found; when thls word has been
encountered, an empty telegram has been detected and ET returns control
to its caller, the maln program. on each occasion that it Ís called' PT
processes a slngle telegram, uslng EI,I to extract words from Èhe buffer'
The words are printed on lines whose length does not exceed 120,
hrith a
ttZZZZt'
slngle space between words, and a word count ls kepË, the words
and "STOPt' belng except.ed from thls count; the variable "anyoversizerr is
used to record the detectton of any words of more than thtelve characÈers
ln a glven telegram. when the r¡ord "zzzz" ls encountered, a suitable set
of messages ls prlnted after Ëhe neat llsting of the Lelegram'

The operatlon of Ëhe generaÈor function instance SF and the


function rtlzz:afound" are relatively stralghEforward and will not be
explained.

8.2 The Odd l^lord Reversal Problen

This problen ls deffned by Dljkstrat35l as follows:

Ì,le consider a character set conslsting of letters ' a space


(sp) and a
polnt (pnt ) . I^Io rds cons l-s t of one or more ' but aE mos t EwenEy
leEters. An input text consists of one or more words, separated
zero or
from
each other by one or more sPaces and EermlnaÈed by more
spaces followed by a poinE. I^Ilth the character valued functlon RNC

(itead Next Characteri the fnput text should be read from and
includi.ng the flrsE letter of the firsE word up to and including Èhe
Ëermlnatfng point. An output texE has to be produced using the
prlmltive i¡¡i(") (i.e. Print Next Character) with a characÈer valued
parameter.Èhetextistobesubject'edtothefollowing
transformatlon:
(1) ín the outPut texE, successíve words have to be separated by a
sl-ngle space
(2)lntheoutputtext,thelastr¿ordhastobefollowedbya
single polnt

212
(3) \then we number the words 0, 1, 2, 3' in the order from
fefi to rlght (i.e. ln whlch they are scanned by repeated evaluatlon
of RNC), the words with an even ordlnal number have to be coPied'
whlle the letters of words with' an odd ordí'nal number have to be
printed in reverse order'
Forinstance(usingtl-lltorePresentaspace)theinputtext
t'
"this----1s--a-silly---prograllF--. has to be transformed into "this-
sl-a-y1lls-program. " .

Ttgure 8.3 cont.ains an ACL Program based on a solutlon ouÈlined by


Bartertl0l; thts outline does noÈ lnclude a descriptlon of the acEions
of the maln program to creaEe lnstances and to transfer conÈrol to the
tterrortt has
f irst instance to executlon. Also, the variable
co¡rrrnence
t\'IDSt' to signal that a word of
been 1nËroduced Eo allow Èhe lnstance
more Èhan threnty characters has been found' The program also includes
ttRNC" and the prlnitive "PNCrr
implementat.fons of the functlon ' both
described by Díjkstra; the latter ls an instance of a generator wlth
a

single contlnuaËion parameter (the character to be printed)'


The program of Figure 8.3 solves the problern in the following
manner: the scanner (ttsÇtt) uses the functLon RNC to obtain the next
rrxrr and ttren transf ers to the
character, sËores lt in Èhe variable
r,words',instance (t\.IDSrt ) ; the instance SC rePeaEs this sequence of
actions unttl the termlnatlng polnt ls encountered, aÈ whlch time 1t
,uses PNC to prlnt the point and then termfnates, causLng control to be
returned to lts creator (the rnaln Program instance) '
The instance l,lDS has a relatively complex fnternal structure and
it
performs onè of a number of tasks, dependÍ-ng on the character passed to
1t by sc (that ls, the character stored in "x") and whether or not any
letters have been encountered since the last complete word rlas found;
the latter plece of ínformaElon ls supplted by the value of the variable
rtk¡r. a ze:Lo Value means that no new word has been stArtedt whereas a
non-zero value lndicates that some letters of a new word have already
been stored ln the array
t'vlordtt. If the Character in ttxtt is a sPace Or
polnt, then control passes to the prlnter insÈance (t'PR") if there are
ttr'Iordtt (and ttktt is reset to zero
some letters of a nelâI word in the array
on Ëhe next entry t.o wDS), or control is returned to sc Ëo obLaín the
rrxrr
next lrord íf ,,\^rord,, is currently enpty. If , on the other hand,
contalns a letter, it 1s stored 1n'bord" if there ls sufficlent rooTtr
(if not, control ls returned to the main program l-nstance, havfng set

2L3
Pleglån oddHordl;
heritable const sPÊ' '; Pta-'."
varxichar;k!lnteger;
word : 9¡¡g¿ tt..20l of char;
herlÈable f unctlon RNC:char;
eeen functlon RNC;
DrÍvaÈe var c: char;
Úesfn read(c); n¡¡C:= c end ( of RNC );
DrlvaÈe generaÈor prlnlnextchâr cont (¿flygfg value c:char);
Drlvatevarl:lnteger;
6een conaE ap;
be¡ln
r¡hlle true do
beqln
vrtte(sp); { carralge concrol character }
for 1:=l to 120 do besln wr1Èe(c); ls.lLgrn end;
nriteln
end
gI{ ( of Prlntnextchar );
fonrard prlvate corouÈlne words;
herltable val PNC : lnstance of Prl'nÈnextchar;
WDS ! lnstance of vords;

Drlvate coroutlne gcannet;


g.¡!!f var x;
aeen conat Pnt; var I{DS'PNC; funcElon RNC;
beÂ1n
repeaÈ x:= RNCi reauue -t unrll x=pnti
call PNC(x)
end ( of scanner );
herltable vâr SC ! fnstance of scanner;
DrlvaÈe corouÈ1ne PrlnÈer;
seen var k, word, SC, PNC; consÈ sP;
DrlvaÈevarl!lnteger;
begin
reÞeat
l:- l;
Eepeat call PNC(word[1] ); 1:= 1+l untll 1>k;
Eg-Usg SC; call PNC(sP); 1:= k¡
repeat caLl- PNC(sordlil); 1:= 1-l untll t=0;
rcsume SC; call PNC(sP)
unt1l false
Ê¡1!( of Prlncer );
herltable var PR : 1n3Èance of printer;
error: boolean;
Dr lvate corouÈlne nords;
1f var word, k, error;
g¡od
seen var x' PRr SC; const sP' PnÈ;
lnltbegfn k:= 0 lnltend;
begin
repea t
tf (x=sp) or (x=pnt)
then begln
1f k>0 Èhen _bs4l4 resune PR; k:= 0 end
elee resune SC
end
else begln
lf k=20 then begln error:= true; exlÈ end
e lse
k:= k+l; vord[k]:- x;
resume SC
end
end
unÈil false
end ( of words );
begin { bodY of ualn Progran )
SC:- create scanner; PR:= create Printer;
llDS!= creare vords; PNC:= create prlntnexEchar;
error3E false; resume SC; wriÈeIn;
1f error Ehen { error exlÈ froo t\'lDStt caused return to nain prograrn )
wrfteln(spr'vord longer Èhan 20 characEers found')
end.

Ffeure B.3 Barter's Solutlon to the Odd I^Iord Reversal Problem

214
,,true'') and then Lhe execution of SC 1s resumed
the ||error', varlable to
to obtain the next characÈer'
ttword"; thls
The fnstance PR prlnts Ehe conÈents of the alltay
PR' and in the
prlntfng occurs in the forwards directlon on one entry Eo
reverse dlrecÈlon on the next entry. A space is
printed before each
word, except the first'
Af ter lts inl-tl-allzat.ions, the main
program Passes control to the
sc. Eventually, control w111 return to the maln program by
one
fnstance
oftworoutes;thebooleanvariable,'error''Ísexamlnedinthemaln
ProgramtodeËermlnewhethercontrollsreEurned(normally)becauseof
ttexlttt in IüDS'
the terrnlnatlon of SC, or (abnormally) via an
Anothersolutlontotheoddwordreversalproblemlspresentedin
FlgureB.4,alsoinACL.Thesamelmplementat'ionsofRNcandPNCare
ttxt" rrkrr and tbordtt have the same
used as before, and Ehe data items
rtPRrr contains an instance of
definitlons. Ttre instance variable
r,printer,, which has sllghtly rnodified deflnitlon from the corresponding
coroutlnelnFlgureB'3:ltuses"forttloopstoperformtheforwardsand
backwards prlnting, tt never prlnts a space before
a word' and it
transferscontroltoEheinstance'l'SP''whenasinglewordhasbeen
rrprlnterrr a sl-mpler
prlnted. The f lrst two of these combine to glve
'appearance 1n the program of Flgure B'4 than
the corresponding
deflnition in Flgure B'3'
Theremainderoft'heprogramlnFlgureB.4consisÈsof.aword-
(rrRSP'r) and the maln
reader (the instance ,,RWD,,), a space-reader
Program.TheÍnstanceRI^IDlsonlyenteredwhenaletterhasalreadybeen
found,anditsjobisËoreadlettersuntilaSpaceorpoinEis
tbrord"' Thls prograE
encountered, storing the letters ln the artay
adoptsadifferentstrategyonflndingawordlongerthantl.JenEy
letters,whlchisnevertlrelessequallyconslstentwiththeproblem
speclficaEion:theflrstÈwentylettersareregardedasoneword,the
lettersafterthemuptothenextspaceorpointarealsotreat.edin
word' hlhen Èhe
thls waY¡ 1f necessary' or a're regarded as a separaEe
entlre word has been read and stored, Ehe instance PR is
then resumed
for the PurPose of Prlntlng lt'

215
Drogran Oddl{ord2 ¡

herltable const sP=' '; Pnt'"'¡


varx:char;k:lnteger;
word : êlgl tl. '201 of char;
RNC : char ;
c;
hâr;
NC:= c Cnd ( of RNC ) ;
(lllyele value c:char);
, Drlvare generator PrlntnexÈchâr cont
DrlvaEevarl¡lnEeger;
seen consÈ sP;
begln
whtle true do
beÊln
vrite(sp); ( carralge control character )
for 1:-ì to 120 do bestn wrLte(c); return 9¡!;
wrlteLn
end
end { of Printnexrchar );
f orwarit ÞElvate coroutlne PElnter;
herltable var PNC : l-nstance of Prlntnextchar;
PR : lnsÈance of PrLnter;
Drlvâte coroutlne readword;
nod lf var x, k, r¡o rd ;
.o.ãÈ sp' pnc; var PR; funcÈion RNc;
"..n
begln
whlle true do
begln
k:'0;
whlte (x#sp) tna 1*#n!!ì and (k<20) lþ
U"*1" tt= k+t; çordtkl:= x; x?= RNC end;
resume PR
end
end { of readword )¡
herttable var RWD : lnsÈance qq readword;
Prlvate coroutlne readsPace;
rnodf f var x¡
.o,ilt sP' PnÈ; var PNc' RWD¡ functlon RNC;
"u"r,
beg.ln
whlle true do
beÊ1n
ghl-le x=sP do x:= RNC;
jq-*'pnc tnet b"gft call PNC(pnt); exlt e!4-
..1". b"g1" call PNC(sp); resume R!¡D end
end
end ( of readsPace );
herltable var RSP : lnstance q! readspace;
Drlvate coroutLne Prlnter;
seen var k, vord, PNC' RSP;
Prfvâ!evarJ:lnÈeger;
begln
wh1le Èrue do
begln
{ PrlnÈ forwards )
for j:=t to k do call PNC(wordljl);
resune RSP;
( Prtnt backwards )
foi 1:=t domto I do eall PNc(uord[ll);
resuDe RSP
end
end ( of Prlnter );
( bodY of maln Program )
begln
RWD:= create readword; RSPs= create readspace;.
pn := prlnter; PNc:= !reelg PrinÈnexÈchar;
"TããIã
x:= RNC; resume RSP
end'
Flgure B.4 Another Solutfon Èo Ëhe Odd ltord Reversal Problem

2L6
ttreadspacett) l-s to consume the
lhe task of RSp (an lnstance of
spaces between words, and the sPaces
and point after Ehe last word;
havlngfoundanon-sPacecharacter,thischaracterisexamlned.Tfl-tis
apoÍnt'RsPcallsPNCtoprlntltandexitstothemainprogramwhen
thlslsdone;lfthecharacterlsaletter'aneI^Iwordhasbeenfound-
to read Èhe word' It
firstly, a space 1s prinÈed and then RI{D is resumed
af ter the maln
1s RSP which 1s the flrst lnstance to gal-n cont.rol
and read the flrst characÈer'
program has created Ehe various instances
printed before the first
Notlce that thl-s solutlon causes a sPace to be
speclflcation of the
word' and that thls is also consl-stenÈ with the
problem.

DeplctedlnFlgureB.5arethesequencecontrolsÈructuresofthese
Èwoprograms;thatinFigureB.5(a)correspondsÈotheprogramlnFlgure
Figure B'4' The main
8.3, and that in Fígure B'5(b) to the program 1n
Programinstancesarethenodes,|oI^I1t'and'|oI^I2'''respectlvely;the
instancesofRNC,andEhelnstancePNC,areomlÈtedforclarity.Aslnthe
group 1s shown belolr
simllar dlagrams in chapter 2, the boss of a
membersofthatgroup;ineachofthecaseslnFlgureB.5,onlythemain
program lnstance ls caterval'

RI^ID RSP
I^IDS

OI,ü2

(b)
(a)
Two Solutlons to
Fi 8.5 The Sequence ConLroI Structures of the
the Odd l{ord Reversal Problem

ThesedlagramsconfirmEheimpresslongtvenbythetexËsofthetwo
Is cleaner and
programs: Èhat Ehe sËrucÈure of the second solution
slmpler.oneadvantageofthesecondsolutionnotevÍdentfromFlgure
resides within
8.5 is that during Èhe execution of thaÈ program, control
agivenlnstanceforlongerperlods;lnpartlcular,thecharacter.by-
characteroscillationofcontrolbet\'eenscandl^IDSinthefirst
solutionlsavoidedinthesecond.ThisnoEonlyaidsÈheundersÈandíng
of the program' but also lmproves lts efficlency'

2L7
8.3 Hannln tr ts Problem
ls descrlbed bY
The followlng Problem, atErlbuted to R.ïl.llamming
DlJkstra ln [36]:
ThewayËheproblemreachedmewas:r|Togenerateinlncreaslngorder
oiall numbers divisible by no
the sequence 1r213,4,516,8,9']¡
-iiå"'2, 'L2""
prirnes orher i,' ;, 5". Another way of stating whlch values
are ln the sequence is by means of three axloms:
Axiorn l. The value I ls in the sequence'
5*x'
Axlom 2. If x ls l-n the sequence' so are 2*x' 3*x and
The sequence contains no other values than
those ÈhaE
Axlorn 3. 2'
belong to lt on account of Axloms I and

TheACLPrograminFigure8.6lsbasedonthesolutlonpresented'
ttaq" is used to hold the
ln Dfjkstra,s own noÈation, ln t361. The array
membersofthesequencev¡híchhavebeengeneratedsofar,''index''
program ln Figure B'6
indlcating the last-generated member; Èhe
does Dijkstra's solution'
generates 1000 members from Èhe sequence' as
.'aq'' and points to the member of
The variable ',12,, is also an index into
thesequencewhosedoubledvaluewlllnextbeaddedtotheSequence;
tt*/tt The palrs of variables
thls doubled value is held 1n the variable '
ill3rr/rrx3" and rr15rr/rrx5" have similar meanings with regard to fnultiples
ofthreeandfive,respectively.IheinitiallzaÈlonslntheflrstgroup
.ofstatemenËsensurethatalloftheabovemeaningsholdforthecase
t'1" as lts only member'
that the sequence contalns the value
ThesecondgroupofsEatemenEsinFlgure8.6selectsthemlnímumof
,rx2rrr,,x3,, and ,,x5,,, and stores it 1n Ehe nexÈ avallable location in the
ar::ay"aq"'IhethírdgrouPofstatements'whlchisÍnaloopwiththe
ttx5ttto see 1f any or all
second grouP, Èests each of "x2"' "x3" and
contalnavaluelessthanorequaltot.hevalueJusÈaddedtothe
sequence;infactrthe"lessÈhanilpartneverapplies'andthistest
effectivelyfindsoutwhetherthevalueoftheparticularvariableis
equaltothevalueaddedÈothesequence.IfatesÈsucceeds,the
and ttí5t" are updated;
Varlable and the corresponding one of "12",ttÍ3tt
forexample,ifitlsfoundEhatthevalueaddedtotheSequencelsthe ttx3tt is
same as Ëha¡ in
,,x3", Èhen rti3rr is lncremented by one t and
to be three ti-mes the value of the element of l'aq" indlcated
redefined
bythenewvalueoflli3t'.TheflnalgroupofstaEementsintheprogram
merelyprlntsthe1000numberssÈoredinthearray'''q''.

2LB
Droßran Hannlngl;
Þrl.vate var aq : gIIs-.¡¿ t1..10001 ql lnteger¡
12,13, 15,x2,x3,x5,lndex : lnteger;
beeln
-iJnrttaLrzatlons ) l;
aqIl]:= l; lndex:=
12!= l¡ 133= l;15:= l;
x2¡- 2, x3:= 3; x5:= 5;
( generate the nutbers ln Èhe sequence )
whlle lndex*I000 do

whl-le x23aqIlndex] do
!rS1E 12:= f2+I; x2¡= 2*aq[f2] end;
whlle x3 laqIfndex] do
ES1n f 3:= 13+l; x3:- 3*aq[13] end;
vhlle x5Saqllndexl do
!9Cj8 f5:' f5+l; x5:- 5*aq[f5l end
end;
{ prtnÈ resulÈs } -
vrtreln('0ffrst lO00 numbers from the seq-' '
' uence : , , , , , , 9, I 0 ' f 2 ' ' ' ' ) ;
I 2 3 4 5 ó 8,
wrlte('0') ;
for lnclex¡=l Èo I000 do wrlte(aq[lndex]:17);
srfteln
end.
Problem
Figure B'6 Dljkstra's Solution of Hamming's

Theprogramdescrlbedabove$¡astransformedinÈothatShov,nin
FlgureB.T,throughthelnÈroductionoftÍToparameterizedsubprograms
(bothgenerators)tofactoroutoPeratlonsperformedanumberoftimes
.1nt'heprogramofFlgure8.6.Thefírstofthese,ageneratorcalled
group
,rhlext", represenÈs a parameterization of Ehe code in the second
ofstatementsintheorigtnalProgramwhlchaddsanewmembertothe
sequence;therearethreeinstancesof|thiext'',whichatecalled
||extend2,t, ,,extend3,, and ,,extenö',, correspondlng to the cases that
the

nesrmemberlscurrentlystoredin,,x2,,,llx3llor||x5||'resPectively.The
than a procedure lras that
reason for making 'rhiext" a generator rather
to be established as
thls allows a reference to the apProPriate variable
which 1s RO slnce onry the R
each lnstance is crea¡ed; this reference,
rlghtlsrequlred'isretainedbytheinstancethroughoutitslifeÈime
andthlsobvlatestheneedtoPassareferenceÈo'orthevalueof'the
a neÍI value to the axray "aq"'
varlable each time 1t is necessary to add
The name ,,hiexE" was chosen slnce lt
corresponds to an operatlon of thls
nameusedbyDijkstraEoextendthe(index)dornalnofanarrayandto
append a ner't element at the high end
of Ehis donain'

2t9
prograE H8m1n82 ¡

ÞrlvaÈe tvpe a = arrâv fl"l000l of lnteger;


Yag-x2, x3, x5: lnteger;
herttable fg¡ aq: a; lndex: lnÈeger;
prlvaLe generator hlexÈ lnlt (-p¡-!yg!.g seen addttlon:lnteger );
nodlf var aq, lndex;
b"gl.
whlle- true do
begin
-Jiã.*t= lndex * 1; aqllndex] ¡- addlÈ1on; reÈurn
end
end ( of hlexE );
DrlvaÈegeneraÈornextj!g!!(¡¡1ye!emod-lfvhlch:lnteger;
vaioe t"rtlpller:lnteger) ;
seen var aq, lndex;
Drlvâte var 1¡ fnteger;
ìnftU"efn i:= I fnltend;
begln
r¡hlle true do
beß1n
whlch 5 aq I lndex] do
--¡9¡119
b egln
--Ï:. f+t ; shlch:= nultlPl1er*aqIll
end ¡
return
end
end ( of nexÈ );
prlvaÈe var exÈend2, extend3, exÈend5: lnstance of hlext;
next2, next3, next5: insEance of next;
( bodY of naln Prograu )

( generaÈe Èhe nunbers ln the sequence )


whtle lndex#I000 do
beeln
=f|t*r¿x2) and (x2 lx5) +rq9+ extend2
else ff ixzjx3) E (*¡sx5) chen call exÈend3
;É;11 ixz¿x5) e¡4 ("tsx3) then call- exlend5;
ãrr next2; nexÈ3; carl nexE5
- end; -carl
( prlnt results )
*,rìt"f.('OtfrsÈ l00O numbers from the seq"
'uence: 1,2,3,4,5,6'8'9'10'12" "')¡
wrlte('0') ;
for lndex:=l to t00O do srl¿e(aqIl-ndex]:17):
srlEeln
end.

Fl.sureB.TTransformingDiJkstra'sSolutionofHaÛ¡ming'sProblem

Thesecondgenerat'orlntroducedlntheprogramofFlgureB.T
representstheactionsPerformedbyeachofthethreeloopsinthethird
generator (called
group of statements ln Figure B'6; Ëhat 1s' Èhis ttIztl
,rnext,,) updates the values of a particular variable palr' such as
and rrx2rr, 1n the program of Fígure 8'6, when
this updatlng ls necessary'
It has two parameEers: a RI^l reference to one of the variables "x2"'
"x3"
to the variable
and 'rx5'r, and the value of the multiplier corresPondlng
thls case
(that is, elthex ttztt, "3" or rr5rr)' The use of a generator in
rrí3rr and tri5rr to be abandoned' their
enables the varlables "í2",

220
functlonsbelngperformedbythevariablerlllllocaltoeachofthree
stored 1n Èhe variables
lnstances of "next" (these lnstances are
,rnext2,,, ,,nexE3,, and ilnext5rr). Thls ËranSfOrmatlon of three global
variableslntoaslnglevarlablelocaltoeachofthreelnstances
emphaslzesthecommonPurPoseofthethreeoriginalvarlablesand
lmprovesthedatacontrolstructureoftheprogrambyllnitingaccessaS
uuchaspossible.NoÈe,hor.zever,thaÈthlstransformation\.Iasonly
posslblebecauseÈhevariables''f2,.,''i3''and''i5''areonl.yusedinthe rrnextl'
the task of was
inltlalizaÈl0ns and the block of code from which
factored,l-ntheoriginalProgram;asfmilarÈransformatloninvolvlng
rrx3rr and "x5tr is not possible'
the varlables ttx2'rr
TheprogramlnFlgureB.Brepresentsanentirelydlfferentsolution
coroutines (or' more
to Hammlng's problem; lt l-s a soluÈi-on which uses
accuraÈely,generators)asltsbasisandcanberegardedasexhlbiting
,,dlstrlbuted controlrr. The essence of the solutlon is the following: as
(returned as the value of the
a new number fs added to the sequence
ttnextnumberrr)' an instanee of
lnstance t'next" of the generator funCLlon
it ls to generaËe' in
the generator r'üult'r is created whose Job
aequence,thethreemultiplesofthevaluejustadded.Also,tlrerelsa
I'acË1ve llsÈ'r), whose head is lndicated by the
llnked list (call ic the
globatpolnËervarlable,,activehead'',whlchcontainsoneltemforeach
.lnsÈanceof,,mult,,stlllactlve.ApartfromapolntertothenexLltem'
each active list item conÈalns an instance
of ttmult" and the next value
to be generated bY that insËance'
ThegeneraÈlonofanewvaluefromthesequencebythelnstance
,,next,, begins by flnding tlre minlmum of the values in items on Ehe
,'fífidmin''. Next, the procedure ''erase''
active list, using the proeedure
lscalled,anditscansalongt'heactivellstlooklngforal]-ltems
ruhosecurrenEvaluelsthesameasthepreviouslycalculatedminlmurn;
eachofthelnst'ancescorrespondlngtoÈheseitemsiscalled,causlng
themtogeneraEetheirnextvalue.Ifthelastvaluegeneratedbyan
Ínstanceof,,mult,,slasltsflvernultiple,thelnstanceannoun.cesEhe
variable "flnlshed" to
completlon of its task by settlng the global
,,true", as a signal to tterasettthat lÈs item on the actlve list may now
returning to "eraset"
be removed (uslng Èhe procedure "remove")' Before
attrlbute, which is a
the lnstance of ,,mult,, f lrstly sets lts ',th1s''
valueparametertndlcatlngEheltemontheactive]-istforthts

22L
ÞrogråE Haonlng3;
prlvaÈe g! aq ! array tt"l000l of lnceger¡
I : lnteger;
herltable genfunc nextnuEber : lnteger;
fors¡ard PrlvaEe ll!9 acÈ1ve;
her.ttable tvpe acEfvep¡¡ = J¿ctlvei
fofl¿ard ÞrivaEe generaÈor nult lnlc (value activePtr'
1nÈe8'er);

prlvaÈe ]LIP. acÈ've -


l#, ÍnÈeger;
lnat : lnstance of nult;
nexÈ: actlvePtr
end;
herlÈable JgI actlvehead : actlvepÈr;
ftnlshed ¡ boolean;
h erlÈable lnser E (p rivate s een whlch :a ctiveP cr) ;
¿r-9-g94C-Eg.
nodlf var acÈlvehead;
beeln
( the new elemene 1s lnserted aÈ the head of the 1f8È )
whlchf . next : = acElvehead ;
accfvehead3= \'hlch
end ( of lnsert );
herltablegrocedureremove(prlvateseenwhlchlacÈlveptr);
nodif var actlvehead;
geen ÈYpe acÈlvePEr;
Drivate var Ptr ! actlveptr;
beÊln
;!f actlvehead=whlch
-l-hes ( renove flrsÈ elemenÈ of 118È )
-ãctlvehead :' wh1chl'next
else
beeln
J frtt¿ eleeenÈ to be renoved )
Ptr:- acElvehead; ptrJ'next;
¡1h:!þ ptrf'nexElvhlch do PÈr:-
{ renove 1r )
Ptrl.next :- whlchJ'next
end
g¡4 ( or renove );
prlvaÈe procedure findnln (¡¡fvgfg nodlf nin:fnteger);
aeen lJPq acclvePEr;
var actlvehead;
orivate var Ptr : actfvePlr;
begln
-îG,' actlveheadf 'val; Prr:= acelveheadl'nexL;
nhlle Ptrlnll do
begl-n
-lfptrJ'vtlcnln then nln¡= PÈrf'val;
Pt.r:= Ptrl .nexÈ
end
end { of flndnin );
prlvare Drocedure erase (priYate value n:inÈeger);
-ÊgrE-llPC ."ti"eptr; proc"dur" renove; var acElvehead;
nodif var finlshed;
Drlvate var Ptr : activepÈr;
besln
pcr:= acclvehead;
r¡hlle Ptr#nl1 do
beqln
ff Ptrf'vaI=n
then
begin
call PÈrf inst;
ff flnlshed Ehen
legqq removeþtr); f inlshed:= f alse end
end;
Ptr:= Plrl.nexÈ
end
ggd { o¡ erase };

Fieure B.8 Another Solutfon to Hammlng's Problem

222
prlvate generator nult
lnf¿ 1¿¡!veqe value th13:actlvePÈr; vålue x:lnteBer);
uodlf var flnlshed;
seen orocedure fn6ert;
lnitbegln thlsf.val:= 2*x; lneert(thle) lnlÈend¡
begln
-î-Z** has been congumed ) thisl'val:= 3*x; reÈurn;
I 3** h"" been consuned ) thlsJ'val:- 5*x; le$!n;
5*x h"s been consumed - slgnal thst thts lnstânce has
i of nunbers )
flnlshed Seneratlng lta sequence
flnlshed:' true; Ehls:= nll; return
end ( of nult );
prLvate var newone : actlvePtri Dln : lnÈeger;
geen genfunc nextnunber;
{ body of nextnunber }
i.i.iátr" acÈlvehead¡= nll; flnished:- false inltend;
begln
:îãi(n."on.)
; newonef 'lnst¡- create rnult(newone'l) ¡
nextnunber:- l; newone:= nll; l!.lq!rg;
whl-le true do
begln
-îGd.ttt(.tn) ; erase(nln) ; new(newone) ;
nesonel.lnst!= creaÈe nult(newone'min) ;
nextnunber:= min; newone:= n11; reÈurn
end
end I of uexÈntmber );
Drlvate var nexÈ : lnsEance of nextnunber;
( body of maln Progran )
begln
next :Ê create nextnunber ;
for 1:=I ro 1000 !g aqtll:= next;
( Prtnt results )
itilor"<'0flrsÈ 1000 numbers from rhe seq"
'uence: Lr2,Jr4,5, 6, 8r9, f0' 12" "' );
vrite('0') ;
for t:=l to 1000 do write(aqIi] ?I7);
r¿r lteln

end.

Figure B'B (contlnued)


management' sLnce otherwlse
l-nstance, to trnl1"; this helps ln storage
Èhe lnsEance of "mul!" and its dlscarded
item from the active llst form
a rlng of garbage'
AftertheerasureProcessdeserlbedaboveÍscomplete,Èheinstance
,|next,,createsanewltemfortheactlveltst(butdoesnotl-nsert'lt)'
andthencreatestheinsEance,,mult''whichlstolookafterthe
generationofnultiPlesoftheminimumJustfound;thisinstanceís
st'oredÍnEheínstancevariablefieldtlithinthenewltem.The
ttmult" involves setÈi-ng the
lnttializaElon of the ins tance of
aPProPriatevaluelnÈhenewacEívelistitemandtheninsertlngthis
ltemlntlrat'llst'usingtheprocedure.'insêfE||.!ÍhenconErolreturnsto
the nel' Ínstance of
the lnstance,,next,'after the lnitlalization of
,,mult", it sets the value to be reÈurried in 1ts pseudovarlable' sets the
ltem Èo "nLltt (thts
pointer used 1n the creaElon of the ne\t7 actlve list

223
returns tso its caller' the
helps in the early recovery of storage) and
maln programr where the ner¿ value is sÈored
ln the array "aq"'

Ffnally,therelsoneaspectoftheProgramofTigureB.Bwhich
makesltqulteunlikeanyoftheotherprogramslnthisAppendíx:the
number of members ln the group with Ëhe
instance "next" as íts boss is
hfghlyvariablerandlÈsvalueataglvenpol-ntlntheexecutlonofthe
program 1s not at all clear from the program
text'

8.4 n lut to 's Prob

used by Grune[59J to
The following ,,hl-ghry contrived" problem l-s
lllustrate his view of coroutlnes:
-'i""]' the outpuÈ will have rrbtr
I,IehaveaprocessAhlchcopl-escharactersfromlnputtooutputwith
Èhe provlso that hrhere the i"p"a-ï;"
lnstead.Andwehavea"r'iiä'processBwhiclrconvertsllbbtllnto
|rc,'.No\.{$'e\.IantEoconnecttheseProcessesinseriesbyfeedingÈhe
output of A lnto B '
Grunepresentsa',1ow.leve1'|Algol68solutlon,aSinulasolutlon
and'flnally,anotherA1gol68solut'lon,th1sËlmeuslngconcurrenf
processesandsemaphores.Grune,sSinulasolutlonlnvolvesinstancesof
twoclassdeflnitlonswhlchareslmllar,butnotidentlcal,whicheffecE an
,,resume,,; subsequently, Lynnlng[99] proposed
conLrol transfers via
,alternatlve sirnula solutlon involving thro lnstances of a single class
deffnition,ÈheseinsEancesbelngtreat'edasseneratorsthroughtheuse
ttdetachtt'
of ttcalltt and

Lynning's soluÈion' translated lnto ACL'


1s presented 1n Flgure
8.9; the program, in execuÈ1on' conslsts of four instances:
nexÈ character
(1) the lnstance t'nextchar"' which slrnplY reads Èhe ttchtt,
from the lnPuÈ text and stores it tn the varlable
of bya
ll- ll
(2) the lnstance rrArr, which replaces double occurrences
d

a character'
sl-ngle "b", calling 'rnextchar" tshen it requires
occurrences of
(3) the lnstance "8", which rePlaces tr¡ro successlve
ilbtt ttctt, calling on the lnstance A vrhen Ít requlres
wlth a slngle
a character, and

B f.or Lhe nexE


(4) the maln progran' which cal-ls on the lnsÈance
(stored 1n the variable
character and then prints Ehis character

224
t'chtt) when conErol returns'

-Ee,SEês LYnnlng;
herlEable var ch : char;
Drivate qenerator fnchcoroutlne;
rrodlf var ch;
begln
-
lhlfC true do begln read(ch); return end
end { of lnchcoroutine };
DrlvâEe qeneraEor converÈer lnit þ¡-¡¡vg¡e seen cl' c2: char¡
seen Producer: generator);
Dtlvâte var chl: char;
nodif var ch¡
begin
whtle true do
begln
call Producer;
ff ch=cl then
begln
call Producer¡
lf ch=c I
then ch:= c2
else
begin
chl:- ch; ch¡= cl;
!et-c-En;
ch:= chl
end
end;
Eeturn
end
end ( of converEer );
prlvaÈe var nexEchar: lnstance of lnchcoroutlne;
. Ar B: lnstance qq converter;
begln
nextchar:= creaÈe lnchcorouÈ1ne;
À:- creaÈe converter('a' ,'b' ,nextchar);
B!= create convercer('b' ,'c' ,A);
wrlte(' ');
whlle Èrue do
besln eall B; wrlte(ch) 9¡¡!;
çr I Eeln
end.

F1 e 8.9 Lynnfng's Solutlon to Grune's Problem

ThisProgramisparticularlylnterestingbecause,unllkeanyof
Gruners solutlons, the conversl-on of double characters
into sl-ngle ones
1s performed by dlfferent lnstances of Ëhe same subprogram deflnltlon'
only with
To achleve thls, the subprogram has to be parameterized not
resPecttothecharacterconversion(forexamPle'thatthefnstanceA
ttatt lnto a ttbtt), but alSO wlth respeq¡ to
COnVertS tqro Oqcurrences of an
whtch lnstance it is that thls lnstance must call when 1t
requires a
ttproducertt in the
character. This latËer paraüeterizaËion (the parameter
the use
deflnltion of rrconverterrr) is easily accompllshed ln ACL through
The Slmula
of the language,s |lgeneral instance Parameter'' feature.
introduced'
verslon ls a llttle more clumsy' sÍnce a durnmy class mustbe
ttConvertertt made SubclasSeS of 1t t to
and both t'inchcOroutinerr and
achleve the same effect'

225
l-rsÈly'
of the instances of 'rconvertert' behaves às foll0ws:
f
Each
theaPproprlateproducerlscalled.IfthecharacÈerreÈurnedin'.ch''is
control 1s returned
not the one soughÈ by thls insÈance (that 1s"rc1") '
then this insÈance
to fts caller (its .consumertt). rf ít 1s a "c1",
callson1Èsproducerforanothercharacter;ifÈhlssecondcharacterls
rrchrr is set to the appropriate
also a ,,c 1" , then the variable
replacemenÈ character ("c2t')' If ' however'
the second characËer is not
thesameasthefirst,whlchwasa,,cl'',thesecondcharacterisstored
trchrr 1s then set to that of
ln che local varlable "chlt'; the value of
"cl"andcontrolreÈurnedEothecallerofthlsinstance'Onthenext simply
occasl-on that, this lnstance is call-ed on
for a character"'chttis
Èo the caller; the
set to the value sÈored ín 'rchl" and control returned
lnstancehasno!ürecoveredfromltsonecharacterlook.aheadandcan
contlnue executlon as before'
Noticethattheproducer/cönsumerrelatlonshlpslnthisprograü
ensurethaÈ,lnÈhesequeflceofcharact'ers'.aab'',i'aa|'¡¡í11flrstlybe
ttbb" \^tlll become "ctt; slmllarlly' Èhe
Converted to "b'r and the resultlng
sequence "baa" wíll also end up as "ct"
slnce when B asks A for a second
ttcltr Value' a rrbrr whl-Ch
character after detectlng an occurrence of lts
1s the result of convertlng the sequence "aa" will
be returned'

'8.5 A Data Abstr acf l-on Example


AsmentlonedinSectlon4.3.l.l,Koster[84]hasexpressedthevj-erv
in a programming
that Ehe need for speclal data absÈracElon facllities
languagecanbeobviatedbyprovldlngsufflcientlyexpressivedaËa
the validity
control facirlties in the language. rn order to lnvestigate
ofËhlsvlew,andthesufficlencyofACL'sdataeonÈrolfeatures,itwas
decldedtoaËtemPtthelmplementatlonofadaÈaabsÈractlonlnthe
language;theeasewiElrwhlchthlsr¡asdonelspartlcularlyslgnlficant
sincetheprovlsionofadataabsÈractlonfacllitydidnotent'erinEo
the deslgn considerations of ACL'
been used ln
The example chosen was one which has ofÈen
(see' for example,
descrlptions of data abstraction facilitles
stackrr ' The set of ope-ratÍons chosen
is
[23, 84, 98, 164J ) : the "pushdown
Ëyplcal of treatments of thls exarnple:
. 'rpush" appends an element to the top of the sEack'

226
"poPt' dlscar<Is the element
on top of the stack'

t'top" returns the value of Èhe top element of Èhe stack' and

ttemptytt ret.urns tttruett if the stack contalns no elements'


and

ttf alsett otherwise '

Slnceltl-snotpossibletoparameEexlzeACLsubprogramsbyLyPe'
for stack elements; the
tt was necessary to choose a particular type
tyoechosenwas,,Ínteger,,.Stacksforot'herÈyPesofelemenEswouldneed
to be r.{rltten as seParaÈe subprogram deflnltlons'
TheACLversionofthestackabsLractlon,andsomeexamplesoffts
use, aPPears fn Figure B'10' Each stack
ls an instance of the generator
1t ls the local data of these instances r¿hlch ls the
'lpushdownstack',;
concreteimplementationoftheabstracElon.ThegeneraÈorhasfour
contlnuatlonparameters,theflrstofwhlchlndicatesÈheoperationto
beperformedonÈhesÈack.Dependl-ngonthlsoperatton,certainofthe
remalnlng three parameters may be used:
. rrpush" exPects the integer to be pushed onto the stack as the value
of the second ParameEer''

Ehree paraneters'
' "PoP" uses none of the last
.tttoP"returnsthevalueofthetopelementofthestackvlaÈhe
fourth Parameter, and
.,,emPtY,,ret,urnsÈhevalue,,true,,or''false''bymeansofthethlrd
Parameter '
ItfscertalnlytruethaÈthesynEaxofthecallsapplylngvarious
oPeratlonstothesÈackslnFlgureB.l0lsmoreawkwardthanwouldbe
thecaselnalanguagewlthaspeciallzeddaÈaabsËractionfaclll-ty,but
theessentlalcharacterístlclspresent:therepresentationofthe
("stack" and "tos") ls hldden and can only be accessed via a
abstraction
specificaËion of a data
supplled set of operatlons' Although Èhe
absEractlonlnACLwasaidedbythelanguage'sdat.acontrolfeatures,
thefeatureofthelanguagewhichmadeltfeasibleatallltlasthe
faclllty; thls Permitted
coroutine (or, nore specifically' generator)
and to have the
the representa.ion Eo be deflned local to a subprogram
samelnst'ancesofthevariablescomprlslngÈhtsrepresentatlontobe

227
used on successive entrles to the subprogram'

ÞroEram SEackTest(outPut) ;

Drlvate tyÞe oP - (pushrpoprÈoprempty);


prlvaÈe ßenerator Pushdownstack 99n! (¿f1ye!g value oPeracfon:oP;
3399 val:lntug"'; todlf bóol:boolean; nodlf lnt¡lnÈeger);
Drlvåtg const maxslze = I00; { maxlnum staek slze }
ìiõã-"¿."kt.nge = I"naxslze ;-
var store , [scackrange] of lnteger; {.Èhe stack }
"Ir.u
to" ; t.Tã!ãi; { the currenc top of stack }
inltbeßfn tos:' 0 lnltend;
begln
whlle Èrue do
begln
case opelatlon gl
Push:
- lf tos(maxslze then
val end;
-!.g,g-lq Èos:= Èos + ll store[tos]:=
PoP: ;!!-tos>0 lqlsq Èo3:= tos - l;
iop, lf tos>o tÏt"tt ltt:= sroreIcos] else lnÈ:= 0;
enPtY: bool:= Èos=O
end;
return
end
gq t tf Pushdownstack );
Drlvate var sÈackl'stackz: instance of pushdomsÈack;
newel, toPel: lnteger; Dt: boolean;
begln { Some examples of operaÈlons on stacks }
{ create tr{¡o stack obJects }
etackl := creaEe Pushdownstack;
stack2: = create PushdownsEack;
( lnltiallze conÈenEs of flrst stack )
call stackl(Push,2,nr' toPel) ;
catl ataekl(Push,5,nt, EoPel) ¡
(push, 3,rnt, toPel) ;
""ll "ta"kl
( lnlÈlallze conEenÈs of second stack )
caLl stack2(Push' 7,rt' toPel) ;
call stack2 (Push, I'nÈ, ÈoPel) ;
( print out toP elemenÈ of both scacks )
gg!! etackl (toP'newel'nÈ, ÈoPel) ;
ilrl.teln('toP elen-ent of sÈackl ts
call etack2(Èop'newel'nt' topel) ; "topel:3);
älcern(' top element of stack2 ls ',toPel:3);
( pop top element fron flrst stack' Prlnt ouÈ 1Ès (new) qop elenent'
ãnã thet Pop rest of elenents fron that stack )
call stackl (poP, neweJ.,mt, ÈoPel) ;
call stackl(roP'newel'nt, toPel) ;
,ri-ft.f.(' top àlement of srackl ls now
, call stackl (PoP 'nesel'mt ' EoPel) ; "Eopel:3);
(PoPrnewel'mt, EoPel) ;
""ll "tt"kl
{ lndfcaÈe whecher sÈâcks are empcy )
call s tackl (enPty'newel'nt' Èopel) ¡
wr1Ee(' stackl ls ');
ff not mÈ lhen wrtte('noÈ ');
wrl reln ( 'enP rY' ) ;
-gg11
scack2(emPty,newel,mt, topel) ;
wiite(' scack2 ls ');
lf not nt then wrlce('noÈ ');
r.rrl,ÈeIn('euPtY') ;

end.

Flgure B.10 The Stack Abstraction ln ÀCL

228
REFERENCES

G. At tardi
tfl L.Alello, M.AleIlo' Generallzed ?.Cavallarl and G'Prinl-r "FormaI
' Control Regimesr', Math ematical
Definition of Semantlcs of
of t rSc cel 76 À.Mazurklewicz ( Ed. ) {Lecture
Fo aL
1 7 3-L79 (SPrlnger-Verlag,
Berlln,
Not es in ComPuÈer Science, VoI.45), PP.
L97 6) .

A.L.Ambler ' D.I.Good, J. C'Browne, I^I . F. Burger , R.M'Cohen,


t 2J
C.G. Ho ch and R.E. Wells,
ItGypsy: A Language for SPeclficaElon and
tt
Pro A. C.M. Conf erence on
ImplementaÈ1on of Verlfiable Progra
ffrs ,
(Ed' . c.l"t. sIGP
Des l- for Rellab Sof re D.B.I^lortroan )

Notlces, Vol.12' No' 3 (Ifa rch 1977 ) ), PP. 1- 10.


[3] American National Standards Institute' U SA StA rd FORTRAN.
¿,nsr i¡.g-Lg66 {Approved March 7' 1966}
(A'N'S'r' , New York,1966).
he Value Parameter (VP) Overaug- the
ed memorandum {Translated and
titut ftir Informatlk, Eldgen8ssische
y L972).
of Structured Programming Applíed to the
t5l U.Anmann, "Ihe Method
erna ional Co L S sl
Develóproent of a ComPllerrr'
1g73, A.GtlnÈher, B'Levrau and H.Lipps (Eds.), PP. 93-99 (North Ho lland
P"b. Co., AmsÈerdam' L974)'
ttClauses: Scope Structures and
16I E.A.Ashcrof t and w .Vl.l.Iadger the Flf rh A.c .M. SvmPosium
Deflned Functlons in Lucidr', Conf. Record ofpp.I7 -22 (A.C.M., New York'
Pri le ofP a
1978 ) .

' 9th
August
t7I K. Babcl-ekY personal comsrunlcatlons (5th ApriL 1977
'
1977 ) .
ttSome Notes on SDG Recommendation No. 2", Simula
t8l K .Babcicky,
News let.ter , Vol.6 ,- Ño. 2 (MaY 1978 ) , PP ' 15-17 '
D.I'I.Barron ' An Intr oduct
t9I to the Studv of P eramming
1977 ) .
Languages (Canbrldge UnlversitY Press ' Cambridge '

-tåp"rt*ãrrr oi" Conputing Scienãe, The University of


tr0]c.J.Barter,.,Programmlngf,TlthlnteractingProcesses'',Technical
Report No.75-0f,
l¿ãtaf¿e, Adelaide, iouth Australia (f975)'
tr,
ans formatlons
G. L.I^Iolf endale
Canberra, Aus-

D.P. Shecter, F'tr'I'TonPa and A.van Damt


t12l R.D.Bergeron, J'D'Gannon' Co ers M.Rubinof f
nSystems programming Languages", Adv S

(Eã. ), vol.12 (r972), PP'175-284'

229
to ?ro osi on Da
t13l D.M.BerrY, rrlnEroducÈ1on Oreganorr,
(Eds.) {A.c.M.
i La J.T.Tou and P'l{egner
Stru tures Pro rnml-
No.2 (FebruarY 197 ),
1) pP.17 1-190'
SIGPLAN No tlces , Vol.6,
or Deletlonrr' Conf.
lf4l D.Ùf.BerrY' "Block Structure: Retentlon f uE Pp.86-
f rd Ann A.C.M. oslum
ord
100 (4.C.M., New York, I97 f) '
A' Sorkln,
t15l D.M.BerrY, L' Chirlca¡ J.B'Johnston' D.F.Martln andHi
m
rrOn the Time Requlred for ReÈentlonrr, Pro S OS

. c.M. S IGPLAN NO ices Vol.8, No.ll


L Compute rAr chlte cture
(November 1973) ), pp.l65-178.

Bego. Sr.a.o;-ir.tU""it publtstters Inc" Philadel-


t16]G.M.Birtwistle,o.-J.Dahl,B.MyhrhaugandK.l.}ygaard,Simula
(Studentliir"r"rrri,
phl"; PennsYlvania; I973)'
M.Ohlin and J'Palme' DECsvs tern 10
t17I G.M.BirErlist le, L.Enderin'
I Swedish National Defe nse Research
ua Ha book Pa C 839 8-ì.13(85),
IMULA
Instit.ute & Norweg ian ComPutl ng CenLer { also: ReportSr,reden (De cember
Swedish National Defense Researc
h InstituÈe, Stoc kholm,
197s ) ).
ttNew Programmlng Languages for
llBl D.G.Bobrow and B'RaPhael' Co rnr¡utlng SurveyS ' Vol.6 , No.3
Artificial Intelligence Research"'
iiãpu.tu.x L97 4), PP'r53-L7 4'
ImplemenLaEion of
t19l D.G'BobrosB.trlegbrelt, ttA l"fodel and Stack
and
vol. 16, No . 1o (october I97 3 ) '
Murtiplã EnvironmenÈsrr' Comm. À.C .M: .
pp '5 9 1-603.
3rA l"lodel f or Co ntroL sËructures for
l20l D.G'Bobrow and B 'l{egbreit' I .E.E.E. Tr
-Artificlal Intelligence Prograruming Languages"'
-coryg-.r-q-,
vol.õ-ãil nt'¿- (apirr Lg76)¡ PP'347'353'
R'E' Griswold' D.R.Hanson and
l21l D.E.BritËon, ReF .C.Druseikls,
ferenclng Envlronmenf s in SL5", Co nf . Re-cord of
R.A.Holrnes r "Procedure fP La e )
Third A.C.lf. s Pr 11C1 les d

he OS

pp. I85-19 r (A' C.M., New Yor k, 1976).

L977 )'
Í22lBurroughsCorporatio^n"'BurroughsBTO00/86O00ALGOLLanguage
DeÈrolÈ l"fichlgan
Ref erence l,fanualr' (Burroughs
Corporaulon
' ' '
1n
\^I.D.Elliottr'rAbstract DaLa Types
123l E.Chang, N'E'Kaden and vàr-.rr, No.3 (llarch 1978), PP'34'42'
Euclld", A. C.M. SIG PLAN No t ices
D.F.Martin, J.G'Peetz and A'Sorkln'
t24l L.M.Ch1-rica' T.À.Dreísbach, the Dang llng Reference, ImPosEer
rrt^ro EULER Run Time Mo<lels:
PARALLEL 1- n
Pr um Hi
EnvironrnenL, and Labe l Problems",
S OS

. SIGPLAN No tic Vo1.B, No. I I (November


uter Àrchí ecÈu . C .1"í

1973)), pp.l 4I-15r.


ttProgr amming Language Const ructs for i¿hich 1t
l25l E.M.Clarke , JE. , rd of
to 0b taín Good Hoare- like Axlom SYstems t Conf.
lsI mpossible L es
f'our h A. C.l'f . lum on Prin I I of Pro
the

230
pp.10-19 (A.C.l'l' , New York, L977)
'
t'Provlng Correc^Eness of Coroutlnes without
t261 E.M.Clarke, Jr', CS:I978-4, DeparÈment of CompuÈer
HÍstory Varlable-sìì,' fechnical RepJrt (March f978)'
Sclence, Duke Univárslty, Durham' NorEh Carollna
CorouEinesrr, Acta Informatica, YoL'Z
Í271 YL.CIlnt, "Program Provlng:
(1973), PP.50-63'
rrConÈrol of Sequence and Parallellsm in
t2Bl L.L.Constantine' J int u rCo erenc r96
Modular Programstt, Proc. r (Thompson Book
ceed ) Vol.32)
pp.409-4 14
A.F.I .P. S. Conf P
'
Co. , l,Iashlngton' D.C. , 1968).

t29l M.E.ConwaYr'rDesign No.7of a Separable Trarrsition-Diagram Cor


pilerrt, Comm. A'C'M', Vol'6, (July 1963), PP'396-408'
Larrguages", Pro qrammlng
l30l 0.-J.Dahl, 'rDiscrete Event S imulation
ade¡nlc Pres s , Iondon , l9 6B).
Lansuages , F.GenuYs (Ed. ) , PP.349-39s
(Ac

l, ItAn Approach to Correctness Proofs of


t31l 0.-J.Dah
tr, Mathematical FoundaÈion sof Compu ter Sc Íence Third
Semlcoroutínes Vol. 2 B ),
A.Blikle (Ed') {Lecture Notes in ComPuter Science,
pp.L57'17 4 ( Sp ringer-Ver lag , Berlln, L975).

t32l O.-J.Dahl and C'A .R.Hoarer "Hierarchical Program SÈructures'r'


Stru cEured Pro srammlng
'
O.-J.Dahl, E'I'I'Di jkstra and C 'A'R'Hoare
(Academic Press'
{A.P.I.C. St udies ln Data P rocesslng, No.B), PP'L75-220
London 1972).
'
r'--L-r-^..^ ^^Å I{- ñvoanrd- l'Common Base Languagett,
t33l O.-J.Dahl, B'Myhrhaug and K'l'lygaard'
Norway (Oetober
PublicaÈlonNo.s-22rNorweglancornputlngcenter'0s1o'
- 1970) .
rrCoroutines and Parallel CompuÈationrr' Proc. Flftl
\" t34I J'B'Dennis' tion san S ST t97 L pp.293-
ince Co Inf a

294.
ttNotes on SÈructured Programmíngrr, Structurell
t35l E.trI.Dijkstra' R.IIoãre {4.P. I. C. Studies
Pro srammj-nq O.-J. Dahl, E.I^I.Dijlèstra and 'À'
C
P ress' London, 1972) '
1n DaÈa Process lng, No. 8), pp.1-82 (Academic

t36I E.W.Di jkstra, A Disci-pline of Programning (Prentlce-Iiall Inc' '


Englèwood Cltffs, New JerseY' 6) .
L97

l37l J.N.Doyle, "A Generalized Facillty for the AnalYsis and SYn-
Model of an ImPlementaElonr',
thesls of Strlngs, ana a Procedure-based Sclence, The UniversiEY
Technlcal Repori S4D4B, DeparEment of1975)'
CompuÈer
of Arizona, Tucson, Arizona (February
t3Bl F.C.Druseikis, "The Design of Transportable InterpreÈerstt,
SNOBOL4 Project Documlnt S4D49'
Department of Computer Science, Ihe
universltyof/ltízonarTrrcsonrArízona(Februaryl975)'

23L
J.N.DoYle' trA Procedural APProach to Pattern
t39l F..C'Druseikls and
A.C.M. Na iona Co fere eP ce S Vol. 2 9
Matchlng 1n SNOBOL4T',
(1974), PP.3rr-317'
of Pro L (Scfence Research
t40l M.Elson' Co
Associates Inc' ' Chlcago, Illinois '
L97 3) .

s uctu ES (Science Research Assoclates Inc' '


t41l M.Elson' Da
Chtcago, Illlnois' 197s ).
C.N.tr'ísche r and R. J. LeBIanc,
ficlent ImPlementatlon
ttEf and
l42l in Pascaltt, Proc. A.C.M. Co nf. on
Optlnlzat lon of Run-Èime Checklng (Ed.
tware, D.B 'I^Iortman A. C.M. SIG
)
e Desisn f or Re Itab 1e Sof
(l"Iarc h 1977 ) ), pp.L9'24.
&tices-' Vo L.L2, No. 3
t'A SurveY of Contr ol Structures in Programmlng
l43l D. A.tr'isher, Lan B.l"l.Leavenworth
Languagestt, Ero SEru ture 1n Pro 72)>,
ice Vol.7 , No. I1 (Nov ember 19 PP.I-13'
(Ed. ) .C.M. SIG PLAN
isher, trDoD's, Common Prograrnming Language Ef f ort'r,
t44] D.A.f
CompuEer, Vol. rr, rqá'l (March -r97B) I PP'24-33'
rrNonde-Èe-r¡nl-nistic Algorithms"' J. A.C.M. Vol.14'
t45l R.!ü.Floyd,
No.4 (oåtober 1967), PP'636-644'
rrThe Paradigms of Programnlngrr' A.C.M., Vol.
t46l R.I'f.floyd,
22, Ño.8 (AugusE lg79), PP'455-460'
-
Corurunlcatlon with Subprograt"'i- cãtt' ¡"ð'r"r' ' Vol'20' No'8 (August
t47]N.Francez,,lAnotherAdvanEageofKeywordNotattonforParameEer
Ig77), PP.604-605'
t'Language Design to Enhance Programming Re-
J.D'Gannon¡
t48l CSne-aZ, Computer SY-s-t-ems Research
nepoit
GrouPr
liability'r, Technlcal f975)'
UnlversiÈY of ToronÈo' Toronto, Ontario (JanuarY

"Simplifled Coroutlne Sy stem


--isrrpírri.¿- - SYstern Su rvey and
t49l W.M'Gentleman, coroutlne systern) Technlcal Note No. 3,
user's l"fanual,,, Science' llnlversltY of tr'Iaterloo'
oãpa. of Applied Laiysrs and Computer
llaierloo, Ontarlo, Canada'
Coroutine System - The Translatortr'
t50l $I.M.GenÈleman,'rPortable Note No.4, DePÈ' of APPlied
(Portable Coroutlne SysÈern) Technlcal of WaEerloo, l^laLerloo '
À"áfy"i" and Computer Science' Unlverslty
Ontarlo, Canada'
tt, InformaÈion Pro-
1] I^I.M.Gentleman, 'rÀ Portable Coroutlne (North Holland ?ub' Co''
SYsEem
[5
cessins 7 L, C'V'Frelman (Ed. ), PP '4L9-424
Amsterdam, I972) '
ItAdding a Modern Control Structure to
t'I.K.Gilol and R'Hof fmann' Pro . APL
1521 er pp. r89-194
APL *tato,rt Changing the SYntax"'
6

(4.C.M., New York, 1976)'

232
rrExtens l-ble Pattern Matching in SNOBOL4|" Proc.
t53l R.E.Griswold' f975)'
A.C.M. An I e r9 5 Pp -2 48-252 (L.C.M., New York,
t'St rlng AnalYsis and Synthesis 1n SL5'r, Pr-qg:-
ts 4l
R.E.GrLswold'
A.C.U. Annual Conference r976, pp.4
l0-4 14 (A.C.l"f ., New York, L976)'

Èo SILrr' f twar Port 111


t551 R.E.Grlswold, 'rAn Alternatlve
p..l.iror¡n (Ed' ) r PP '2gl-298 (Carnbrldge unlvers lEy Press, Carnbridge,
1977 )

D. R.Hanson,
trAn Overvíer¿ of sl,srr, À. c.M.
t56l R.E.Grlswold and (Aprll 1977)¡ PP'40-50'
SIGPLAN Notlces, Vol'I2' No 4

"Language Facíl1t1-e s for


Prograrnr
t57l R.E.Griswold and D'R .Hansonr
osirtm on Ar tific ial Inte 1li ence
and
mable Backtracking", Proc. Vol.12, No. 8 (AugusÈ
. C.M. SIG PLAN NO ES
T News ter No.64 (August 1977)>, pp.94-99.

[58] R.E.Grlswold' I D.R.Hanson and J . T.Korb, trTtte Icon ?rogrammlng


NoEices, Vol.14, l{o.4 (APr1l
Language: An Overvlewr t A.C .M. SIGPLAN
L979) ¡ pP. lB-31"

"A View of Coroutlnesrr' A'C'M'


SIGPLAN NotLces-'
159l D'Grune,
vor.izr No.7 (July L977), pp'75-81'
t60l D.R.Hanson, 'rA Slmple Variant of the Bo undarY-tag Algorithm for
Coroutine Envl-ronments'r' In t P ESS
the Allocatlon of (January L976)' PP'109-112'
iã.."r", vol.4, No'4
ItA Pro cedure Mechanism for BackÈrack ?rogrammingtt,
t61l D.R.Hanson'
I 76 pp.40 1-405 (4.C.M., New York'
Pro .4. .M. nual Confe
1976 ) .

162l D.R.Hanson and R.E.Griswold' 'rTLre SL5 Procedure llechanlsmrr'


Comm. A. C.M. , Vo1.21, No.5
(MaY 1978)' pp.392-400.
rrPosit ional versus KeYword Parameter Commtrni-
t63l I{.T.Hardgrave, . C.M. SIGPLAN NO lces Vo1.11, No.5
catlon in Programml-ng Languages
(May 1976), PP.52-58'
r'An ExperÍmenE in SEructured Pro-
t64l P.Ilenderson and R.Snowdon,
gramming", LI.!:, Vol' 12 (L972), PP.3B-53'
on of the Control a nd Envl-ronmen!
t65l R.G.HerrloE, The Definlti
u s Ph.D. Thesis, DePartrnen t
of ComPuter
SËru re of Pr a Madison, lllsconstn (1 97 1).
Sci ence' The Universl ty of i{lsconsln'
t'AJl Axiomatlc Basis f or Computer Programrningtr,
t66l C.A.R.IIoare,
Comm . A.C.M. , Vo1.12, n..io
(october 1969), PP'576-581'583'
Language Deslgntt' Stanford
t67] C.A.R.Hoare, "Hlnts on Prograrnmlng Report
A.I. Lab. Memo {also: Cómputer Science Department (October
^fi'4-224
STAN-CS-73-403)rstanfordUniverslty'stanford'Call-fornla
1973).

233
rrRecurslve Data Structurestr, Int. J. of Comp. and
t68l C.A.R.Hoare' 105-132'
Inf. Sciences, Vo1'4, No.2 (L975 ), PP'
I'An Axl-omal-1c Definition of Ehe
t69l C.A'R'Hoare and N.llirth,
Acta InformatlcA, Vol'2 (L973)' pp.335-
Programming Language Pascal",
355.

t7O]J.D.IchblahandS.?.l"forse,''GeneralConceptsoftheSimula6T
Progranming Language",
Part I (L972), PP'65-93'
Prl- 1es Pro am De {A.P.I.C. Studles in
t71l M.A.Jackson, Londonr ).
Data Processlng, No'1 2> (Academic Press'
19 7s

A.C.M.
l72t T.Jacobsen, "Another Vtew of Coroutlnes'r'
SIGPLAN

Uotries, Vol.13, No'4 (Apri! 1978)' PP'68-75'


hemat 1 t of
t73l R.Janickl, "Ve ctors of Coroutinestt, Notes in ComPuter
uter ience I976 A.Mazurkl ewj-cz (Ed' ) cture
Sclence, Vol. 45), pp.37 7 -384 (Sprínger-Verlag' Berlln, L976).

rrVecEor sofCoroutlnesoveÌ.BllkleNets'r'Fundamen-
174l R.Janlckl,
ls of ut on l"f.Karpinskl (Ed. ) {Lecture Notes in Computer
Sclence, Vol.56)' PP' r13-11 9 (Sprineer-Verlag,
Berlln, L977)'
Pas Us la Re or Lecture
U 5I K. Jensen and N 'I^Itrth '
Not,es in ComPuter ScÍence, Vol . lB (Springer-Ver
lag' Berlin, 1974).

t76l C.I^l.Johnsonr "The Run-Tlme Structure of sLmula 6T"' Technical


Australlan National
Report TR-cs-77-0ir' cornputer science Department, (February 1977)'
universlty, canberra, Australian capital Territory
ttReferences and/or EfflciencY ln High-Level
Í77I C .W. Johnson
' Compu ter Conference (1978) ' YoL.Z'
Languagestt, Proc. Eiehth Aust rallan
pp .7 7 2-7 88.

Contour Model of Block Structured


I7B] J. B . Johns ton ' "The Languages t
Processestt, Proc. Svmposium on Data St ructures in Prosramml .2
J.T.Tou and P.I^legner (Eds.) A. C. SIGPLAN lces Vol.6 , No

(February 1971) ), PP'55-82'


"The Narrowing Gap Between
A. K. Jones ,
Language SYstems and
Í79I lon Proc i B.Gilchrisr (Ed. ),
Op erating SY s tems'r ,Inf o 7

pp.869-873 (North-Ho lland Pub. Co., Ams terdam , 1977 ) '


ExEel"l9-tt for Expressing
tB0I A. K.Jones and B.H.Llskov, "A Languagevol'21' No'5 (Þfay 1978)'
Cons tralnts on Data Access", coq,tr--alc'ú',
pp .35 8-367 .
of
t81l N.D.Jones and S.S.Muchnick, "TEMPO: A Unified Treatment
Langauges"'
Blnding Tlne and Parameter fassrng óo""tpt"
voi'66
1n Programming
(Sprtnger-Verlag' Berlln'
Lecture Notes in Computer scienJe,
1978).

234
and D.MacQueen, rrCorout ines and Networks of Parallel
tBz¡ G.Kahn (Ed')r
Processes It , Inf lon Proces 1 77 Ì.Gllchrlst PP'993-998
(North Ho tland Pub. Co., Amster dam,1977>
Programs'', Technlcal
I83l R.B.Kleburtz, ',SÈeps Toward Verif iabIe
ReportNo.12,Dept.ofComputerScience,sEaEeUniversityofNewYorkat
Stàny Brook, Stony Brook, Ñew York (Noveml¡er L972) '
and TYPes", Proc. Confe
tB4l C.Il.A.Koster' "vlsÍbillty ure
D

Str A.C" SIGPLAN Notl Vol. I I


Abst tlon Def 1n lon
(1976) Special Issuer PP. 179-190.
'
r 1: Tunda
t85I D. E.I(nuth, The Ar of Co uter P Vo
1973).
tal Aleorlthrns (Add lson-WesleY Pub. Co. t Readlng, Massachusetts'
tB6l B.Krleg,
t'A Class of Recurslve Cor ouÈlnes tr, Inf o tion P o-
7 4, .1.í.nosenf eld
(Ed' ) , pp'408-412 (North Holland Pub' Co''
"""*ir',n
Ar"t.td"t' Lgl4).
Proc. Fifth Prince ium
lSTl B.I,I.Lampsonr "Protectionrr, Princeton UnlversitY (March 197 I),
Info tion S ience and S stems tems Vo1.8 , No.1
pp.437 -443{reprinted in A" C.M. er ln el¡I

(January 74), pp.L9-z4l.


19

R'L'london' J.G.Mitchell and


tSBl B.I'I.Lanpson, J'J'Hornlng' Language Eu clidrr, A.C.l"f . SIGPLAN
e..f .ropät, "Repoìt on the Programml-ng
Ño.r".", úor.1â, No.2 (tr'ebruary r977)r PP'L-79'
tB9]R.J.LeBlanc,Jr.,llSpeclflcattonsandRatlonaleforTELoS'a
Language"' Computer
Pascal-based Artlfiáia1 Intelligence Programmlng Department {also:
sciences Technlcal Report No. 30"9, cornputãr sclences
MadlsonAcademicComputlngCenterTechnicalReportNo.49)'The
(Decerober 1977)'
,UnlversiEy of l{lsconsin, Madison' !'Iisconsin
t90]R.J.LeBlanc'PersonalconrnunicaElon(12thl"farchL979>.
I'Coroutl-ne PASCAL: A Case Study in SeParable
l91l M.J.Lemon, Dept' of Computer Sclence'
Contioli', Technical ReporË No' 76'13' (December 1976 ).
University of Pittsburgh, PiÈtsburgh' Pennsylvania
rfControl Separation in
t92l M.J.Lemon, G.Lindstr om and M.L.Soffa,
ll A.C.M. An lCo 1 77 pp .4 96-50 l-
Prograrnmlng Languages Pr
(4.C.M., New York, L97 7).
rrOPeratlng System Structures to Support SecuritY
t93l T.A.Linden, No.4 (December L976) '
and Reliable Software", Comout lns SurveYs , Vol.8,
pp.409-445.

t94]G.Llndstrom,,,EfflciencyinNondeterminísticConÈrolthrough
Department
Non-forgetfur ¡acttrácking", Technical Report No'UUCS-77'LL4'
ofComputerSclence,Universl-tyofUtah,saltLakeCity'Utah(October
1977 ) .

235
rrControl Structure Aptness: A Case Study using
t95l G.LlndsËrom
ce on So f tv¡are
Top-down Parsing", Proc. Thfrd Internatlonal Conferen
Engineerlng, PP.5-12 (r.E.E.E., L97 8).
tfBacktrackl-ng in a Generalized Control Settlngrr,
t96l G.Lindstrom' sandS sÈems Vol.1, No.1 (JulY
A.C.M. Tr onP amml La
L979)¡ pP.B-26.
f971 B.Llskov' A. Snyder ' R.At klnson and
C.Schaffert, rrAbstracÈion
Mechanlsns ln CLUrf, Co À.C.l"f .. Vo1.20, No.8 (August L977), pp'564-
576.
TechnJ.ques for Data
t98l B.H.Liskov and S.N.Zlllesr "SPecification Rel iable Software L975
AbsÈractlonsrr ¡ Proc. InternaE ional Conference on
A.C .M. SIGPLAN Not Vol. 10 ' No. 6 (June 1975 ) ), pp.7 2-87 (a lso :
I.E.E.E. Trans. Sof r¡tare En neeri Vol. SE- 1, No. I (March L97s),
pp.7-19).
tices,
t99l E.Lynning, letter to the Edltor' A.C.M. SIGPLAN No

vof.i3, No.2 (February 1978), Pp'L2-L4'


rrAn Experiment \tl-th the Ext ensibllity of SÍmula'r,
tt00I C.D.Marlln
A.C .ll. SIGPLAN Noti Vo1.l1, No.l I (Novernber 197 6), pp.50-57.
t 10 D.l'farlln ' "A Model f or Data Control in the Programmlng
1l C.
Language Pascal'r, Proc. Au stralia n Colle ges(Ed. of Advanced Education
) r PP.293'306 (SouÈh
Computing Conference' August 1977, A.K.Duncan
Australian InsÈltute of Technology, Adelaide, Sou th Australla,
L977).

rrlhe Des lgn of Ehe Sequence Control Aspect of a


t1021 C.D.Marlln, Languagett, Proc. Eiehth
Coroutlne Facl-litY for a Proced ural Progra mmingpp.L267
Aus lian Eer nferen (1978)' Vol.3' -L292 (Australlan
. Computer SocletY Inc' t 1978 ) .
I'coroutines and Return Addressestt, letter to the
t1031 c.D.Marlin,
Editor, A.C.M. SIGPLAN l{otlces, Vol' 13, No'9 (Septernber 1978)r PP'19'20'
I'A Heap-based ImPlemenEation of the Programmíng
t1041 C.D.Marlin, Exoerlence' Vo1.9, No.2
Language Pascaltt, So f Ër.rar e-Pra ctlce a
(February 1979), pP .101-119.

tl05lJ.R.McGrawrt'LanguageFeaÈuresforProcesslnteractionand
Department of Computer
Accå"" ConËrol'r, Technlcal Report No'77-319'-
York (August 1977)'
Science, Cornell UniversiÈy, Ithaca, New

,,coroutlnes", unpubllshed memo' Bell Telephone


t1061 M.D.Mcllroy,
Laboratories, Murr"y ttitt, New Jersey (May 1968)'
"The 2.PAK Language: Primitíves for A'I'
t1071 L.F.Melli, of computer science'
appir""lrons,,, Technical Report No. 73, Department
UniversiÈyofTorontorTorontorOntario'Canada(DecernbetL9T4)'
tl08l L.F.Melli, "The 2'PAK La nguage: Goals and Descriptionrr, Proc.
urth I ternâEi 1Jo tCo rence Art ficial Intell
( Tbilisi U. S. S.R. e SePEember 1975 ), pp .5 49-555.
'

236
[109] R.M1lne and C ' StracheY,
trA Theory of Prograrnmfng Language
SemanÈlcs" (Chapman and Hall, London, I97 6> .
ttSchemes: À High Level Data SÈruc-
t f 10 IMltchell- and B 'Iüegbreit '
J. G.
turing Concept'r, Report No' CSL-77-l' Xerox Palo Alto Research
CenÈer'
palo Ãlto, Californla (January 1977)'
rrThe Sp eciflcatlon of Prograu Flow in
t1 lf l J.B.Morrls and M'B'I^Iells, B.l'f .LeavenworEh
Madca P 6",
972)>, pp.2B-35.
(Ed. ) A.C.

tIl2l P.Naur (Ed.), "Revlsed Report on Lhe AlgorlÈhmic Language Algol


60tt, A.C.M. , Vol.6, No.1 (JanuarY 1963), PP'1-17'
|rAn Introduct'ion to Inf ormation
tr 13] A. Nev¡ell and F .M. Tonge,
processl-ng Languagê V", The RANõ Corporation Paper P-L929^-{presented at
the A.c.M. ttationãl conference, BosCon, Massachusetts' 1959) (The RAND
Corporation, SanÈa Monica, Californla, 1960)'
SIGPLAN Notices, Vol. 12,
t1141 J.G.Noel, letter to the Editor' A.C.M.
Nô.12 (December 1977), P.23'
tl15lK.V.Nori,U'Ammann,K'Jensen'H'H'NageliandCh'Ja.cobl'rrThe
pascal<P> Compller: Implementatlon Notes (Revised Editlon)", Berichte
Hoehschule'
Nr. 10, Institut fllr Iìformatlk, Eidgen6ssische TechnÍsche
Ztlrich (JulY 1976).
erS s Or lzaE The 85 00 00
t1161 E.I.Organick' Co
Series (Academic Press, tondon, 1973).
t117]J.Palrne,l|ProcectedProgramModulesinSlmuLa6T'|,FoAPReport
c 8372-yß(E5), Swedish NaÈ1onal Defense Research Institute, sÈockholm'
"Sweden (Ju1y L973).
r,securtty and Prograrnml-ng Languagestt, FOA P Report c
t11g] J. palme,
8395-M3(E5), Swedish Natlonal Defense Research InstiEute,
stockholm
(April I974>.

[119] D .L.Parnas,Technlque for SofEware Module SpeclflcaElon r¡lth


ttA
Examples", Conm. A.C.M. Vo1.li, No.5 (May 1972), pp'330-336'

t120]D.L.Parnas,'lontheCrl-terlatobeUsedinDecomposlngSystens
l_nto Modules,,, _co*n:_ ¿_.c_.r't:, vol.15, No.12 (Dec. L972) I PP'I053-1058'

11211 T.W.PratE'
es: Desisn and rmp le.mentaEion
Pro arnmlng La
(Prentlce-Hall Inc. ' Englewood Cliffs,
New Jersey I975).
'
es of ECLtt, Proc.
lL22) C.J.Prenner, "The ConÈrol Structure Facillti s.A.schuman (Ed. )
Intern â, tional Svmoosium on ExÈ ens ib 1e LanquaPes.1) pp.104-112.
A.C .M. SIGPLAN Notíce , Vol.6, No.l2 (December 197 ) r

t 1231 P.A.Prltchard, 'rA Proof Rule for MultlPle CorouElne SYstems'r,


Info tion Processi ers Vol.4 No.6 (March 1976)r PP'141-143'
'

237
tL24]P.A.Prltchard,''onemantlcCharacterlsaÈlonofSome , M'C'Neweyt
AdVanced Control Structurestt, ian National
R.B. Stanton and G.L.i^Iolf endal
unlverslty press, canberra, Australtan capltal rerrlEory' 1978).
I'Semantlcs and Proof Rules for Coroutlne Hierarchles
lL25l P.Raulefs, Mat hematlcal FoundationC --S-!
in Block-Structured Progr arnming Languagestt, Notes 1n ComPuter
ut Scienc r977 J.Gruska (Ed. ) {Lecture
Scl-ence, Vol.5 3), PP. 45 L-459 (Springer-Verlag, Ber 1in,
L977).

I'SAILrr, Stanf ord A'I' Lab' Memo AIM-289


1126l J.F.Relser (Ed. ),
{also: ComPuter Science Department RePort STÀN-CS-76-574> ' Stanford
Universlty, SËanford, Call-fornla (August L976)'

lI27]J.C.Reynolds,''GEDANKEN-AsimpleTypelessLanguageBasedon A'c'M.,
the Princlple of completeness and the Reference concêPttt, comm'
Vol.I3, No.5 (May 1970), pp'308-319'
tl28l M.Richards ' "BCPL: A Tool f or CornPller I,Irlting and SYstem
1969 {A.F.I.P.S.
Prograrn-ningt', Proc. Sprins Joi nt Comouter Conference
Conf ence P eedin , Vo1.34), pp.557-5 66 (A.F.I.P.S. Press, Montva Iet
New JerseY, l9 6g).
ttPerformance of
ll29i G.D.Rlpley, R.E.Griswold and D.R'Hanson, i!, I.E.E.E . Trans. on
Storage l'fanagement in an Implenentation of SN0BOL .130-137.
Software Engineering' Vol.SE-A, No-2 (March 1978), PP

t1301 J.Sajaniemi, "The Safety of a Coroutine


Syst êIDtt, Automata '
LanÄuaeås and-Programming, A'Salomaa and M'Stelnby
(Eds') {Lecture Notes
L'52)r PP '440-452 (SPringer-V erlag, Berll-n'
L977'.) .

t13rlA.H.J.Sale,"867OO/TT00PASCALReferenceManual-Compi-lerVer-of
slon II.8.002", Deiartment of InformatÍon Sclence, The Unlverslty
Tasmanla, Hobart, Tasmanl¿ (July L977)'
is Us es Co nes M. S. thesis,
f32l S.E.Sevclk' An
t
North Carolina at Chapel
DepartruenE of ComPu ter Science, UniversltY of
H111, Chapel llill, North Car ollna (1976).
I'A SCRABBLE Crossword Gaure Playlng
t1331 S.C.Shaplro and II.R.Surlth, Science' StaEe
Program", Technical Report 119, Department of CompuEer (March 1977)'
Universlry of New York ãt Buffaio, Buffalo, New York
and verif ication
11341 M. Shaw, t{.À.tlulf and R.L.London, "AbstracEion
in Alphard: Deflning and Specifylng lteratl-on and GeneraËors", Comm'

À.c.f"r.', Vol.20, No.8 (¿\ugust I977), PP'553-564'


Proc. American
t13sl H.À.Simonr "The Archl-tecture of ComplexitY'r,pp.467-482.
PhÍ os op hlcal Societv, Vol.l06, No'6 (December L962),
rfThe Detach and call Statements'r'
11361 Simula Development Group,
Recommendatlon No. 2 (Septenbet L977)'

238
rrCoroutlnes fn FORTRANTT,
Ir3il Skordalakis and G.Papakonstantlnou'
E.
A.C.M. S No t lces Vol.l3, No.9 (SePtember 1978), pP.76-84.
rrAnalytlc-al Properties of General-
tl3Sl M.L.soffa and G.Lindstrom, No. 76-L0, Department of CompuÈer
fr.å Cotoutlnes", Technical Report Pennsylvania (March
Science, Unlversicy of Pittsúurgh, PitEsburgh'
L977 ) .
ttA Formal AnalYsis of Name Accessing 1n Programming
t1391 C.L.Srnith'
Languages'r , Ph. D. Dissertation, Iowa State UnÍversltY, Ames, Iowa
(1975).
Memo AIM-290 {also:
t1401 N.I^I.Smith, 'TSAIL Tutorialr', A'I' Lab' UnlversitY'
Computer Sclence Department RePort STAN-CS-76-575)' Stanford
Stanford, Californla (October I976)'
t{.SÈallings, "An Appllcatlon of CorouËlnes and Backtracking
11411 on
Ln
Interactive SYstems", lnt. J. of ter and Informati Sclences.
Vol.5, No.4 (December L976), pp.303-313.
in Comouter
Í142J D.F.Stanat and D'F' IfcAllister, Discrete ì,IathemaÈicsr977).
Sciencã (Prentlce-Hall Inc', Englewood Cliffs, New JerseY,

t1431 R.B.Stantonr "Programnl ng Languages Matterrr, Proc. Seventh


(Australian
Au ralian uter er (I976), Vo1.3, PP.85- 111
Computer SocietY Inc., 1976).

t1441 H. S. Stone and D.P. Siewiorek,


Ors.anLzat ion and D ata Struc tures: PDP-Il Ed
New York' 1975).
to CONNIVER ' À
t1451 G.J.Sussman and D.V.McDermott, "From PLANNER L972 {A.F.I.P.S.
-Genetic Approach", Proc Fa11 Jolnt ComPu ter Conference (A.F'I'P' S.
Conference Proceedings, Vo1'4 1) ' Part II, pp.1171-1179
f r*"s, f"fonEvale, New Jersey, 1972) '

146I I^1. Teltelman ' INTERLISP Reference Manual (Xerox Palo Alto
Re-
t
search CenÈer, Palo Al to, Californla, L975 ).
GeneralizaElon of caltt,
tl4Tl R.D.Tennentr "PASQUAL: A Proposed Pas
0ntario
Technlcal Report No.75-32, Queen's UniverslÈy' Kingston'
(February 1975).
S.Zelgler, ttDeslgn Ratlonale
t1481 L.Travis, I'l.Ilonda, R'LeBlanc and Ar tlf 1al
for TELOS, a Pascal-based A'I' Language t
il Proc. osl
. C.M. Vo1. I 2'
In tell-ieence and P roqrammi nq Languages SIGPLAN S

No.B (August L917) and A.C.M. SIGART Newsletter' No.64 (August L977 ) ),
pp.67'76.

t1491 L.I.Vanekr "Hierarchical Coroutines: A Mechanism


for Improved
Research
Program Structure'r, Technlcal Report No'99, Conputer SYst.ems
Croup, Unlversity of Toronto, ToronEo, Ontarlo (February L979).

239
t1501 A.van B.J.Mallloux, J.E.L.Peck, C'H'A'Koster,
Wl-Jngaarden'
M.Sintzoff, C.H.LlndseY, L' G.L.T.Meertens and R.G.Fisker (Eds.),
rrRevlsed ReporÈ on Èhe AJ-gorl- throlc Language ALGOL 68", A. C.M. SIGPLAN
Notlces, Vol.12' No .5 (May 197 7 ) ' pp.t-70 (also: Acta Informatica' Vo1.5
(1975), pP.t-236).
rrEuclid and Pascal", A'C'M'
t1511 T.Venema and J.des Rivieres,
SIGPLAN Notices Vo1.13, No.3 (l"farch 1978), PP'57-69'
l|Coroutlne Sequencing in a Block
ÍI52,J À.I^Iang and 0..J. Dahl,
StrucÈured Envlronmenttr, B.I.T., Vol.11 (1971), pp.425-449'
31 S . K. l{arren ' The Co routine Mo 1 of Attrl te Grammar Evalu-
t 15
ation, Ph.D. thesls, Rlce UnlversiEY, llouston' Texas (Apr11 1976).
11541 D.A.I,Iatt, "An Extended Attribute Grammar
for Pascaltt, A.C.M.
SIG PLAN Notlces Vol.14, No.2 (February I97 9), pp.60-74.

t155l P.I{egner, "Data Structure I'fodels for P rogramming Languagestt,


J. T. To u an<l
oc. um on Dat S rucLures nPr La s
P.Wegner (Eds.) A.C.I'I" SIGPLAN NOÈi Vol.6, No.2 (FebruarY f971) )
pp. 1-54.
rrAmblguities and In-
t1561 J.I,Ielsh, W.J. Sneeringer and C 'A'R'Itroare'
securitles in Pascalrt, Sof t Prac e and ience Vol.7 , No.6
(November-December L977 ), PP'685-696'
t1571T.R.Wilcox, "ASPEN Language Speclficatlonsrr' A. C.M. SIGPLAN
NotÍces, Vo1.12, No.ll (November L977), pp'70-87'
formatfca.
t15Bl N.Wlrth, "Ttre Programrning Language Pascal", Acta In
Vo1. 1, Fase. I ( 197 1) , PP.35-63'

t1591 N.l,lirth, "Program DevelopmenÈ by Stepwfse


Ref lnementrr, Comm.

A.C.M. Vol.14, No.4 (April 197f ) r PP'22I-227 '


'
t1601 .Wirth, rrThe Programml-ng Language Pas cal and íts(Infotech
N
Deslgn
Crf terlarr, Infotech S tate of th e Art Re f') or r No. 7. pp.453'473
InformaË1on Ltd., Maldenhead, England, L97 2) .

t16ll N.Wlrth' Svst t1c Pros anmt_nø Än IntroducÈion (Prentice-


Ha1I Inc., Englewood Cllffs, New Jersey, r973).
tton the Design of Programmlng Languages", InformaEion
Í162) N.I^lirth,
Processl-ns,74,J.l,.Rosenfeld(Ed'),pp'386-393(NorthHollandPub'Co"
Amsterdam, L974).

t1631 N.Wlrth, "Progr amming Languages: What to Demand and Ho w to As-


sess Themtt, Sof trvar En eer R.H.Perrot (Ed.){A.P.I.C. SË udles in
Data Processl-ng, No. l4), PP'155- L73 (Acadenlc Press, London, L977)'
rrAn Introduction to the
11641 I.I.A.l^lulf , R. L.London and M. Shaw,
ConsEructlon and Verl ficatlon of AlPhard Programs", I.E.E.E. Trans. on
Sof tware Ensirreerlnq. Vol.SB-2, No.2 (Deceuber L976)¡ PP'253-265'

240
t1651 f{.I{ulf , D.B.Russel-l and A.N.Ilabermann, I'BLISS: A Language for
Systems Programmingrt, Qemm. A.C.l'{.. Vo1.14 t No. I 2 (December I97 l) ,
pp .780-790.

t1661 I{.Ì{ulf and M.Shaw, I'Global Variable ConsLdered Harnful", A.C.M.


SIGPLAN Notfces, Vol.8, No.2 (February Lg73), pp.28-34.
t1671 M.V.Zelkowltz and H,J.Larsenr ttlmplemenÈat,1on of a Capabllity-
Based Data AbstracEiontr, I.E.E.E. Tyans. oo Software Ensineer I no^
Vol.SE-4, No.1 (January L97 8 ), pp .56-64.

24L

You might also like