[PDF] [PDF] Compiling Polymorphism Using Intensional Type Analysis

and Quest 9], it is impossible to eliminate all polymorphism at compile-time Therefore, we view duplication and spe- cialization as an important optimization, but 



Previous PDF Next PDF





[PDF] Compile-Time Polymorphism in C++ :

9 fév 2000 · C++ ○ Polymorphism ○ Generic programming ○ POOMA 9 Compile-Time Polymorphism class TwoMult {}; class A { inline



[PDF] C++ Compile Time Polymorphism for Ray Tracing

Compile time polymorphism (CTP) (which is sometimes also referred to as static polymorphism [MS00]) is a means to imple- ment branching without having to explicitly specify every possible branch in library code



[PDF] Run Time Polymorphism Against Virtual Function in Object Oriented

compiler In this paper, we will discuss the role of Run Time Polymorphism and how it can A somehow derives from type B, or type C implements an interface



[PDF] POLYMORPHISM

to sayHi()'s entry point } void sayHi(){ cout



[PDF] Interface-based Programming in C++ - autosys

C++, Compiler Optimizations, Callgrind, Interface, polymorphism Abstract In many object oriented literature runtime polymorphism is often the only way 



[PDF] Compiling Polymorphism Using Intensional Type Analysis

and Quest 9], it is impossible to eliminate all polymorphism at compile-time Therefore, we view duplication and spe- cialization as an important optimization, but 



[PDF] Types, Polymorphism and Overloading - UiO

Compile-time or run-time checking can prevent Parametric Polymorphism: ML vs C++ ◇C++ function template • Declaration gives type of funct arguments 



[PDF] OOP (Object Oriented Programming) with C#: Dynamic Binding/ Run

Runtime Polymorphism or Late Binding or Dynamic Binding In simple C# language, In run time polymorphism or method overriding we can override a method in 



[PDF] Polymorphism in C++

In C++ polymorphism is mainly divided into two types: • Compile time Polymorphism • Runtime Polymorphism 1 Compile time polymorphism: This type of 

[PDF] compile time polymorphism in c++ language are

[PDF] compile time polymorphism in c++ language are mcq

[PDF] compile time polymorphism in python

[PDF] compile time polymorphism is achieved by

[PDF] compile time polymorphism is also known as

[PDF] compile time polymorphism vs runtime polymorphism

[PDF] compiler book

[PDF] compiler c++

[PDF] compiler construction tools pdf

[PDF] compiler definition

[PDF] compiler design

[PDF] compiler design ppt

[PDF] compiler error

[PDF] compiler pdf

[PDF] complementary slackness condition lagrangian

CompilingPolymorphismUsingIntensionalTyp eAnalysis ?Rob ert Harp er yGregMorrisett zScho ol of Computer ScienceCarnegie Mellon UniversityPittsburgh? PA 15213?3891Abstract

Traditional techniques for implementing p olymorphism useauniversal representation for ob jects of unknown typ e?Of?ten? this forces a compiler to use universal representationseven if the typ es of ob jects are known?We examine an al?ternative approach for compiling p olymorphism where typ esare passed as arguments to p olymorphic routines in order todetermine the representationofan ob ject?Thisapproachallows monomorphic co de to use natural? e?cient represen?tations? supp orts separate compilation of p olymorphic de??nitions and? unlike co ercion?based implementations of p oly?morphism? natural representations can b e used for mutableob jects such as refs and arrays?Weareparticularlyinterestedinthetypingprop ertiesof an intermediate language that allows run?time typ e anal?ysistobeco dedwithinthelanguage?Thisallowsustocompile many representation transformations and manylan?guage features without adding new primitive op erations tothe language?In this pap er? we provide a core target lan?guage where typ e?analysis op erators can b e co ded within thelanguage and the typ es of such op erators can b e accuratelytracked?The target language is p owerful enough to co de avariety of useful features? yet typ e checking remains decid?able?Weshowhow to translate an ML?like languageintothe target language so that primitive op erators can analyzetyp es to pro duce e?cient representations?We demonstratethe p ower of the ?user?level? op erators by co ding ?attenedtuples? marshalling? typ e classes? and a form of typ edynamicwithin the language?1Intro ductionManycompilersassumeauniversalor?b oxed?represen?tationofasinglemachinewordifthetyp eofavalueis

