Universita degli Studi di Torino
Dipartimento di Informatica
C.so Svizzera,185  10149 Torino,Italia
DOTTORATO DI RICERCA IN INFORMATICA (Ciclo XVII)
PhD thesis
Types for objectoriented and
functional programming languages
Silvia Likavec
THESIS DIRECTORS:
Prof.Viviana Bono
Prof.Pierre Lescanne
PhD COORDINATOR:
Prof.Pietro Torasso
2001  2004
2
Contents
Abstract vii
Acknowledgements ix
Summary xi
Riassunto xvii
R´esum´e xxiii
I Introduction 1
1 Introduction 3
1.1 Type systems for programming languages.............3
1.1.1 Introduction.........................3
1.1.2 Formalizing a typed programming language........5
1.2 Objectoriented programming...................7
1.2.1 Basic concepts.......................7
1.2.2 Typing objectoriented languages.............8
1.2.3 Classbased vs.objectbased languages..........9
1.3 Basic domain theory........................10
1.4 Basic category theory........................11
1.5 Overview of the thesis.......................13
II Core calculus of classes and mixins and extensions 15
2 Mixins in programming languages 19
i
ii
CONTENTS
2.1 Introduction.............................19
2.1.1 What is a mixin?......................19
2.1.2 Examples..........................20
2.2 Literature on mixins.........................22
3 Core calculus of classes and mixins 27
3.1 Overview..............................27
3.2 Motivating the design........................28
3.3 Core calculus in more details....................29
3.4 Extending the core calculus.....................31
4 Adding higherorder mixins 33
4.1 Introduction.............................33
4.2 Syntax of the calculus........................34
4.3 Operational semantics........................38
4.3.1 Reduction rules for standard and heap expressions....39
4.3.2 Reduction rules for class and mixin related forms.....40
4.3.3 Reduction rule for mixin composition...........43
4.4 Type system.............................46
4.4.1 Types............................46
4.4.2 Subtyping rules.......................48
4.4.3 Typing rules for standard and heap expressions......49
4.4.4 Typing rules for class and mixin related forms.......49
4.4.5 Typing rule for mixin composition.............52
4.5 Properties of the system.......................53
4.5.1 Preliminary properties...................54
4.5.2 Subject reduction......................60
4.5.3 Soundness.........................73
4.6 An example of mixin inheritance..................80
5 Adding incomplete objects 85
5.1 Introduction.............................85
5.2 Syntax of the calculus........................87
5.3 Operational semantics........................90
5.3.1 Reduction rules for objectoriented forms.........91
5.3.2 Reduction rules for incomplete objects...........95
5.4 Type system.............................97
5.4.1 Types............................97
CONTENTS
iii
5.4.2 Typing rules for class related forms............98
5.4.3 Typing rules for mixin related forms............99
5.4.4 Typing rules for incomplete objects............101
5.5 Allowing method invocation on incomplete objects........103
5.6 Properties of the system.......................104
5.6.1 Preliminary properties...................104
5.6.2 Subject reduction......................105
5.6.3 Soundness.........................119
5.7 Examples..............................122
5.7.1 Object completion via method addition..........123
5.7.2 Object completion by object composition.........125
6 Width subtyping for incomplete objects 129
6.1 Introduction.............................129
6.2 Syntax and operational semantics..................131
6.2.1 An example of reduction..................132
6.3 Type system.............................134
6.4 A more exible solution......................136
6.4.1 Remarks..........................138
6.5 Properties of the system.......................139
6.5.1 Subject reduction......................139
7 Final remarks 145
7.1 Conclusions.............................145
7.1.1 Mixin calculus supporting higherorder mixins......145
7.1.2 Mixin calculus with incomplete objects..........145
7.1.3 Incomplete objects with width subtyping.........146
7.2 Related work  comparison.....................146
7.2.1 Mixin calculi........................146
7.2.2 Calculi with incomplete objects..............149
7.3 Future research directions......................149
III Understanding
λµµ calculus and Gemini 151
8 Introduction to
λµµ calculus and Gemini 155
8.1 Intuition and syntax.........................155
8.2 Reduction rules...........................157
iv
CONTENTS
8.3 Two conuent subcalculi......................158
8.4 Type assignment systemfor
λµµ..................159
8.5 Related systems...........................160
8.5.1 λµ calculus.........................160
8.5.2 λC calculus.........................161
9 Conuence of Gemini 163
9.1 Introduction.............................163
9.2 Parallel reduction for Gemini
n
...................164
9.3 Conuence of Gemini
n
.......................169
9.4 Parallel reduction and conuence for Gemini
v
...........171
10 Semantics of Gemini 175
10.1 Continuation semantics.......................175
10.1.1 Introduction.........................175
10.1.2 Category of continuations.................176
10.1.3 Category of negated domains................177
10.1.4 Fromordinary models to continuation models.......179
10.2 Semantics of Gemini
n
.......................181
10.3 Kleisli category and continuation semantics............189
10.3.1 Kleisli category.......................189
10.3.2 Kleisli triple of continuations...............190
10.4 Semantics of Gemini
v
.......................191
10.5 Improving the semantics of Gemini
n
................197
11 Final remarks 203
11.1 Conclusions.............................203
11.2 Future research directions......................203
IV Using intersection types to characterise the behaviour of
lambda terms 205
12 Behavioural inverse limit λmodels 207
12.1 Introduction.............................207
12.2 Inverse limit λmodels and intersection types...........209
12.2.1 Stone duality........................209
12.2.2 Inverse limit λmodels...................210
CONTENTS
v
12.2.3 Step functions.......................211
12.3 The models.............................212
12.3.1 Reminder on λcalculus..................212
12.3.2 Normalisation,persistent normalisation,and closable prop
erties............................212
12.3.3 Relationships between sets of terms............214
12.3.4 Functional behaviour of terms...............216
12.3.5 Denition of models....................217
12.3.6 Main theorem,version I..................218
12.4 Types and lter models.......................219
12.4.1 Pretypes and types.....................219
12.4.2 Filter models........................222
12.5 The type assignment systems....................225
12.5.1 The type assignment systems and examples of derivations 225
12.5.2 Main theorem,version II..................229
12.6 Persistently normalising terms...................231
12.6.1 Safe and unsafe subterms..................231
12.6.2 Characterisation of PN..................232
12.7 Reducibility method.........................234
12.7.1 Reducibility method....................234
12.7.2 Soundness.........................236
12.8 Conclusion.............................238
vi
CONTENTS
Abstract
This thesis consists of three parts.
The rst part presents three extensions of the core calculus of classes and mix
ins.The rst extension is a proposal for a programming langu age equipped with
higherorder mixins,which enable the construction of sophisticated class hierar
chies.In the second extension mixins are seen as incomplete classes,and accord
ingly,their instances are seen as incomplete objects that could be completed in
an objectbased fashion via method addition and object composition.In the third
extension,width subtyping on (complete) object types is added to the calculus of
mixins and incomplete objects.
The second part studies the untyped
λµµ calculus called Gemini.The con
uence of Gemini
n
and Gemini
v
,two wellbehaved subcalculi of Gemini,closed
under callbyname and callbyvalue reduction respectively,is proved.Moreover,
the interpretation of Gemini
n
in the category of negated domains,and the interpre
tation of Gemini
v
in the Kleisli category is given.To the best of our knowledge,
this is the rst interpretation of untyped
λµµ calculus.
In the third part,two inverse limit λmodels are constructed,which completely
characterise the sets of terms with similar computational behaviours:the sets
of normalising,head normalising,weak head normalising λterms,those corre
sponding to the persistent versions of these notions,and the sets of closable,clos
able normalising,and closable head normalising λterms.
vii
viii
Abstract
Acknowledgements
Many people believed that I would be writing these lines after all.I warmly thank:
✁✄ My supervisors Viviana Bono and Pierre Lescanne for sharing their knowl
edge with me and for dedicating their time and patience to the development
of this thesis.Without their help and encouragement it would be much
harder to come to the end of this path.
Mariangiola Dezani for her valuable support and advice during these three
years of my PhD.
♦ Silvia Ghilezan for suggesting Torino as a place for doing my PhD,and for
providing constant encouragement and constructive criticismduring all this
time.
Lorenzo Bettini for being a dynamic and practically oriented coauthor.
Ugo de'Liguoro for numerous discussions we had on metaphys ics.
The whole λ group at Dipartimento di Informatica in Torino for being a
stimulating working environment.
Michele Bugliesi,Dan Dougherty,Susan Eisenbach,and Hugo Herbelin
for accepting to be the referees for my thesis.Steffen van Bakel,Pierre
Louis Curien,Ren´e David,Sophia Drossopoulou,Paola Gannini,and Ugo
de'Liguoro for giving their availability to substitute some of the referees in
case of necessity.
My mum,dad,and Danka for their love and support,and for boldly believ
ing in me for more than 30 years.
♥ Chris for successfully fooling the kilometres with me,always being an end
less source of love,comfort,and motivation.
ix
x
Acknowledgements
♣ Ale,Andris,Bobo,Cri,Elaine,Fabri,Gigi,Iva,Loca,and Vivi for their
friendship and presence that made my days in Torino colorful and unforget
table.Bobo and Fabri for infecting me with tango.Marcello for taking me
to the rst party in Torino.
♠ Daniela,Duda,Gaga,Goca,Ivana,Jovana,Livija,Natasa,Tanja,and Zoran
for their constant friendship that I would never stop counting on and for
sharing many joyful and critical moments with me.Ivana and Tanja for
their help in resolving all the bits and pieces that were in the way.
Antonietta Pontieri for her patience in helping me to ght th e bureaucracy.
Daniel,Dragisa,Etienne,Myriam,Pushpinder,and Tom for making my
staying in Lyon much more enjoyable.Tomfor the help with French transla
tions.Sonia for being my companion in many schools,meetings and work
shops.
Treba mi svet
Otvoren za poglede
Otvoren za trcanje
I treba mi soba
Da primi pet hiljada ljudi
Sa dignutimcasama
Sa dignutimcasama
Summary
This thesis was developed as a joint work between Dipartimento di Informat
ica,Universita di Torino,Italy,and Laboratoire de l'Informatique du Par all´elisme
(LIP),
´
Ecole Normale Sup´erieure de Lyon,France.
The thesis is divided into three parts.The rst part,superv ised by Prof.Vi
viana Bono,is a proposal for the design of a mixinbased calculus that accommo
dates incomplete objects and higherorder mixins.The second part is developed
under the supervision of Prof.Pierre Lescanne,and it investigates some properties
of two subcalculi of untyped
λµµ calculus of Curien and Herbelin [CH00].The
third part,written in collaboration with Prof.Mariangiola Dezani and Prof.Silvia
Ghilezan,presents two inverse limit models for the lambda calculus with intersec
tion types.
Mixin calculus
In objectoriented world,there are two predominant programming paradigms:
classbased and objectbased.Classbased objectoriented languages promote
disciplined programming by enabling construction of solid class hierarchies,while
objectbased languages provide a convenient environment for experimenting with
prototypes,where parts of their implementation might still be missing.
The aim of this work was to give the basis for designing a calculus that com
bines classbased features with objectbased ones,that is,to try to t into one
setting the best of both worlds,discipline and exibilit y rst of all.We propose
two extensions of the Core Calculus of Classes and Mixins of [BP S99],one
with higherorder (composable) mixins,the second one with incomplete objects.
Our approach
Mixins [BC90] are (sub)class denitions parameterized over a superclass and
were introduced as an alternative to some forms of multiple inheritance.A mixin
xi
xii
Summary
can be seen as a function that,given one class as an argument,produces a (sub)class,
by adding and/or overriding certain sets of methods.
Mixins in our calculi have the following form:
mixin
method m
j
= v
j
;
(j∈N)
redeﬁne m
k
= v
k
;
(k∈R)
expect m
i
;
(i∈E)
constructor v
c
;
end
Methods m
j
= v
j
are newly introduced by the mixin,m
k
= v
k
are redening
methods,that will redene the methods with the same names fr omthe superclass,
and m
i
are expected method (names),that must be provided by the superclass.All
the methods are functions of the private
eld
,and of
self
,which will be bound to
the newly created object at instantiation time.In addition,redening methods can
refer to their corresponding superclass implementation via a special keyword
next
.
A mixin type takes into account the types of the methods already present in the
mixin and the expected types of the components not yet present.New subclasses
are created by applying a mixin to a class via a mixin application operation .The
type systemdetermines when a mixin application is possible.
The rst proposed calculus extends the core calculus of clas ses and mixins of
[BPS99] with higherorder mixins.In this extension a mixin can:(i) be applied to
a class to create a fullyedged subclass;( ii) be composed with another mixin to
obtain yet another mixin with more functionalities.In what we believe being quite
a general framework,we give directions for designing a programming language
equipped with higherorder mixins,although our study is not based on any already
existing objectoriented language.
In the second proposed calculus we extend the core calculus of classes and
mixins of [BPS99] with incomplete objects.Since mixins have a exible nature of
incomplete classes prone to be completed according to the programmer's needs,
we decided that the promising starting point for our calculus could be the com
bination of mixinbased inheritance with constructs for manipulating incomplete
objects.In addition to standard class instantiation,it is also possible to instanti
ate mixins thus obtaining incomplete objects.Therefore,an incomplete object is
incomplete in two different respects:( i) it may need some expected methods;
(ii) its redening methods cannot be invoked until methods with the functionality
of their
next
are added.Incomplete objects can be completed in two ways:(i)
Summary
xiii
via method addition,that adds one of the expected methods or one of the miss
ing
next
s;(ii) via object composition,that composes an incomplete object with
a complete one that contains all the required methods.When a method is added,
it becomes an effective component of the host object,meaning that the methods
of the host object may invoke it,but also the new added method can use any of
its sibling methods.The type systemensures that all method additions and object
compositions are type safe and that only complete methods are invoked on ob
jects.This way the type information at the mixin level is fully exploited,obtaining
a tamed and safe objectbased calculus.
In addition to functional,record,and reference types,our type systemhas class
types,mixin types,and object types (both for complete and incomplete objects in
the second extension).
The metatheory of both extensions is studied.In particular,the soundness
property is proved,to guarantee the absence of runtime me ssagenotunderstood
errors.
Gemini calculus
λµµ calculus was introduced by Curien and Herbelin in [CH00],to provide a
CurryHoward correspondence for classical logic.The terms of
λµµ represent
derivations in a sequent calculus proof system and reduction reects the process
of cutelimination.
The untyped version of the calculus can be seen as the foundations of a func
tional programming language with an explicit notion of control.The new termi
nology for the basic syntactic constructs was given in [GL04],which will also be
used in this work.We call this untyped language Gemini.
The basic syntactic entities are given by the following:
v::= x  λx.v  µα.c e::= α  v • e  µx.c c::= v e
where v ranges over the set Caller of callers,e ranges over the set Callee of
callees and c ranges over the set Capsule of capsules.The variables denoted with
Latin letters represent input and the variables denoted with Greek letters denote
continuations.We refer to the terms of Gemini as Gterms.
There are three rules that characterise the reduction in the calculus:
(λ) λx.r r
• e → r[x ←r
] e
(µ) µα.c e → c[α ←e]
(˜µ) r ˜µx.c → c[x ←r]
xiv
Summary
The calculus has a critical pair µα.c
1
µx.c
2
where both,(µ) and (µ) rule can be
applied ambiguously,producing two different results.Hence,the calculus is not
conuent.But if the priority is given to one of the rules,we ob tain two conuent
subcalculi
λµµ
T
and
λµµ
Q
,that are closed under callbyname and callbyvalue
reduction,respectively.
This work investigates some properties of two subcalculi of untyped
λµµ cal
culus of Curien and Herbelin [CH00],called Gemini
n
and Gemini
v
,respectively.
It proves the conuence and then gives domain theoretic mode ls for both versions.
In order to prove the conuence for each of them,we adopt the t echnique
of parallel reductions given by Takahashi in [Tak95].This approach consists of
simultaneously reducing all the redexes existing in a term.First,we dene the
notion of parallel reduction ⇒
n
for Gemini
n
.Then,we show that →→
n
is a reex
ive and transitive closure of ⇒
n
.Therefore,in order to prove the conuence of
→→
n
,it is enough to prove the diamond property for ⇒
n
,which follows from the
stronger Star property for ⇒
n
that we prove.The proof for Gemini
v
is obtained
by a straightforward modication of the proof for Gemini
n
.
When interpreting the calculi that embody a notion of control,it is convenient
to start from continuation semantics,that enables to explicitly refer to continua
tions,which are the semantic constructs that represent evaluation contexts.
Continuation semantics of Gemini
n
is given by the interpretation in the cate
gory of negated domains of [SR98a],whereas Gemini
v
is interpreted in Moggi's
Kleisli category over predomains for the continuation monad [Mog91].Using
computational monads,we also give an improved interpretation for Gemini
n
,in
troducing the new syntactic entity,called covalue.In all the cases the reduction
preserves the denotations.The main point about these domaintheoretic models
is that they cope with untypedness of the calculus by solving a recursive domain
equation.
Using intersection types to characterise the behaviour
of lambda terms
In the simply typed lambda calculus λ
→
,the basic type forming operator is the
arrow →.Among many known extensions of this type assignment system,the
one which characterizes larger class of terms is the extension with intersection
types.The intersection type assignment systemwas introduced in [BCDC83] and
[CDCV80],and is denoted by λ
∩
.In this system,the new typeforming operator
Summary
xv
is introduced,namely the intersection ∩.Consequently,it is possible to assign
two types σ and τ to a certain lambda termat the same time.Another outstanding
feature of this systemis the universal type ω which can be assigned to all lambda
terms.
We construct two inverse limit λmodels which completely characterise sets of
terms with similar computational behaviours:the sets of normalising,head nor
malising,weak head normalising λterms,those corresponding to the persistent
versions of these notions,and the sets of closable,closable normalising,and clos
able head normalising λterms.More precisely,for each of these sets of terms
there is a corresponding element in at least one of the two models,such that a
term belongs to the set if and only if its interpretation (in a suitable environment)
is greater than or equal to that element.We use the nitary lo gical description of
the models,obtained by dening suitable intersection type assignment systems,to
prove this.
xvi
Summary
Riassunto
Questa tesi e stata sviluppata in cotutela tra il Dipartimento di Informatica,Uni
versit
a di Torino,Italia,e il Laboratoire de l'Informatique du Pa rall
´
elisme (LIP),
´
Ecole Normale Sup´erieure de Lyon,Francia.
La tesi e divisa in tre parti.La prima parte,sviluppata sotto la supervisione
della Prof.ssa Viviana Bono,e una proposta per il design di un calcolo basato sul
costrutto di mixin,nel quale vengono modellati una forma di oggetti incom
pleti ed introdotti mixin di ordine superiore.La second a parte e stata sviluppata
sotto la supervisione del Prof.Pierre Lescanne e presenta alcune propriet
a di due
sottocalcoli del
λµµ calcolo non tipato di Curien e Herbelin [CH00].La terza
parte,scritta in collaborazione con la Prof.ssa Mariangiola Dezani e la Prof.ssa
Silvia Ghilezan,presenta due modelli per il lambda calcolo tipato con i tipi inter
sezione.
Mixin calcolo
Nel mondo dei linguaggi orientati agli oggetti,ci sono due paradigmi di program
mazione predominanti:i linguaggi basati sulle classi e i linguaggi basati sugli
oggetti.I linguaggi basati sulle classi promuovono una programmazione disci
plinata,permettendo la costruzione di solide gerarchie di classi,mentre i linguaggi
basati sugli oggetti forniscono un ambiente conveniente per sperimentare con pro
totipi,ovvero codice in cui parti dell'implementazione potrebbero essere assenti.
Lo scopo della prima parte di questo lavoro e di fornire le basi per un cal
colo che unisca alcune delle caratteristiche di entrambi i paradigmi,e produca un
linguaggio con la disciplina delle classi e la essibilit a dei prototipi.Abbiamo
proposto due estensioni del Core Calculus of Classes and Mixin s di [BPS99],
una con i mixin di ordine superiore ed un'altra con gli oggett i incompleti.
xvii
xviii
Riassunto
Il nostro approccio
I mixin [BC90] sono denizioni di (sotto)classi parametrizza te rispetto a una so
praclasse,e sono stati introdotti come alternativa a certe forme di ereditarieta
multipla.Un mixin puo essere visto come funzione che,data una classe come
argomento,produce una nuova (sotto)classe,aggiungendo e/o ridenendo certi
insiemi di metodi.
Nei nostri calcoli,i mixin hanno la forma seguente:
mixin
method m
j
= v
j
;
(j∈N)
redeﬁne m
k
= v
k
;
(k∈R)
expect m
i
;
(i∈E)
constructor v
c
;
end
I metodi m
j
= v
j
sono i metodi nuovi introdotti dal mixin,gli m
k
= v
k
sono i metodi rideniti che sovrascriveranno i metodi con gli stessi nomi della
sopraclasse,e gli m
i
sono i (nomi dei) metodi previsti,che devono essere for
niti della sopraclasse.Tutti i metodi sono funzioni di un
eld
privato,e di
self
,
che sara legato all'oggetto stesso nel momento della sua creazione.In piu,i
metodi rideniti possono chiamare la loro corrispondente i mplementazione nella
sopraclasse,usando la parolachiave
next
.Il tipo del mixin contiene i tipi dei
metodi gia presenti nel mixin ed i tipi previsti per le componenti non ancora pre
senti.Le nuove sottoclassi sono generate applicando un mixin ad una classe,
attraverso un'operazione di applicazione .Il sistema di tipi determina quando
un'applicazione mixinclasse e possibile.
Il primo calcolo proposto estende il Core Calculus of Classes a nd Mixins di
[BPS99] con i mixin di ordine superiore.In questa estensione un mixin pu
o:(i)
essere applicato ad una classe per generare una sottoclasse funzionante;(ii) essere
composto con un altro mixin per ottenere un altro mixin con piu funzionalita.Il
nostro scopo e di offrire alcune direzioni,secondo noi generali,per il design di un
linguaggio di programmazione con i mixin di ordine superiore,benche il nostro
calcolo non sia basato su alcun linguaggio esistente in particolare.
Nel secondo calcolo proposto estendiamo il Core Calculus of Cl asses and
Mixins di [BPS99] con una forma di oggetti incompleti.Poiche i mixin pos
sono essere visti come classi incomplete che possono essere completate secondo
le richieste del programmatore,abbiamo deciso che un buon punto di partenza
per il nostro calcolo potesse essere l'ereditariet a basata sui mixin,combinata
Riassunto
xix
con operazioni per la manipolazione degli oggetti incompleti.Nella nostra pro
posta,quindi,oltre che instanziare le classi,´e possibile instanziare i mixin per
ottenere cos degli oggetti incompleti.Un oggetto incompleto puo essere in
completo in due modi:( i) gli possono mancare alcuni metodi previsti;(ii) i
suoi metodi rideniti non possono essere invocati nch e i metodi con la funzion
alita del loro
next
non sono stati aggiunti.Gli oggetti incompleti possono essere
completati in due modi:(i) con method addition,che aggiunge uno dei metodi
previsti o uno dei
next
mancanti;(ii) con object composition,che compone un
oggetto incompleto con un oggetto completo contenente tutti i metodi richiesti
dall'incompleto.Quando un metodo viene aggiunto (via addition o via com
position),diventa una componente effettiva dell'oggetto ospite,quindi i metodi
dell'oggetto ospite possono invocarlo,ma anche il nuovo me todo aggiunto puo
usare i metodi dell'oggetto ospite.Il sistema di tipi assic ura che tutte le aggiunte
di metodo e composizioni degli oggetti siano ben tipate e che soltanto i metodi
completi possano essere invocati sugli oggetti.Con quest o approccio,le infor
mazioni di tipo al livello dei mixin sono sfruttate completamente,ottenendo un
calcolo basato sugli oggetti safe.
Partendo dai tipi funzionali,tipi puntatore,e tipi reco rd,il nostro sistema di
tipi comprende anche i tipi delle classi,i tipi dei mixin ed i tipi degli oggetti (degli
oggetti completi,e anche degli oggetti incompleti nella seconda estensione).
La metateoria di entrambe le estensioni e stata studiata estensivamente.In par
ticolare,entrambi i calcoli sono stati dimostrati sound,una proprieta che garan
tisce l'assenza degli errori detti messaggenotunderst ood durante l'esecuzione.
Gemini calcolo
Il
λµµ calcolo e stato introdotto da Curien ed Herbelin in [CH00],per fornire una
corrispondenza CurryHoward alla logica classica.I termini di
λµµ rappresentano
le derivazioni in un sistema di prove basato sui sequenti e la riduzione riette il
processo dell'eliminazione del cut.
La versione non tipata del calcolo puo essere vista come la fondazione di un
linguaggio di programmazione funzionale con una nozione esplicita di controllo.
Una nuova terminologia per le costruzioni sintattiche di base e stata introdotta
in [GL04],ed e stata usata anche in questo lavoro.Chiameremo questo nostro
linguaggio non tipato Gemini.
Le entita sintattiche di base sono cos´ denite:
v::= x  λx.v  µα.c e::= α  v • e  µx.c c::= v e
xx
Riassunto
dove i v appartengono all'insieme Caller dei caller,gli e appartengono all'insieme
Callee dei callee e i c appartengono all'insieme Capsule delle capsule.Le vari
abili denotate con le lettere latine rappresentano l'input mentre le variabili deno
tate con le lettere greche rappresentano le continuazioni.I termini di Gemini si
chiamano Gtermini.
Ci sono tre regole che caratterizzano la riduzione nel calcolo:
(λ) λx.r r
• e → r[x ←r
] e
(µ) µα.c e → c[α ←e]
(˜µ) r ˜µx.c → c[x ←r]
Il calcolo ha una coppia critica µα.c
1
µx.c
2
,dove le due regole (µ) e (µ)
possono essere applicate ambiguamente,producendo due risultati diversi.Quindi
il calcolo non e conuente.Ma se si d a a una delle regole la priorita,si ottengono
due sottocalcoli conuenti
λµµ
T
e
λµµ
Q
,che sono chiusi per callbyname e call
byvalue riduzioni,rispettivamente.
Il presente lavoro studia alcune proprieta di questi due sottocalcoli chiamati
Gemini
n
e Gemini
v
,rispettivamente.Viene provata la conuenza per tutte le d ue
versioni,e vengono presentati dei loro modelli categoriali.
Per dimostrare la conuenza per le due versioni,abbiamo ado ttato la tecnica
delle riduzioni parallele,introdotta da Takahashi in [Tak95].Questa tecnica con
siste nella riduzione simultanea di tutti i residui che esistono in un termine.Come
primo passo,abbiamo denito la nozione di riduzione parall ela ⇒
n
per Gemini
n
.
Dopodiche,abbiamo dimostrato che →→
n
e una chiusura riessiva e transitiva
di ⇒
n
.Di conseguenza,per dimostrare la conuenza di →→
n
,e stato sufcente
provare la propriet a del diamante per ⇒
n
,che seque dalla piu forte propriet a
di stella per ⇒
n
(anch'essa dimostrata).Le prove delle propriet a per Gemini
v
sono state ottenute modicando direttamente le prove per Gemini
n
.
Quando si interpretano dei calcoli che comprendono nozioni di controllo,con
viene utilizzare la semantica delle continuazioni,che permette di riferirsi esplici
tamente alle continuazioni,ovvero alle costruzioni semantiche che rappresentano
i contesti di valutazione.
La semantica delle continuazioni per Gemini
n
e stata ottenuta interpretando
il calcolo nella categoria dei domini negati di [SR98a],mentre Gemini
v
e stato
interpretato nella categoria di Kleisli basata sui predomini per le monadi delle
continuazioni,introdotte da Moggi in [Mog91].Usando le monadi delle com
putazioni,otteniamo inoltre un'interpretazione miglior ata per Gemini
n
,intro
ducendo una nuova categoria sintatica che abbiamo chiamato covalue.In tutti
i casi,la riduzione preserva le denotazioni.
Riassunto
xxi
Uso dei tipi intersezione per caratterizzare il compor
tamento dei lambda termini
Nel lambda calcolo con tipi semplici λ
→
,l'operatore principale per construire i
tipi e la freccia →.Fra le molte estensioni di questo sistema di tipi,quella
che caratterizza la classe piu grande di termini e l'estensione con i tipi inter
sezione.Il sistema di tipi con i tipi intersezione e stato introdotto in [BCDC83]
ed in [CDCV80],ed e di solito denotato da λ
∩
.Il nuovo operatore ∩ per la for
mazione di tipi e introdotto in questo sistema.La caratteristica principale di tale
operatore e che rende possibile assegnare due tipi σ e τ ad un certo lambda ter
mine allo stesso tempo.Un'altra caratteristica important e di questo sistema e il
tipo universale ω che puo essere assegnato a tutti i lambda termini.
In questo lavoro,sono stati costruiti due modelli per il lambda calcolo basati
sui limiti inversi.Essi caratterizzano completamente gli insiemi di termini con
comportamenti computazionali simili:gli insiemi dei termini normalising,head
normalising,weak headnormalizing,gli insiemi dei termini che corrispondono
alle versioni persistenti di queste nozioni,e gli insiemi dei termini closable,clos
able normalising,e closable head normalising.Pi´u precisamente,per ciascuno
di questi insiemi di termini,esiste un elemento corrispondente almeno in uno
dei due modelli,tale che il termine appartiene all'insieme se e solo se la sua in
terpretazione (in ambiente adatto) e superiore o uguale a quell'elemento.Per di
mostrare questo,abbiamo usato la descrizione logica nita ria dei modelli,ottenuta
denendo i sistemi di tipi con i tipi intersezione adatti.
xxii
Riassunto
R´esum´e
Cette these s'est droul ´ee en collaboration avec deux laboratoires scientiques:l e
Dipartimento di Informatica de l'universit ´e du Turin,en Italie,et le Laboratoire
de l'Informatique du Parall ´elisme (LIP),l'
´
Ecole Normale Sup´erieure de Lyon,en
France.
La these est divis´ee en deux parties.La premiere partie,dirig´ee par Viviana
Bono (professeur),propose un calcul fond´e sur la notion de mixin,qui permet
de repr´esenter a la fois des objets incomplets et des mixins d'ordre sup ´erieur.
La seconde partie,dirig´ee par Pierre Lescanne (professeur),´etudie les propri´et´es
de deux souscalculs du
λµµ calcul non typ´e de Curien et Herbelin [CH00].
La troisieme partie,´ecrite en collaboration avec Mariangiola Dezani et Silvia
Ghilezan,pr´esente deux modeles de limite inverse pour le lambda calcul avec
types intersections.
Mixin calculus
Dans le monde orient´e objet,on trouve deux paradigmes de programmation pr´edo
minants:les langages fond´es sur les classes et ceux fond´es sur les objets.Les
langages fond
´
es sur les classes renforcent la discipline de programmation en per
mettant la construction de hi´erarchies de classes rigides,alors que les langages
fond´es sur les objets offrent un environnement confortable pour l'exp ´erimentation
de prototypes,dont certaines parties manquent encore.
Le but de ce travail ´etait de concevoir un calcul qui combine les deux paradigmes,
c'est adire d'essayer de fournir en un seul langage la discipline des classes et la
exibilit ´e des prototypes.Nous proposons deux extensions du Core Calc ulus of
Classes and Mixins [BPS99],l'une avec mixins d'ordre sup ´erieur (composite),
l'autre avec objets incomplets.
xxiii
xxiv
R´esum´e
Notre approche
Les mixins [BC90] sont des d´enitions de (sous) classes param ´etr´ees par une
superclasse.Ils ont
´
et
´
e introduit comme une alternative
a certaines formes d'h
´
eritage
multiple.Un mixin peut etre vu comme une fonction qui,´etant donn´ee une classe
en argument,produit une (sous) classe,en ajoutant et/ou red´enissant certains
ensembles de m´ethodes.
Dans notre calcul,les mixins ont la forme suivante:
mixin
method m
j
= v
j
;
(j∈N)
redeﬁne m
k
= v
k
;
(k∈R)
expect m
i
;
(i∈E)
constructor v
c
;
end
Les m´ethodes m
j
= v
j
sont introduites par le mixin,les m
k
= v
k
sont des
m
´
ethodes red
´
enies,qui vont red
´
enir les m
´
ethodes de m
eme nom provenant de
la superclasse,et les m
i
sont des (noms de) m´ethodes attendues,qui doivent etre
fournis par la superclasse.Toutes les m´ethodes sont fonctions du champ priv´e
eld
et de
self
,qui seront li´es a l'instanciation a l'objet en cours de cr ´eation.En
outre,les m´ethodes red´enies peuvent faire r ´ef´erence a leur impl´ementation dans
la superclasse grace au motclef sp´ecial
next
.Un type de mixin prend en compte
les types des m´ethodes d´eja pr´esentes dans le mixin,ainsi que les types attendus
pour les composants manquant.On cr´ee de nouvelles sousclasses en appliquant
un mixin a une classe via un op´erateur d´edi´e .Le systeme de types v´erie que
l'application de mixin est possible.
Le premier calcul propos´e par la these ´etend le Core Calculus of Classes and
Mixins [BPS99] avec des mixins d'ordre sup´erieur.Dans cette extension,un
mixin peut (i) etre appliqu´e a une classe pour cr´eer une sousclasse complete,ou
(ii) tre compos´e avec un autre mixin,ce qui donne un nouveau mixin avec plus
de fonctionnalit´es.Dans ce que nous croyons etre un cadre sufsamment g ´en´eral,
nous donnons des ´el´ements pour concevoir un langage de programmation ´equip´e
de mixins d'ordre sup ´erieur,bien que notre ´etude ne soit pas bas´e sur un langage
orient´eobjet existant.
Dans le second calcul propos´e par la these,nous ´etendons le Core Calculus of
Classes and Mixins [BPS99] avec des objets incomplets.Les mixins pouvant etre
vus comme des classes incompl
etes,susceptibles d'
etre compl
´
et
´
ees suivant les be
soins du programmeur,nous avons choisi comme point de d´epart de notre calcul la
R´esum´e
xxv
combinaison du style d'h
´
eritage fourni par les mixins avec les constructions pour
la manipulation d'objets incomplets.Par cons ´equent,en plus de l'instantiation de
classe habituelle,le calcul fournit aussi un m´ecanisme d'instanciation de mixin,
qui g´enere des objets incomplets.Ainsi,un objet incomplet est incomplet en deux
sens distincts:(i) il peut avoir besoin de m´ethodes attendues et (ii) les m´ethodes
qu'il red ´enit ne peuvent pas etre invoqu´ees tant que leurs
next
s ne sont pas
fournies.Les objets incomplets peuvent etre compl´et´es de deux fac¸ons:(i) par
ajout de m´ethode,qui ajoute l'une des m´ethodes attendues ou l'un des
next
s man
quant,ou bien (i) par composition d'objets,qui compose un objet complet avec
un objet complet contenant toutes les m
´
ethodes requises.Lorsqu'une m
´
ethode est
ajout´ee,elle devient un composant effectif de l'objet h ote,de telle sorte que les
m´ethodes de cet objet peuvent y faire r´ef´erence.De meme,la m´ethode ajout´ee
peut utiliser les autres m´ethodes de l'objet h ote.Le systeme de types v´erie que
tous les ajouts de m´ethode et les compositions d'objets sont s ures et que seules
des m´ethodes compl etes sont invoqu ´ees.Ainsi,l'information de types sur les
mixins est exploit´ee au maximum,ce qui donne un calcul d'objets s ur et exible.
En plus des types de fonctions,d'enregistrements et de r ´ef´erences mutables,
nos systemes de types comprennent des types de classes,de mixins et d'objets
(complets et incomplets pour la seconde extension).
Nous ´etudions la m´etath´eorie des deux extensions.En particulier,nous prou
vons la propri´et´e de suret´e,pour garantir l'absence d'erreur Message not under
stood a l'ex ´ecution.
Le Gemini calcul
Le
λµµ calcul a ´et´e introduit par Curien et Herbelin [CH00],dans le but d'´etablir
une correspondance de CurryHoward pour la logique classique.Les termes de
λµµ repr´esentent des d´erivations dans une pr´esentation de la logique classique re
posant sur un calcul de s´equents,et la r´eduction re ete le processus d'´elimination
des coupures.
La version non typ´ee du calcul peut etre vue comme le fondement d'un lan
gage de programmation fonctionnel avec une notion explicite de controle.Une
nouvelle terminologie a ´et´e donn´ee dans [GL04],que nous utilisons ici.Nous
appelons ce langage non typ´e Gemini.
Les constructions de base sont d´enies comme suit:
v::= x  λx.v  µα.c e::= α  v • e  µx.c c::= v e
ou v d´esigne un ´el´ement de l'ensemble Caller des callers,e d´esigne un ´el´ement
xxvi
R´esum´e
de l'ensemble Callee des callees,et c d
´
esigne un
´
el
´
ement de l'ensemble Cap
sule des capsules.Les variables en lettres latines repr ´esentent les entr´ees et
les variables en lettres grecques repr´esentent les continuations.Nous appelons les
terms de Gemini des Gtermes.
La r´eduction dans ce calcul est caract´eris´ee par trois regles principales:
(λ) λx.r r
• e → r[x ←r
] e
(µ) µα.c e → c[α ←e]
(˜µ) r ˜µx.c → c[x ←r]
Le calcul pr´esente une paire critique µα.c
1
µx.c
2
ou les regles (µ) et (µ)
s'appliquent toutes les deux et donnent deux r ´esultats diff´erents.Le calcul est
donc nonconuent.N ´eanmoins,si la priorit´e est donn´ee a l'une des r egles,on
obtient deux souscalculs conuents
λµµ
T
et
λµµ
Q
,qui sont clos par r´eduction
en appel par nomet en appel par valeur,respectivement.
Ce travail ´etudie les propri´et´es de deux souscalculs du
λµµ calcul de Curien
et Herbelin [CH00],appel´es respectivement Gemini
n
et Gemini
v
.On prouve leur
conuence et on en donne des mod eles dans la th´eorie des domaines.
Pour prouver la conuence de ces calculs,nous adoptons la te chnique des
r´eductions paralleles propos´ee par Takahashi [Tak95].Cette approche consiste a
r´eduire simultan´ement tous les redexes d'un terme.D'abord,on d ´enit la notion
de r
´
eduction parall
ele ⇒
n
pour Gemini
n
.Ensuite,nous montrons que →→
n
est une
fermeture r´eexive et transitive de ⇒
n
.Ainsi,pour prouver la conuence de →→
n
,
il suft de prouver la propri ´et´e du diamant pour ⇒
n
,qui d´ecoule de la propri´et´e
plus forte de l'´etoile,que nous prouvons.La preuve pour Gemini
v
est obtenue
en modiant l ´egerement la preuve pour Gemini
n
.
Pour interpr´eter les calculs dot´es d'une notion de contr ole,il est int´eressant
de partir de la s´emantique des continuations,qui permet de faire explicitement
r´ef´erence a des continuations,qui sont les structures s´emantiques utilis´ees pour
repr´esenter les contextes d'´evaluation.
La s´emantique des continuations de Gemini
n
est donn´ee par l'interpr ´etation
dans la cat´egorie des domaines ni ´es [SR98a],alors que Gemini
v
est interpr´et´e
dans la cat´egorie de Kleisli sur les pr´edomaines pour la monade des continua
tions,propos´ee par Moggi [Mog91].En utilisant les monades calculatoires,nous
donons aussi une meilleure interpr´etation pour Gemini
n
,qui introduit une nou
velle entit´e syntaxique appel´ee covaleur.Dans tous les cas,la r´eduction pr´eserve
la d´enotation.L'avantage principal de ces mod eles est qu'ils s'accomodent du
caractere non typ´e du calcul en r´esolvant une ´equation de domaine r´ecursif.
R´esum´e
xxvii
Utilisation de types intersections pour caract´eriser le
comportement de lambda termes
Dans le lambda calcul simplement typ´e λ
→
,l'op ´erateur basique de construction
de type est la eche →.Parmi les nombreuses extensions connues de ce systeme
de types,celle qui caract´erise la plus grande classe de termes est l'extension avec
types intersections.Le systme de types avec intersection [BCDC83,CDCV80]
est not
´
e λ
∩
.Dans ce syst
eme,un nouvel op
´
erateur de construction de type est
introduit,l'intersection ∩.Grace a cet op´erateur,il est possible d'assigner deux
types σ et τ simultan´ement a un certain lambda terme.Une caract´eristique de ce
systeme est le type universel ω,qui peut etre assign´e a tous les lambda termes.
Nous construisons deux λmodeles avec limite inverse qui caract´erisent comple
tement des ensembles de termes dot´es de comportements calculatoires semblables:
les termes normalisants,ceux qui admettent une forme normale de tete,ceux qui
admettent une forme normale de tete faible,les ensembles de termes correspon
dant aux versions persistentes de ces notions,ainsi que les ensembles de terms qui
admettent la fermeture,la fermeture normalisant et la fermeture normalisant de
tete.Plus pr´ecis´ement,pour chacun de ces ensembles de termes,il y a un ´el´ement
correspondant dans au moins l'un des deux mod eles,de sorte qu'un terme appar
tient a l'ensemble consid ´er´e si et seulement si son interpr´etation est sup´erieur ou
´egale a l'´el´ement correspondant.Pour prouver ce r´esultat,nous utilisons une de
scription logique nie des mod eles,obtenue en d´enissant des syst emes de types
avec intersection ad´equat.
xxviii
R´esum´e
Part I
Introduction
1
Chapter 1
Introduction
1.1 Type systems for programming languages
1.1.1 Introduction
In a struggle for designing more exible and expressive prog ramming languages,
type systems certainly play a very important role.They were introduced in order
to check the occurrence of some execution errors during runtime,and ensure the
semantical good behaviour of programs.
A type is a syntactic construct assigned to a term to provide a description of
some properties of the term.It is a set of values together with the operations and
relations applicable to them.A type assigned to a term can be compared with a
dimension of a physical entity.More accurately,terms and their types can be seen
as programs and their specications,respectively.
Typed languages are the ones where variables can be assigned nontrivial
types,i.e.,each part of the program can be assigned a type that describes its be
havior,and can be deduced from the types of its subfragments.The types of
operands are checked to prevent nonsensical operations.On the other hand,un
typed languages either have no types at all,or have a single universal type for all
values.
It is exactly the concept of type for functional languages that is the connect
ing link among the various parts of this thesis.
We distinguish dynamically typed languages,where type checking is done
just before the operations are executed,from statically typed languages,where
types are assigned to terms at compile time.Static typing enables earlier detection
of errors,and provides information to compilers,as well as documentation of
3
4
CHAPTER1.INTRODUCTION
the program.The algorithm that performs the type checking process is called
typechecker,and the program that passes the typechecking process is said to
be welltyped.In the case of dynamic typing,only values are assigned types,
which brings more exibility,but at the cost of execution sp eed and space.Java
[AGH00],ML [MTHM97],Haskell [JHA
+
99],and Pascal [JW71] are examples
of statically typed languages.LISP [Ste90] and Python [vRD03] are some of the
dynamically typed languages.In this thesis we are dealing with static typing only.
Using type systems enables static analysis of the programs,thus establishing
the properties about their execution.The key property of absence of some runtime
errors is ensured by proving formally a property of type safety.For instance,
for objectoriented languages this guarantees avoiding messagenotunderstood
errors.
Base types in programming languages include types like Character,String,
Integer,Real,Boolean etc.By applying certain operators to base types,it is also
possible to build new types,like record or function types.
Record type is a list of labeltype pairs,where all the labels are pairwise
distinct.They give types to records,which means that they assign a type to each
value corresponding to a label in a record.Record type is of the form
{
i
:σ
i
}
i∈I
.
Function type types functions.It needs to take into account the types of its
arguments and the types of the returned results.It has the form
σ →τ
which means that the argument is of type σ and the result is of type τ.
Intersection type makes it possible to assign two types σ and τ to a certain
lambda termat the same time.It has the form
σ ∩τ.
We distinguish explicitly typed languages where programs are typed manu
ally,i.e.,types are part of the syntax and the programmer gives the annotations to
the program's source code,so that the compiler has only to check the validity of
provided types,from implicitly typed ones where programs are typed automati
cally,i.e.,types are inferred by a type inference algorithm.
1.1.TYPESYSTEMSFORPROGRAMMINGLANGUAGES
5
1.1.2 Formalizing a typed programming language
In this thesis we focus on the languages based on the functional programming
paradigm.Functional programming is a programming style in which compu
tation is performed by applying functions to arguments.The central concept is
evaluation of expressions,rather than execution of commands.A functional lan
guage is the language that supports functional programming style.Functional
programs have a more abstract nature,making formal reasoning about them eas
ier.
When formalizing a typed functional programming language,the following is
usually described:
• syntax of its terms and types.Terms are the programs and types express
static information about the terms;
• scoping rules dened by the set of free variables of the program.A notion
of substitution of types or terms for free variables is also given;
• operational semantics via reduction rules that compute results (values) start
ing fromterms;
• type system that consists of the set of formal rules used compositionally to
assign types to welltyped programs.
Judgements of the type systemspecify the has type relations of the form
Γ t:τ,
where Γ is a context,t is a term and τ is a type.Contexts are used to record the
types of the free variables.A context Γ has the form
Γ = x
1
:σ
1
,...,x
n
:σ
n
,
where for all i = 1...n,x
i
are term variables,and σ
i
are types.All the variables
in the context are pairwise distinct,and none of themoccurs twice.
Starting from some typing judgements of the language,type rules assert the
validity of other judgements.They are given by one or more premisses,followed
by a conclusion judgement.
The consistency of a type systemwith respect to operational semantics is pro
vided by type soundness,which ensures that the well typed programs are well
behaved,i.e.,they cannot go wrong.
6
CHAPTER1.INTRODUCTION
Simply typed lambda calculus
As an example,we present here the syntax,operational semantics and typing rules
of the simply typed lambda calculus.For comprehensive account of the subject
we refer the reader to [Bar84].
The syntax of the lambda calculus is given by
t::= x  λx.t  tt
where x is a variable,λx.t is a lambda abstraction (which represents a mapping
x →t),and tt is the application (which represents application of a function to its
argument).
The main reduction rule of the lambda calculus is the βrule,which we give
for the callbyname variant:
(λx.t
1
)t
2
→[t
2
/x]t
1
.
This means that the actual parameter t
2
is substituted for the formal parameter x
in the function body t
1
.
The typing systemfor simply typed lambda calculus has the following axioms
and rules.
(x:α) ∈ Γ
Γ x:α
(ax)
Γ,x:α t:β
Γ λx.t:α →β
(→I)
Γ t
1
:α →β Γ t
2
:α
Γ t
1
t
2
:β
(→E)
Subtyping
In some languages,subtyping relation of the form
Γ σ <:τ
between types is given.It means that an expression of type σ can be used when
ever an expression of type τ is expected.In the type system,subtyping is usually
included by the subsumption principle which says that if an expression e has type
σ and σ is a subtype of τ (σ <:τ),then e is also of type τ.
For the record types the subtyping relation is given by
{
i
:σ
i
}
i∈I
<:{
j
:τ
j
}
j∈J
iff J ⊆ I and ∀j ∈ J,σ
j
<:τ
j
.
1.2.OBJECTORIENTEDPROGRAMMING
7
This means that a subtype of a record type may have more elds ( subtyping in
width) and types of corresponding labels may be subtypes of the ones in the su
pertype (subtyping in depth).
In the case of function types,the argument has a contravariant position,whereas
the result is covariant.This can be expressed as
σ
1
→τ
1
<:σ
2
→τ
2
iff σ
2
<:σ
1
and τ
1
<:τ
2
.
If we add imperative side effects to a functional language,reference types
have to be taken into account.A reference variable of type σ denotes a location
in which a value of type σ is stored.Hence,for reference types there are no
nontrivial subtypes,i.e.,
ref σ <:ref τ iff σ τ.
In the sequel,we consider type systems for objectoriented languages and in
these systems,subtyping relation plays a very important role.
1.2 Objectoriented programming
1.2.1 Basic concepts
Objectoriented programming languages are not loosing their strength and inu
ence over the last two decades.
The basic computational entities are objects which are data structures with
a state (represented by instance variables or elds ) and some operations,called
methods,used to access and manipulate the object's state.
A program can act on objects'states by invoking methods on them.Objects
are instances of classes.A class stores implementation information about its ob
jects,like initial values of the instance variables,and names and bodies of the
methods.
One of the main features of objectoriented languages is inheritance which
is the ability to generate subclasses from existing classes.The subclass inherits
all the components from its superclass and it has the possibility to add/replace
the instance variables and methods from the superclass.Using inheritance as an
implementation technique when designing class hierarchies,avoids code duplica
tion,enhances code reuse,and enables consistent changes in the class hierarchy.
Encapsulation is a concept that enables modular programming,since objects
in a system can be seen as black boxes that hide the implemen tation details
8
CHAPTER1.INTRODUCTION
of their components while only revealing their usable interface.There are usually
three levels of visibility for instance variables and methods:public,when they can
be seen and accessed fromall the components of the system,protected,if they can
be only inherited,and private,when they are owned by a class and accessible only
frominside the class itself.
Dynamic binding enables choosing the appropriate method to be executed
based on the runtime type of the receiving object.The same message can be
sent to different objects that have the method with the given name and appropriate
type but different implementations.When the code selection depends only on
the receiving object,it is called single dispatch,whereas in the case of multiple
dispatch,the selected code depends also on method arguments.
self
is a language construct that is used to refer to the object that executes the
method.The term
self
is used in languages like Object Pascal and Smalltalk,this
is used in C++ and Java,and Current is used in Eiffel.
Finally,another basic concept of this thesis is the concept of mixin.Mixins
[BC90,FKF98] are (sub)class denitions parameterized over a superclass and
were introduced as an alternative to some forms of multiple inheritance [BLS94,
Bra92,LM96].It can be seen as a function that,given one class as an argument,
produces another class,by adding and/or overriding certain sets of methods.
1.2.2 Typing objectoriented languages
In objectoriented programming languages,types ensure that certain methods can
be safely invoked on certain objects,preventing the occurrence of the so called
messagenotunderstood errors.In the literature,invo king a method is often
regarded to as sending a message to an object.The object that is sent a message,
must have a method with the same name,where types of formal parameters and
return types are compatible with the ones in the message.
Object types give names and types of methods that the objects of that type
support,but usually do not restrict the implementation of the methods.Types can
be seen as a usable interface which species the legal operat ions on the objects of
that type.As pointed out in [FM96],there is also another formof object type:the
type that also imposes some implementation constraints.In this work,only the
rst formwill be used.
Variable
self
,which denotes the object that receives the message and executes
the method,may introduce complexity in typing systems,when it is given a poly
morphic type,usually called
MyType
or
SelfType
[Bru02,FHM94].
MyType
1.2.OBJECTORIENTEDPROGRAMMING
9
specializes as the methods are inherited and can be considered as a special form
of a recursive type.
Subtyping is an important concept that enables uniform treatment of expres
sions of various types.Object subtyping is based on record subtyping and we
distinguish subtyping in width,where the subtype can have more components,
and subtyping in depth,with componentwise subtyping on the components.This
form of object subtyping is called structural because it depends only on the pub
lic interfaces of the objects,not on their implementations.Especially,objects in
subtyping relation do not necessary need to be instances of the classes that are in a
subclass relation.Hence,objects with the same interface,but different implemen
tations can be used interchangeably in a program.There is another formof object
subtyping,called nominal subtyping,where subtyping hierarchy depends strictly
on the class hierarchy (as it is for instance in Java [AGH00]).
In the presence of subtyping,there is some added exibility in constructing
language expressions,although at the price of further complications in typing is
sues,since the actual parameters of the methods can differ from the formal ones.
Subtyping in the presence of
MyType
is more complicated because of the well
known issues concerning subtyping and recursive types.
1.2.3 Classbased vs.objectbased languages
In objectoriented world,there are two predominant programming paradigms:
classbased and objectbased.
In classbased languages,objects are created as instances of classes (that can
be seen as templates) and as such are computational entities of a software system.
But they are passive with respect to their structure,which is xed by a class
hierarchy.In objectbased languages,new objects are produced starting from
the existing ones,through operations like method addition and method override.
Classbased objectoriented languages (like Java [AGH00] and C++ [Str97]) pro
mote disciplined programming by enabling construction of class hierarchies,espe
cially needed in a programminginthelarge setting.The objectbased paradigm
is gaining a renewed interest in the context of script languages (see for example
[BDG02,DG03]) like JavaScript [Fla02],and delegationbased languages (see
for example [AD02,ABDCD03]),since it provides a convenient environment for
experimenting with prototypes,where parts of their implementation might still be
missing.For some insightful discussions about the differences between the two
paradigms observed from different angles,some of the good references are the
books of AbadiCardelli [AC96] and of Bruce [Bru02].
10
CHAPTER1.INTRODUCTION
1.3 Basic domain theory
The theory of domains was established in order to have appro priate spaces on
which to dene semantic functions for the denotational appr oach to programming
language semantics. [GS90]
This section summarises some basic terminology on domain theory.
A partially ordered set or poset (X,
X
) is a set X with a binary relation
X
which is reexive,antisymmetric and transitive.If no con fusion can arise,
we will often omit the underlying relation and write just X for a poset (X,
X
).
Let X be a poset and let A ⊆ X.Then:
• x ∈ X is an upper bound for A if ∀a ∈ A.a x;
• x ∈ X is a greatest element of A if x ∈ A and x is an upper bound for A;
• a ∈ A is maximal if ∀a
∈ A,if a a
,then a
= a;
• the notions of a lower bound,least and minimal element are dened analo
gously;
• a join or supremum of A (if it exists) is a least upper bound for A.It is
denoted by A.A meet or inmum of A (if it exists) is a greatest lower
bound for A.It is denoted by A.
Let X be a poset.Then:
• A ⊆ X is called directed,A ⊆
dir
X,if A = ∅ and ∀x,y ∈ A,∃z ∈ A.x
z and y z;
• X is complete or cpo if it has a least element ⊥ and every A ⊆
dir
X has a
join;
• X is a lattice if it has nite meets and joins.If it has only nite meets (joi ns)
it is called a meet (join)semilattice.A poset with arbitrary meets and joins
is called a complete lattice;
• x ∈ X is compact or nite if ∀A ⊆
dir
X.x A ⇒∃a ∈ A.x a.The
set of all compact elements of X is denoted by K(X).
Let X be a cpo.Then:
• its lifting is X ∪ {⊥} = X
⊥
,where ⊥ ∈ X and x
X
⊥
y iff (x =
⊥or x
X
y);
• X is algebraic if for all x ∈ X,the set M = {x
0
∈ K(X)  x
0
x} is
directed and x = M;
1.4.BASICCATEGORYTHEORY
11
• X is bounded complete if every bounded subset of X has a join;
• X is Scott domain if it is algebraic and bounded complete.
A function f between two cpo's (X,
X
) and (Y,
Y
) is:
• monotone if ∀x,y ∈ X.x
X
y ⇒f(x)
Y
f(y);
• continuous if it is monotone and ∀A ⊆
dir
X.f(A) = f(A);
• strict if f(⊥) = ⊥.
If X is a cpo and f:X →X is continuous then a xed point of f is an ele
ment x ∈ X such that x = f(x).The minimal xed point is given by
n∈N
f
n
(⊥).
For two domains X and Y,the function space X →Y contains the continu
ous functions fromX to Y ordered pointwise,which means that
f g iff ∀x ∈ X.f(x) g(x).
Two posets X and Y are isomorphic if there are monotone functions f:X →
Y and g:Y →X such that g ◦ f = id
X
,and f ◦ g = id
Y
A pair of continuous functions (f,g),where f:X → Y and g:Y → X is
called embeddingprojection pair if g ◦ f = id
X
,and f ◦ g id
Y
.
1.4 Basic category theory
Category theory arose in mathematics to enable abstract description of different
mathematical structures and relationships between them.
A category C is specied by the following:
• A collection Obj(C) of objects,often denoted by A,B,C,....
• A collection Mor(C) of morphisms,often denoted by f,g,h,....
• Two operations assigning to each morphism f its source src(f) and target
tar(f),both objects of C.If A = src(f) and B = tar(g),we write
f:A →B or f ∈ C(A,B).
• Morphisms f and g are composable if tar(f) = src(g).Composition of
two composable morphisms f and g is a morphism denoted by g ◦ f such
that src(g ◦ f) = src(f) and tar(g ◦ f) = tar(g).
• For each object A of C there exists an identity morphism id
A
:A →A.
12
CHAPTER1.INTRODUCTION
• For every f:A →B,g:B →C and h:C →D the following holds:
id
tar(f)
◦ f = f,f ◦ id
src(f)
= f
h ◦ (g ◦ f) = (h ◦ g) ◦ f
The opposite category C
op
is the category with the same collection of ob
jects as the category C and morphisms given by the following:f:A → B is a
morphismin C
op
if and only if f:B →A is a morphismin C.
The category is small if Obj(C) is a set.It is locally small if far all A,B ∈
Obj(C),C(A,B) is a set.
A functor F:C → D between two categories C and D,maps objects of C
into objects of D and morphisms of C into morphisms of D,preserving identities
and composition,i.e.,
• For every A ∈ Obj(C),FA ∈ D;
• For every f:A →B in C,Ff:FA →FB in D;
• For every f:A →B,g:B →C,F(id
A
) = id
FA
and F(g◦f) = Fg◦Ff.
In a category C,a binary product of objects A and B is a triple
(A×B,π
1
,π
2
)
where A × B is an object in C,and π
1
:A × B → A,π
2
:A × B → B are
morphisms in C,such that for any C ∈ C and any two morphisms f:C →A and
g:C → B,there is a unique morphism h:C → A ×B for which π
1
◦ h = f
and π
2
◦ h = g.h is usually denoted by f,g.
Given morphisms f:X → X
and g:Y → Y
,morphism f ×g is dened
as
f ×g = f ◦ π
1
,g ◦ π
2
:X ×Y →X
×Y
.
Finally,cartesian closed category (CCC) is a category which has nite prod
ucts and for any A,B ∈ Obj(C),exponent B
A
∈ Obj(C) and a morphism
ev:B
A
× A → B exist,such that for any f:A × B → C there is a unique
morphismλ(f):A →C
B
for which f = ev ◦ (λ(f) ×id
B
).
Some examples of categories are:
1.Set (Part),the category of sets and total (partial) functions;
2.Any preorder (X,≤) can be seen as a category,where objects are the ele
ments of X,and morphisms are instances of the order relation;
3.Cat,the category of small categories and functors;
4.SDom,the category of Scott domains and continuous functions.
For further reading on category theory,some of the good textbooks are [Lan71,
Kro93].
1.5.OVERVIEWOFTHETHESIS
13
1.5 Overview of the thesis
This thesis was developed as a joint work between Dipartimento di Informatica,
Universita di Torino,Italy,and
´
Ecole Normale Sup´erieure de Lyon,France,under
supervision of Prof.Viviana Bono (Torino) and Prof.Pierre Lescanne (Lyon).
The thesis is divided into three parts.The rst part,superv ised by Prof.Vi
viana Bono,is described in Part II.It is a proposal for the design of a mixinbased
calculus that combines and puts to the test some fairly innovative features with
more classical ones.It is organised as follows:
• Chapter 2 is an introduction to mixin calculi.It also gives a simple example
of the mixin usage and gives an account on the existing work on the subject.
• Chapter 3 is a short overview of Core calculus of mixins and classes
of [BPS99] that was the starting point for the rst part of the t hesis.
• Chapter 4 presents the extension of the Core calculus of mixins and cla sses
of [BPS99] with higherorder mixins,which enable the construction of more
exible class hierarchies.
• In Chapter 5 the Core calculus of mixins and classes of [BPS99] is en
riched with incomplete objects,thus yielding a language suited for rapid
prototyping.It is an attempt to integrate good features of classbased and
objectbased languages.
• In Chapter 6,width subtyping on complete objects is added to the variant of
the calculus with mixins and incomplete objects fromChapter 5.A general
technique for composing objects in the presence of subtyping is given.
• Finally,Chapter 7 concludes comparing our work with the related work on
the subject,and giving some directions for possible future development.
The work on the mixinbased calculi is published in [BBL04a,BBL04b,BBL04c,
BBL05a,BBL05b].
The second part was developed under the supervision of Prof.Pierre Lescanne
and is described in Part III.It investigates some properties of the untyped
λµµ
calculus and is organised as follows:
• Chapter 8 recalls the syntax and the reduction rules of
λµµ calculus,and
its two wellbehaved subcalculi
λµµ
T
and
λµµ
Q
.It also presents the type
system based on simple types,and gives a short account of the related sys
tems.
14
CHAPTER1.INTRODUCTION
• Chapter 9 presents an elegant proof of the conuence for the
λµµ
T
and
λµµ
Q
variants of the calculus.
• Chapter 10 deals with the denotational semantics of untyped
λµµ calcu
lus.It gives an account of negated categories where the
λµµ
T
calculus is
interpreted.Next,the basic notions of Kleisli triple and Kleisli category
are presented and interpretation of the
λµµ
Q
calculus is given.Finally,the
improved interpretation of
λµµ
T
calculus is provided.
• Chapter 11 concludes,indicating some possible future research directions.
The work fromthis part can be also found in [LL04].
The third part was written in collaboration with Prof.Mariangiola Dezani and
Prof.Silvia Ghilezan It is presented in Part IV and is organised as follows:
• Section 12.2 discusses the duality between intersection types and inverse
limit domains.
• In Section 12.3 the models D
∞
and E
∞
are built.
• In Section 12.4 we dene intersection types and build sets F
D
and F
E
of
lters in order to prove the isomorphismbetween the inverse limit λmodels
and the lter models.The corresponding intersection type a ssignment sys
tems are dened in Section 12.5.
• The main result is a complete characterisation of computational behaviours
of terms by their typeability in the corresponding type systems.This is
stated in Section 12.5 and one direction of the equivalence is proved there
for all cases but for persistently normalising terms.Section 12.6 deals with
the case of persistently normalising terms,which needs the notions of re
placeable and nonreplaceable variables.
• In Section 12.7 we prove the other direction of the equivalence using stan
dard techniques of the reducibility method adapted for these type systems.
The results fromthis part are published in [DCGL04].
Part II
Core calculus of classes and mixins
and extensions
15
17
18
Chapter 2
Mixins in programming languages
2.1 Introduction
2.1.1 What is a mixin?
Recently,the concept of a mixin is undergoing a renaissanc e,due to its exible
nature of incomplete entity that can be completed accordi ng to the program
mer's needs.There are two uses of the term mixin in the litera ture:it can be
seen as a mixin class (parameterized (sub)class denition,see [ALZ00,DT01,
BBV02,BBV03]),and as a mixin module (module supporting deferred compo
nents,see [ALZ02,FF98,SB98,HL02]).In this work the term mixin refers to
mixin classes.
Mixins [BC90,FKF98] are (sub)class denitions parameterize d over a super
class and were introduced as an alternative to some forms of multiple inheritance
[BLS94,Bra92,LM96].Amixin could be seen as a function that,given one class
as an argument,produces another class,by adding and/or overriding certain sets
of methods.The same mixin can be used to produce a variety of classes with
the same functionality and behavior,since they all have the same sets of methods
added and/or redened.This uniformextension and modicat ion of classes is ab
sent from the classical classbased languages,where a new subclass needs to be
written whenever a class has to be extended with a certain set of components.
The superclass denition is not needed at the time of writing the mixin def
inition.This minimizes the dependencies between superclass and its subclasses,
thus improving modularity and code reuse.
Mixins actually specify how a particular subclass differs from an arbitrary
superclass.Therefore,separate mixins can be used to specify each of these varia
19
20
CHAPTER2.MIXINSINPROGRAMMINGLANGUAGES
tions and more complex structures can be obtained by combining the basic mixins.
This approach is fundamentally different fromthe inheritance mechanismin pure
classbased languages.
As mentioned before,the notion of mixin is not strictly connected to object
oriented programming.A mixin module is generally regarded as a construct with
some missing components,expected to be provided by some other module.Mix
ins were rst introduced in the Flavors system [Moo86] and CLO S [Kee89],al
though not as a formal language construct but as a programming idiom.
2.1.2 Examples
In this section,we present the examples that should illustrate some of the uses of
mixins.
In standard classbased languages,(sub)classes are produced by extending
the (super)class,giving denitions of new methods and/or r edening the exist
ing methods fromthe superclass.
Let us assume that we have two classes FileStream and Socket that both
have methods read and write with different implementations.Moreover,class
Socket may have some additional methods,for example,IPaddress.
To create encrypted streamclass EncryptedFileStream which redenes
these two methods,we have to extend the class FileStream providing rede
nitions for these two methods.
class FileStream
method write =...
method read =...
...
end
class EncryptedFileStream extends FileStream
redeﬁne write =...
redeﬁne read =...
end
If we also want to create class EncryptedSocket,which encrypts data
communicated over a network connection,then read and write methods must
be redened with the same body as in the previous case.Theref ore,we have to
extend the class Socket providing again the same redenitions for these two
methods.
class Socket
method write =...
method read =...
...
end
class EncryptedSocket extends Socket
redeﬁne write =...
redeﬁne read =...
end
2.1.INTRODUCTION
21
In some other situation we might want to use the stream as a logging de
vice which provides a doLog method.Then we have to create the subclass
LogFileStream that extends the class FileStream with the denition of
doLog method.The same would happen if we wanted to use a socket as a log
ging device,i.e.,we would again be in the situation to create a new subclass
LogSocket with the same additional method denition.
class LogFileStreamextends FileStream
method doLog =...
end
class LogSocket extends Socket
method doLog =...
end
We can see that the extensions in all the cases duplicate the code,thus making
the code less understandable and more difcult to maintain.It would be much
better if we could reuse the method redenitions that we used when extending the
FileStream class to also extend the Socket class.Furthermore,it should be
possible to use the denition of doLog method whenever we need to add logging
functionality to some class.
Mixins are a simple solution to these problems.We can group the encrypting
redenitions into Encrypted mixin and then apply this mixin to all the classes
that need to be encrypted.
mixin Encrypt
redeﬁne write =...
redeﬁne read =...
end
class EncryptedFileStream= Encrypted FileStream
class EncryptedSocket = Encrypted Socket
In the same manner,we can create the mixin Logger and apply it to any class
that is supposed to provide logging.
mixin Logger
method doLog =...
end
class LogFileStream= Logger FileStream
class LogSocket = Logger Socket
Mixins are also useful to simulate some cases of (linearized) multiple inher
itance.For example,we can construct class LogEncryptedFileStream by
applying mixins Logger and Encrypted to FileStream,i.e.,
class LogEncryptedFileStream= Logger Encrypted FileStream
22
CHAPTER2.MIXINSINPROGRAMMINGLANGUAGES
With the mixin constructs we achieved a signicant reductio n in code size,
and we provided for a better understanding of the program,since the connected
(re)denitions are grouped together and can be uniformly ap plied to many differ
ent classes.
In the following chapters (see Sections 4.6 and 5.7) we will see how this ma
chinery works in our proposal and what are its benets and res trictions.
2.2 Literature on mixins
In the literature,there are many proposals that deal with mixins.We mention here
some of them,the most interesting with respect to our proposal.Direct compari
son with our work will be given in Section 7.2.
• Bracha and Cook extend Modula3 with mixins in [BC90] (this is one of
the seminal papers on mixins).Mixins are taken as the basic compositional
constructs in the language and inheritance is simulated by mixin composi
tion.The novelty is seeing object types as mixins,which either explicitly
state the modications to the superclass,or are obtained as a result of mixin
composition.The lefthand mixin has a priority and the co mposition is
not explicitly written in order to ensure upward compatibility with the ex
isting language.
• JIGSAW is a module manipulation language introduced by Bracha and
Lindstrom [Bra92,BL92].The basic notion is that of a module and oper
ators can be seen as moduletomodule functions.JIGSAW's operator suite
supports mixins,encapsulation,multiple inheritance,and strong typing.
Amodule is a language construct that binds names to values through deni
tions.Names are not bound to types.Module can also contain declarations
which assign types to the attributes,without providing values for them,and
are used for dening abstract classes.Modules do not have fr ee variables.
They can be nested.
While JIGSAW is a typed language,its operators are dened in untyped
lambda calculus and typing constraints are deduced for module operations.
They do not need access to modules'denitions.Since module s are seen as
generators,operators are modelled as functions that operate on generators
and produce generators as results.
2.2.LITERATUREONMIXINS
23
There is a number of operators that can be used to modify modules.Mixin
composition is modelled by merge and override operations.In the rst case,
name conicts result in static error,while in the second one,lefthand mod
ule is modied by the righthand one,where the type of the res ult is taken
from the overriding module and it has to be the subtype of the type in the
module being overridden.It is also possible to:eliminate the conicting
attributes by rename operator,eliminate the attribute denition (but retain
its declaration) by restrict in order to achieve sharing,statically bind at
tribute references by freeze,control visibility by hide and show,and access
overridden denitions by copyas operator.
Typing in JIGSAWis structural.Modules have interfaces associated to them
which provide types for all visible attributes of the module.The subtyping
relation on interfaces is interface equivalence.
Object are produced instantiating modules,which is done by taking the
xedpoint of the module generator.
• Flatt et al.[FKF99] extend a subset of sequential Java called CLASSIC
JAVA with mixins and call it MIXEDJAVA.Only mixins and interfaces can
be declared,whereas classes can be seen as special cases of mixins where all
the components are dened.As opposed to C LASSICJAVA,where classes
are organized into class hierarchy,and new classes are produced by extend
ing the existing classes,in MIXEDJAVA the basis for inheritance is a mixin
hierarchy and new classes are produced by applying mixins to classes.
They distinguish two types of mixins,atomic and composite ones.Atomic
mixin denes a set of elds and methods that extend or/and red ene elds
and methods fromunspecied superclass.Mixin is not statically connected
to the superclass,but uses its inheritance interface to specify howthe inher
ited methods are extended and/or overridden.Mixin also implements one
or more interfaces.
A composite mixin does not have any new eld and method denit ions,
but combines two existing mixins in order to produce a new mixin with
different functionality.The lefthand mixin has a preced ence over the
righthand one which means that the method redenitions are taken from
the lefthand mixin according the lefthand mixin's inheri tance interface,
whereas the new denitions are taken from both mixins.Compos ition is
welldened only if the righthand mixin implements the lef thand mixin
inheritance interface (i.e.,the righthand mixin is required to provide all the
24
CHAPTER2.MIXINSINPROGRAMMINGLANGUAGES
methods expected by the lefthand one).A new mixin extends the right
hand mixin inheritance interface and implements all the inheritance inter
faces implemented by the composing mixins.
The duplication of method names during runtime is resolved with the run
time context information provided by the current view of the object (repre
sented as a chain of mixins).
It is possible to instantiate mixins with the new operator if they have all
the methods implemented,i.e.,they do not inherit any methods from the
superclass.
• Boudol [Bou01] extends Reference ML [WF94] with records and let rec
operator.Degrees (which are boolean information) are introduced into the
type system,distinguishing certainly safe frompossibly unsafe variables for
recursion from the typing context.Degrees apply also to functions select
ing out the functions that are protective towards their arguments and thus
safe for the recursion (since in the recursive record semantics of objects the
usage of let rec expression is unsafe).This enriched ML leads to a theoret
ically solid treatment of mixins,which are seen as class transformers and
are protective functions of their argument
self
.
• Ancona and Zucca [AZ98,AZ02] give a formal mathematical model for
mixin modules.A mixin is a function from input to output components,
i.e.,fromdeferred and virtual components to the components dened in the
module.They give an axiomatic/denotational characterisation of the oper
ators for composing mixins in order to obtain higherorder mixins.These
operations are:merge,restrict,override,hide,and functional composition.
It is showed that all these operations can be expressed using three primitive
operations (sum,reduct,freeze) which are characterized by the small set of
axioms.They also present a variety of method renaming forms,to deal with
different typologies of name collisions.
• In [LZ03] Ancona et al.present JAM,where the notion of mixin is inte
grated with Java,respecting Java design principles and type system con
straints.
In JAM,mixin declaration has two parts:components dened by the m ixin
and components expected from the superclass,labelled with inherited
modier.The latter methods must have the same return and arg ument type
and equivalent throws clause as the corresponding methods in the parent
2.2.LITERATUREONMIXINS
25
class.Unexpected and ambiguous overriding,as well as hiding,are all for
bidden in JAM.Mixin instantiation on classes can be explained by a copy
principle,i.e.,the newly obtained subclass behaves as if obtained by usual
inheritance,copying all the components from the superclass.Mixins can
implement interfaces,in the same way classes do.
Classes obtained by applying the same mixin to different classes are sub
classes of the corresponding mixin.This enables using common interface
to manipulate objects of any mixin instance.
JAM to Java translator ensures that JAM code can be executed on every Java
Virtual Machine.
One of the drawbacks of the approach in this work is that this cannot be
used as argument in method and constructor invocations inside a mixin.
Therefore,it is not possible to refer to the generic parent class or to the
generic heir class.Moreover,there is no support for mixin composition.
• Traits have been recently proposed by Sch¨arli et al.[SDNB03] as an al
ternative to class and mixin inheritance in order to enhance code reuse in
objectoriented programs.A trait is a collection of methods that can be
used as building blocks for assembling classes.It is a lan guage construct
that implements pure behaviour providing only a set of methods.It can also
expect some other methods that serve as parameters.A trait neither denes
nor directly accesses state variables.
Newclasses can be created by subclassing existing classes,possibly adding
a set of traits or composting a number of traits.Additionally,special glu
ing methods that connect the traits and state variables nee d to be provided.
When traits are composed (using symmetric sum,override,exclusion,and
aliasing operators) the conicting methods are resolved explicitly.Thus
traits can be used to extract reusable building blocks from classes,thereby
identifying different aspects of their behaviour.
The original calculus of traits,since intended as an extension of Smalltalk,
is untyped.A typed calculus of traits is proposed by Fisher and Reppy in
[FR04] as an attempt to integrate traits into a staticallytyped objectoriented
language.
26
CHAPTER2.MIXINSINPROGRAMMINGLANGUAGES
Chapter 3
Core calculus of classes and mixins
3.1 Overview
The rst part of this thesis extends The Core Calculus of Classes and Mixins of
[BPS99].When designing the calculus,the main goal was to nd a balanced
solution that has enough expressive power and a relatively simple type system.
Starting fromthe basic constructs like records and references,the components
that model classes and mixins were added,thus producing a calculus that supports
mixin inheritance,data encapsulation,structural subtyping,and modular object
creation.The main constructs introduced in the calculus are:
 class value classval,
 mixin expression mixin,
 mixin application ,
 instantiation expression new.