unknown?This allows the compiler to generate one simple?Thisworkwassp onsoredbytheAdvancedResearchPro jectsAgency?CSTO?underthetitle?TheFoxPro ject:Advanced De?velopment of Systems Software?? ARPA Order No?8313? issued byESD?AVS under Contract No? F19628?91?C?0168?y

E?mail: rwh?cs?cmu?eduz

E?mail: jgmorris?cs?cmu?edu

piece of co de to manipulate the value?But b oxed represen?tationsoftenrequiremorespaceandprovidelesse?cientaccess than natural representations?For example? an arrayofsmall unknown ob jects?such as b o oleansorcharacters?is represented as an arrayof words? wasting the ma jorityofthe space?An ob ject larger than a word? such as a double?precision ?oating?p ointvalue?is allo cated and a p ointer isused in place of the value?Consequently? accessing the valuerequiresanadditionalmemoryaccess?Aswordsizesin?crease from 32 to 64?bits? and memory latencies increase? itb ecomes increasingly imp ortant to minimize b oxing?Inmo dernprogramminglanguagessuchasMo dula?3?Standard ML ?SML?? and Haskell? unknown typ es and thusboxed representations arise b ecause of twokey language fea?tures:

typ es imp orted from a separately compiled programunit and typ es within p olymorphic routines?Polymorphicvalues are particularly troublesome b ecause we can simulta?neouslyviewthem as having any one of an in?nite numberof monomorphic typ es?For example? a p olymorphic routinethatmapsafunctionacrosstheelementsofanarraycanb e simultaneously seen as a function that works on b o oleanarrays and a function that works on real arrays?The routinecan thus b e used in place of a function that was compiledknowing whether the argument arraycontains b o oleansorreals?Consequently?monomorphicroutinesareforcedtouse the same representationsasp olymorphic routinesandthe entire program pays the price of the increased space andexecution?time overheads of the universal representations?1?1Co ercionImplementationsThe problem with p olymorphism stems from the assumption

thatviewinga p olymorphic value as a monomorphic valueshould have no computational e?ect?Recentwork byLeroy?30 ? and others ?41 ? 24 ? 43 ? has suggested that the instantia?tion of a p olymorphic value should corresp ond to arun?timecoercionfrom the universal representation to the appropri?atesp ecializedrepresentation?Atfunctiontyp es?thisre?quiresthedualco ercion?forthefunctionargument?thatconverts sp ecialized representations to the universal repre?sentation?For example? when the identity function of typ e8?:?!?isinstantiatedtohavetyp eint!int?aco er?cion is generated that takes an integer argument? b oxes it?passesittothe identity function?andunboxes theresult?This approachallows monomorphic co de to use the natural?e?cient representations?Leroy?s co ercions pro duce an isomorphic copyofadatastructure?Forexample?toco erceatuple?wepro jectthe

comp onents of the tuple? b ox?unbox them? and then form anew tuple?Unfortunately? copying co ercions are impracticalfor large data structures since the cost of making the copyof?ten outweighs the b ene?ts of the unboxed representation ?asp ointed out by Leroy ?30 ? page 184???More problematically?copying co ercions do not work for mutable data structuressuchasarrays?If wemake a copyof the value to b ox thecomp onents then up dates to the copy will not b e re?ectedin the original array and vice versa?1?2Typ ePassingAn alternative approach to co ercions? ?rst suggested by theNapier ?88 implementation ?37 ?? is to pass the typ es that areunknownatcompile?timetoprimitiveop erationsatlink?time or even run?time?Then the primitive op erations cananalyze the typ e in order to select the appropriate co de tomanipulate the natural representation of an ob ject?For ex?ample? a p olymorphic subscript function for arrays mightbecompiled into the following pseudo?co de:sub???:typ ecase?ofbool?b o olsubjreal?realsubj??boxedsub???Here?subis a function that takes atypeargument???? anddo esacaseanalysistodeterminethe appropriatesp ecial?ized subscript function that should b e returned?For exam?ple?sub?bool?returnstheb o oleansubscriptfunctionthatexp ects an array of bits? whilesub?real? returns the ?oatingp oint subscript function that exp ects a double?word alignedarray of ?oating p ointvalues?For all other typ es? we assumethe arrayhasboxed comp onents and thus return the b oxedsubscript function?If thesubop erationis instantiatedwith a typ e that isknown at compile?time ?or link?time?? then the overhead ofthe case analysis can b e eliminated by duplicating and sp e?cializingthe de?nition ofsubat the appropriate typ e?Forexample?thesourceexpression?subhx;4i?3:14?willbecompiledtothetargetexpression?sub?real?hx;4i?3:14?sincetheresultofthesubop erationisconstrainedtobeareal?Ifthede?nitionofsubisinlinedintothetargetexpressionandsomesimplereductionsarep eformed?thisyields the optimized expression ?realsubhx;4i?3:14??Thus?parameterizing the primitive op erations bytyp e provides asingle? consistent metho dology for typ e analysis at compile?time? link?time? and run?time?In languages where p olymorphic de?nitions are restrictedto ?computational values? ?essentially constants and func?tions?? p olymorphic de?nitions can always b e duplicated andsp ecialized or even inlined?Lazy languages suchasHaskellsatisfythisconstraint?andWrighthasdetermined empir?icallythatsucharestrictiondo esnote?ectthevastma?jority of SML programs ?52 ??Languages like core?SML andHaskell only allow p olymorphic values to arise as the resultofa?let?bindingandrestrictthetyp eofsuchvaluestob e prenex?quanti?ed? That is? the typ e must b e of the form8?1

;:::;?n

:?where?contains no quanti?er? Thus? the onlything that can b e done to a p olymorphic value is to instan?tiate it?Since the scop e of aletis closed?it is p ossible todetermine all of the instantiations of the p olymorphic valueat compile time and eliminateal lp olymorphism through du?plication andd sp ecialization?Such an approach is used? forinstance? by Blello chet al?in their NESL compiler ?6 ? and

more recently by Jones to eliminate Haskell overloading ?27 ??Furthermore? Jones rep orts that this approachdoesnotleadto excessive co de?blowup?Unfortunately? eliminating all of the p olymorphism in aprogramisnotalwaysp ossibleorpratical?Inparticular?there is no way to eliminate the p olymorphism when sepa?rately compiling a de?nition from its uses b ecause it is im?p ossible to determine the typ es at which the de?nition willp otentially b e used?This prevents us from separately com?piling p olymorphic libraries or p olymorphic de?nitions en?tered at a top?level lo op?Furthermore? in languages that al?low p olymorphic values to b e ??rst?class? such as XML ?21 ?and Quest ?9 ?? it is imp ossible to eliminate all p olymorphismatcompile?time?Therefore?weviewduplicationandsp e?cialization as an imp ortant optimization? but consider somerun?time typ e analysis to still b e necessary for practical lan?guage implementation?1?3Typ e?CheckingTyp eAnalysisIn this pap er? we showhow to compile ML?like p olymorphiclanguagestoatargetlanguagewhererun?time typ e anal?ysis maybeusedby the primitive op erations to determinethe representation of a data structure?We are particularlyinterestedinthetypingprop ertiesofalanguagethatal?lowsrun?timetyp eanalysis?Thesubde?nitionab oveisill?typ edinMLb ecauseitmustsimultaneouslyhavethetyp esb o olarrayint!bool?realarrayint!real?aswellas8?:???boxedarrayint!??Sinceb o olarrayandrealarrayare nullary constructorsandnotinstantiationsof???boxedarray?itisclearthatthereisnoMLtyp ethatuni?es all of these typ es?Our approach to this problem is to consider a typ e sys?tem that provides analysis of typ es via a typ e?level ?Typ e?case? construct?For example? thesubde?nition ab ovecanb e assigned a typ e of the form:8?:Sp clArray???int!?where the sp ecialized array constructorSp clArrayis de?nedusingTyp ecaseas follows:Sp clArray????Typ ecase?ofbool?boolarrayjreal?realarrayj?????boxedarrayThe de?nition of the constructor parallels the de?nition of

the term:If the parameter?is instantiated tobool?thenthe resulting typ e isb o olarrayand if the parameter is instan?tiated toreal? the resulting typ e isrealarray?In its full generality? our target language allows typ es tob e analyzed not just by case analysis? but also via primitiverecursion?Thisallowsmoresophisticatedtransformationsto b e co ded within the language? yet typ e checking for thetarget language remains decidable?An example of a moresophisticated translation made p ossible by primitiverecur?sion is one where arrays of tuples are represented as tuples ofarrays?For example? an arrayofboolrealis represented asa pair of aboolarrayand arealarray?This representation al?lows the b o olean comp onents of the array tobepacked andallowstherealcomp onentstobenaturallyaligned?Thesubscript op eration for this representation is de?ned usinga recursivetyp ecaseconstruct calledtyp erecin the following