Mixins govern the inheritance mechanism which is achieved via mixin appli
cation.The class values are the products of mixin inheritance.The new construct
creates new objects fromthe existing classes.
The class value consists of a class generator,and two sets of method names,
public and protected.The generator function produces a function from
self
to
a record of methods.To this function,the xedpoint operat or can be applied at
instantiation time (when new constructor is applied) to bind
self
in method bodies
and produce an object.
A mixin expression consists of declarations of new and rede ned methods,as
well as the mixin constructor,described later.It also contains names of protected
methods,not modelled in the extensions presented in this work.
27
28
CHAPTER3.CORECALCULUSOFCLASSESANDMIXINS
Inheritance in the calculus is simulated by applying a mixin to a class value.
When creating a new (sub)class,mixin dictates the changes to the (super)class.
First,the superclass generator builds the record of its methods.Then the generator
of the new class is built by integrating the modications spe cied by the mixin
(method additions and/or replacements).
Instantiation is possible only on fullyedged classes,wh ile mixins serve only
as inheritance mechanism.
Objects are represented by recursive records of methods.Methods are func
tions that depend on two arguments,
eld
and
self
.A special parameter
self
is
bound in all method bodies to enable themto reference the host object.Recursive
reference to
self
is given only after resolving the inheritance,which permits the
xedpoint operator to be applied only once.Redening metho ds have three ar
guments:additional special keyword
next
is used to enable themto access the old
method body inherited fromthe superclass.
Constrained parameterization ensures static type checking.Each mixin dec
laration species to which class the mixin may be applied.Th e mixin declara
tion and mixin application are typed separately.The calculus supports structural
subtyping,hence the types of objects do not depend on the classes they were
instantiated from,which removes the dependency of object users on class imple
Enter the password to open this PDF file:
File name:

File size:

Title:

Author:

Subject:

Keywords:

Creation Date:

Modification Date:

Creator:

PDF Producer:

PDF Version:

Page Count:

Preparing document for printing…
0%
Commentaires 0
Connectezvous pour poster un commentaire