manner:typ erecsub?bool??b o olsubjsub?real??realsubjsub??1 ?2 ??hhx; yi;ii:hsub??1 ?hx; ii;sub??2 ?hy; iiijsub????boxedsub???Ifsubis given a pro duct typ e??1 ?2

? it returns a functionthattakesapairofarrays?hx; yi?andanindex?i?andreturnsthe pairofvalues from b oth arrays atthatindex?recursively calling thesubop eration at the typ es?1

and?2

?The typ e of thissubop eration is:8?:RecArray???int!?where the recursive? sp ecialized array constructorRecArrayis de?ned using a typ e?level ?Typ erec?:Typ erecRecArray?bool??b o olarrayjRecArray?real??realarrayjRecArray??1

?2 ??RecArray??1 ?RecArray??2 ?jRecArray???????boxedarrayAgain? the de?nition of the constructor parallels the de?ni?

tion of thesubop eration?If the parameter is instantiated tobool? then the resulting typ e isb o olarray?If the parameteris instantiated with?1

?2 ? then the resulting typ e is thepro duct ofRecArray??1 ? andRecArray??2

??Run?time typ e analysis can b e used to provide other use?fullanguagemechanismsb esidese?cientrepresentations?Inparticular?adhocp olymorphicop erators?suchastheequalityop eratorofSML?oranoverloadedop eratorex?portedfromaHaskelltypeclass?canbedirectlyimple?mented in our target language without the need to tag val?ues?Furthermore? the static constraints of SML?s equalitytyp esandHaskell?styp eclassesmaybeco dedusingourTyp erecconstruct?Our target language is alsoableto ex?press?marshalling?ofdata structures and aform oftyp edynamic?In Section 2we describ ethe typ e?analysis approachtocompilation as a typ e?based translation from a source lan?guage?Mini?ML?toourtargetlanguage?

MLi ?Thekeyprop erties of MLi

are stated?and a few illustrative exam?ples involvingtyp erecandTyp erecare given? In Section 3 weshowhowmanyinteresting and useful language constructscan b e co ded usingtyp erec? including ?attened representa?tions? marshalling? typ e classes? and typ edynamic?In Sec?tion 4 we discuss related work? and in Section 5 we summa?rize and suggest directions for future research?2Typ e?DirectedCompilationIn order to take full advantage of typ e information duringcompilation?we consider translationsof typing derivationsfrom the implicitly?typ ed ML core language to an explicitly?typ ed target language? following the interpretation of p oly?morphism suggested by Harp er and Mitchell ?20 ?? The sourcelanguage is based on Mini?ML ?11 ?? which captures manyoftheessentialfeaturesoftheMLcorelanguage?Thetar?get language?

MLi ? is an extension of ML? also known asXML ?21 ?? a predicativevariant of Girard?sF! ?16 ? 17 ? 42 ??enriched with primitives for intensional typ e analysis?

2?1SourceLanguage:Mini?MLThe source language for our translations is a variantof Mini?ML ?11 ??The syntax of Mini?ML is de?ned by the followinggrammar:?monotypes??::?tjintj?1

!?2 j?1 ?2?polytypes?::??j8t:?terms?e::?xj?njhe1 ;e2 ij1 ej2 ejx: eje1 e2 jletx?vine?values?v::?xj?njhv1 ;v2

ijx: eMonotypes??? are either typ e variables ?t??int?arrowtyp es?or binary pro duct typ es?Polytypes?? ?also known astypeschemes? are either monotyp es or prenex quanti?ed typ es?Wewrite8t1

;:::;tn :?to represent the p olytyp e8t1 :???:8tn

:??ThetermsofMini?ML?e?consistofidenti?ers?numerals??n?? pairs? ?rst and second pro jections? abstractions? appli?cations? andletexpressions?Values ?v? are a subset of theterms and include identi?ers? integer values? pairs of values?and abstractions?The static semantics for Mini?ML is given in Figure 1 asaseriesofinferencerules?Therulesallowustoderiveajudgement of the form ?; ??e:?where ? is a set of freetyp e variables and ? is a typ e assignment mapping identi?ersto p olytyp es?We write ???t??

0to denote the substitution ofthe typ e?for the typ e variabletin the typ e expression?

0?Weuse ???

0to denote the union of two disjoint sets oftyp e variables? ? and ?

0? and ??fx:gto denote the typ eassignment that extends ? so thatxis assigned the p olytyp e? assumingxdo es not o ccur in the domain of ??Let?b ound expressions are restricted to values so that ourtranslation? whichmakes typ e abstraction explicit? is correct?see b elow??2?2TargetLanguage:

MLiThe target languageof our translations?

MLi ?is based on

ML?20 ?? a predicativevariant of Girard?sF!

?16 ? 17 ? 42 ??The essential departure from the impredicative systems ofGirard and Reynolds is that the quanti?er8t:ranges onlyover ?small? typ es?or ?monotyp es??which do not includethe quanti?ed typ es?This calculus is su?cientfor theinter?pretation of ML?style p olymorphism ?see Harp er and Mitchell?20 ? for further discussion of this p oint??The language

MLiextends

MLwithintensional?orstructural?19 ?? p olymor?phism? that allowsnon?parametric functionsto b ede?nedbyintensional analysis of typ es?The four syntactic classes for

MLi ?kinds?k?? construc?tors ???? typ es ??? and terms ?e?? are given b elow:?kinds?::??j1 !2?con?s??::?tjIntj!??1 ;?2 ?j??1 ;?2 ?jt:::?j?1 ??2 ?jTyp erec?of??i j?! j? ??types?::?T???jintj1 !2 j1 2 j8t:::?terms?e::?xj?njx::ej? e 1 e2 jhe1 ;e2 i 1 ;2j 1 ;21 ej 1 ;22 ej?t::: eje???jtyp erec?of?t:??ei je! je

?Kinds classify constructors? and typ es classify terms?Con?structorsofkind?name?smalltyp es?or?monotyp es??The monotyp es are generated fromIntand variables bythe

?var?

FTV???n

?tn ?t1 ?; ??fx:8t1 ;:: :;tn :?g?x:??n ?tn ???? ????1 ?t1 ?int??; ???n:int?pair? ?; ??e1 :?1 ?; ??e2 :?2 ?; ??he1 ;e2 i:?1 ?2 ?; ??e:?1 ?2?; ??i e:?i ?i?1;2??abs? ?; ??fx:?1 g?e:?2 ?; ?? x: e:?1 !?2 ?app? ?; ??e1

0!??; ??e2

0?; ??e1

e2 :??let? ??ft1 ;:::; tn g;??v:?

0?; ??fx:8t1

; :::;tn

0g?e:?

?; ??letx?vine:?Figure 1:Mini?ML Typing Rules constructors!and? The application and abstraction con?structors corresp ond to the function kind1 !2 ?Typ esin MLi

include the monotyp es? and are closed under pro d?ucts? function spaces? and p olymorphic quanti?cation?Wedistinguishconstructorsfromtyp es?writingT???forthetyp e corresp onding to the constructor??The terms are anexplicitly?typ ed?calculus with explicit constructor abstrac?tion and application forms?The o?cial syntax of terms shows that the primitiveop?erations of the language are provided with typ e informationthatmaybeusedatrun?time?Forexample?thepairingop erationishe1

;e2 i 1 ;2?whereei :i

?re?ectingthe factthat there is ?p otentially? a pairing op eration at each pairof typ es?In a typical implementation? the pairing op erationisimplementedbycomputingthesizeofthecomp onentsfrom the typ es? allo cating a suitable chunk of memory? andcopying the parameters into that space?However? there isnoneedtotagtheresultingvaluewithtyp einformationb ecause the pro jection op erations ?

1 ;2i

e? are corresp ond?ingly indexed bythetyp es of the comp onents so that the ap?propriate chunk of memory can b e extracted from the tuple?Similarly? the application primitive??

e 1 e2 ? is indexed bythe domain typ e of the function

1and is used to determinethe calling sequence for the function?Of course?primitiveop erations can ignore the typ e if a universal representationis used?Consequently? the implementor can decide whetherto use a natural or universal representation?Weuseasim?pli?ed term syntax without the typ es when the informationis apparent from the context?However?it is imp ortanttob ear in mind that the typ e information is present in the fullyexplicit form of the calculus?TheTyp erecandtyp erecformsprovidetheabilitytode?neconstructorsandtermsbystructuralinductiononmonotyp es?These forms may b e thought of as eliminatoryforms for the kind ? at the constructor and term level??Theintro ductory forms are the constructors of kind ?; there areno intro ductory forms at the term level in order to preservethe phase distinction ?8 ? 21 ???At the term leveltyp erecmayb e thought of as a generalization oftyp ecasethat providesforthede?nitionofaterm by inductiononthestructureof a monotyp e?At the constructor levelTyp erecprovides asimilarability to de?ne a constructor by induction on the

1In general? application could also dep end up on the range typ e?but our presentation is simpli?ed greatly by restricting the dep en?dency to the domain typ e?

structure of a monotyp e?Thestaticsemanticsof MLi

consistsofacollectionofrules for deriving judgements of the following forms? where? is a kind assignment? mapping typ e variables ?t? to kinds?and?is a typ e assignment? mapping term variables to typ es????::?is a constructor of kind???1

?2 ::?1 and?2 areequivalent constructors??is a valid type??1 2 1 and2

areequivalent types?; ??e:eis a term of typeTheformationrulesforconstructorsarelargelystan?dard? with the exception of theTyp erecform:???:: ????i

??Typ erec?of??i j?! j?

?::The whole constructor has kindif the constructor to b eanalyzed??? is of kind ? ?i?e?? a monotyp e???i

is of kind?and?! and?

are eachofkind?!?!!!?The constructor equivalence rules ?see Figure 2? axiom?atizede?nitional equality?47 ? 31? of constructors to consistof??conversion together with recursion equations governingtheTyp erecform?Conceptually?Typ erecselects?i

?or?

according to the head?constructor of the normal form of?and passes it the comp onents of?and the ?unrolling? oftheTyp erecon the comp onents?The level ofconstructorsand kinds is a variation of G?odel?sT?18 ??Every construc?tor???has a unique normal form?NF????with resp ecttothe obvious notion of reduction derived from the equivalencerules of Figure 2 ?47 ??This reduction relation is con?uent?from which it follows that constructor equivalence is decid?able ?47 ??The typ e formation? typ e equivalence? and term forma?tion rules for

MLi

are omitted due to lack of space? but canb e found in a previous rep ort ?22 ??The rules of typ e equiv?alencede?ne theinterpretationT???oftheconstructor?as a typ e?For example?T?Int?intandT?!??1

;?2 ??T??1 ?!T??2

??Thus?Ttakes us from a constructor whichnamesatyp e to the actual typ e?The term formation rulesare standard with the exception of thetyp erecform? which

??ft:: 0g??1 ::???2 0 ???t:: 0:? 1 ???2 ???2 ?t??1 ???i :: ?!?!!!??Typ erec Intof??i j?! j? ??i ::???1 :: ????2 :: ????i ??Typ erec?!??1 ;?2 ??of??i j?! j? ?1 ?2 ?Typ erec?1 of??i j?! j? ?? ?Typ erec?2 of??i j?! j? ?? ::??Typ erec???1 ;?2 ??of??i j?! j? ?1 ?2 ?Typ erec?1 of??i j?! j? ?? ?Typ erec?2 of??i j?! j?

Figure 2:Constructor Equivalence

is governed by the following rule:???:: ???ft:: ?g??; ??ei :?Int?t??; ??e! :8t1 ;t2 ::?:?t1 ?t?!?t2 ?t?!?!?t1 ;t2 ??t??; ??e :8t1 ;t2 ::?:?t1 ?t?!?t2 ?t?!??t1 ;t2 ??t? ?; ??typ erec?of?t:??ei je! je

?:???t?The argument constructor?must b e of kind ?? and the re?sult typ e of thetyp erecexpression is determined as a func?tion ofthe argument constructor?namely the substitutionof?fortin the typ e expression?The ??t:?? lab elpro?videsthetyp einformationneededtochecktheconstructwithoutinfererence?Typicallytheconstructorvariableto ccurs inas the argumentof aTyp erecexpression so that???t?isdetermined byarecursiveanalysisof??Similarto normalization of aTyp erecconstructor? the evaluation ofatyp erecexpression selectsei

?e ?ore!

according to thehead constructor of the normal form of?and passes it thecomp onents of?and the ?unrolling? of thetyp erecon thecomp onents?Typ e checking for

MLi

reduces to equivalence checkingfortyp esandconstructors?Inviewofthedecidabilityofconstructorequivalence?wehavethefollowingimp ortantresult:Prop osition2?1It is decidable whether or not?; ??e:is derivable in

MLi ?To?xtheinterpretation oftyp erec?we sp ecify a call?by?value? natural semantics for MLi

as a relationof the forme?!vwherevis a closed ?with resp ect to b oth typ e andvaluevariables??syntacticvalue?Valuesarederivedfromthe following grammar:v::??njx::ejhv2

;v2 i 1

;2j?t::: eTyp e abstractions are values? re?ecting the fact that evalu?ation do es not pro ceed under ??Figure 3 de?nes the evaluation relation with a series ofaxioms and inference rules?The semantics uses an auxiliaryjudgment???!?

0? ?not formally de?ned here? that deter?mines the normal forms of constructors?During evaluation?we only need to determine normal forms of closed construc?tors of kind ??This amounts to evaluating constructors ofthe formTyp erec?:::? and ??1

??2

?? byorienting the equiva?lences of Figure 2 to the right and adding the appropriatecongruences?The rest of the semantics is standard except for the eval?uationofatyp erecexpressionwhichpro ceedsasfollows:

First? the normal form of the constructor argument is deter?mined? Once the normal form is determined? the appropriatesub expression is selected and applied to any argument con?structors?The resulting function is in turn applied to the?unrolling? of thetyp erecat each of the argument construc?tors?Some simple examples usingtyp erecmay b e found atthe end of this subsection?The semantics uses meta?level substitution of closed val?ues for variables and closed constructors for typ e variables?Inalower?levelsemanticswheresubstitutionismadeex?plicit?an environmentwould b e needed not only for valuevariables? but also for typ e variables?Tolmach ?51 ? describ esmany of the issues involved in implementing such a language?Prop osition2?2 ?Typ e Preservation?If;;;?e:ande?!v? then;;;?v:?Byinsp ectionofthevaluetypingrules?onlyappropriatevalueso ccupyappropriatetyp esandthusevaluationwillnot ?gowrong??In particular?itis p ossibleto showthatwhen evaluating well?typ ed programs? we only use theprojevaluation rule when

01 1 and 02 2 and we only usetheapprule when

0?Furthermore? programs writteninpure

MLi

?i?e??withoutgeneralrecursionop eratorsorrecursivetyp es? always terminate?Prop osition2?3 ?Termination?Ifeis an expression suchthat;;;?e:? then there exists a valuevsuch thate?!v?Afewsimpleexampleswillhelptoclarifytheuseoftyp erec?The functionsizeofof typ e8t::?:intthat computesthe ?size? of values of a typ e can b e de?ned as follows?sizeof??t:: ?:typ erectof?t

0:int??ei

je! je ?where e i ?1e ??t1 :: ?:?t2 ::?:x1 :int:x2 :int: ?1e ??t1 :: ?:?t2 ::?:x1 :int:x2 :int:x1

?x2?Here we assume that arrowtyp es are b oxed and thus havesize one??It is easy to checkthatsizeofhas the typ e8t::?:int?Notethatinaparametricsettingthistyp econtainsonlyconstant functions?As another example? Girard?s formulation of SystemF?16 ?includes a distinguished constant0?

of typ e?for eachtyp e??including variable typ es??Wemay de?ne an analogue ofthese constants usingtyp erecas follows:zero??t:: ?:typ erectof?t

0:T?t

0???ei

je! je ?val?v?!v?pair? e 1 ?!v1 e2 ?!v2 he1 ;e2 i 1 ;2?!hv1 ;v2 i 1 ;2 ?proj? e?!hv1 ;v2 i 01 02 1 ;2i e?!vi ?i?1;2??app? e 1 ?!x: 0:ee2 ?!v 0?v

0?x?e?!v

e 1 e2 ?!v ?tapp? e?!?t::: e

0???t?e

0?!ve????!v

?trec?int? ??!Intei ?!vtyp erec?of?t:??ei je! je ??!v?trec?fn? ??!!??1 ;?2 ?typ erec?1 of?t:??ei je! je ??!v1typ erec?2 of?t:??ei je! je ??!v2? ??2 ?t???quotesdbs_dbs17.pdfusesText_23