• Aucun résultat trouvé

Abstract Machines for Open Call-by-Value

N/A
N/A
Protected

Academic year: 2021

Partager "Abstract Machines for Open Call-by-Value"

Copied!
34
0
0

Texte intégral

(1)

HAL Id: hal-02415780

https://hal.archives-ouvertes.fr/hal-02415780

Submitted on 17 Dec 2019

HAL is a multi-disciplinary open access

archive for the deposit and dissemination of

sci-entific research documents, whether they are

pub-lished or not. The documents may come from

teaching and research institutions in France or

abroad, or from public or private research centers.

L’archive ouverte pluridisciplinaire HAL, est

destinée au dépôt et à la diffusion de documents

scientifiques de niveau recherche, publiés ou non,

émanant des établissements d’enseignement et de

recherche français ou étrangers, des laboratoires

publics ou privés.

Abstract Machines for Open Call-by-Value

Beniamino Accattoli, Giulio Guerrieri

To cite this version:

Beniamino Accattoli, Giulio Guerrieri. Abstract Machines for Open Call-by-Value. Science of

Com-puter Programming, Elsevier, 2019, 184, �10.1016/j.scico.2019.03.002�. �hal-02415780�

(2)

Contents lists available atScienceDirect

Science

of

Computer

Programming

www.elsevier.com/locate/scico

Abstract

machines

for

Open

Call-by-Value

,

✩✩

Beniamino Accattoli

a

,

Giulio Guerrieri

b

,

aINRIA,UMR7161,LIX,ÉcolePolytechnique,Palaiseau,France

bUniversityofBath,DepartmentofComputerScience,Bath,UnitedKingdom

a

r

t

i

c

l

e

i

n

f

o

a

b

s

t

r

a

c

t

Articlehistory:

Received17February2018

Receivedinrevisedform17January2019

Accepted8March2019

Availableonline15March2019

Keywords: Lambda-calculus Costmodel Complexity Sizeexplosion Implementation

The theory ofthe call-by-value λ-calculus relies on weak evaluation and closed terms, that are natural hypotheses in the study of programming languages. To model proof assistants, however,strongevaluation andopentermsare required.Opencall-by-value is

theintermediatesettingofweak evaluationwith(possibly)openterms,ontop ofwhich GrégoireandLeroydesignedoneoftheabstractmachinesofCoq.Thispaperprovidesa theoryofabstractmachinesforthefireballcalculus,thesimplestpresentationofopen call-by-value.

The literature contains machines that are eithersimple but inefficient, as theyhave an exponentialoverhead,orefficient butheavy,astheyrelyonalabeling ofenvironmentsand atechnicaloptimization.Weintroduceamachinethatissimple andefficient:itdoesnot uselabelsanditimplementsthefireballcalculuswithinabilinearoverhead.Moreover,we provideanewfineunderstandingofhowdifferentoptimizationsimpactonthecomplexity oftheoverhead,andevidencethatthetimecostmodelweworkwithisminimal.

©2019PublishedbyElsevierB.V.

1. Introduction

The

λ

-calculus is thecomputational modelbehind functional programminglanguagesandproof assistants. Its elegant definitionisbasedonjustone import-step computationalrule,

β

-reduction,anddoesnotrestonanynotionofmachineor automaton.Compilersandproofassistantshoweverareconcretetoolsthatimplementthe

λ

-calculusinsomeway—a prob-lemclearlyarises.Thereisahugegapbetweentheabstractmathematicalsettingofthecalculusandthetechnicalintricacies ofanactualimplementation.Thisiswhytheissueofimplementationisstudiedviaintermediateabstractmachines,thatare implementationschemeswithmicro-step operationsandwithouttoomanyconcretedetails.

Closedandstrong

λ

-calculus.Functionalprogramminglanguagesare basedon asimplified formof

λ

-calculus, that welike tocall closed

λ

-calculus,withtwo importantrestrictions.First,evaluationisweak,i.e. itdoesnot evaluatefunctionbodies (untiltheirformalparametersarereplacedbyactualarguments,ifany).Second,termsareclosed,thatis,theyhavenofree variables.Thetheoryoftheclosed

λ

-calculusismuchsimplerthanthegeneralone(e.g.,seepp.2–3).

Proofassistantsbasedonthe

λ

-calculususuallyrequirethepowerofthefulltheory.Evaluationisthenstrong,i.e. without thetwoaboverestrictions,andthedistinctionbetweenopenandclosedtermsnolongermakes sense,becauseevaluation

Thisisarevisedandextendedversionof [8].

✩✩ Thisworkispartofawiderresearcheffort,theCOCAHOLAproject(https://sites.google.com/site/beniaminoaccattoli/coca-hola).

*

Correspondingauthor.

E-mailaddresses:[email protected](B. Accattoli),[email protected](G. Guerrieri). https://doi.org/10.1016/j.scico.2019.03.002

(3)

hastodealwiththeissuesofopentermseveniftermsareclosed,whenitentersfunctionbodies.Werefertothissetting asthestrong

λ

-calculus.

Historically, the study of strong andclosed

λ

-calculi have followed orthogonal approaches. Theoretical studies rather dealtwiththestrong

λ

-calculus,anditisonlysincetheseminalworkofAbramskyandOng[1] thattheoreticiansstarted to takethe closedcaseseriously.Dually,practical studiesmostly ignoredstrongevaluation, withthenotableexception of Crégut[19] andsomerecentwork[25,13,2].Strongevaluationishoweveressentialintheimplementationofproofassistants orhigher-orderlogicprogramming,typicallyfortype-checkingwithdependenttypesasintheEdinburghLogicalFramework [28] ortheCalculusofConstructions[18],andforunificationinsimplytypedframeworkslike

λ

-Prolog [29].

Open call-by-value.In recent work [7], we advocated the relevance of the open

λ

-calculus, a framework in between the closedandthestrongones,whereevaluationisweak but termsmaybeopen.Its keypropertyisthatthestrongcasecan be described asthe iterationof theopen one intofunction bodies.The samecannot be done withtheclosed

λ

-calculus because—asalreadypointedout—enteringfunctionbodiesrequirestodealwith(locally)openterms.

Theopen

λ

-calculusdidnotemergebeforebecausemosttheoreticalstudiesfocusonthecall-by-name strong

λ

-calculus, andincall-by-nametheopen/closeddistinctiondoesnotplayan importantrole.Suchadistinction,instead,isdelicatefor call-by-value (CbVforshort)evaluation,1wherePlotkin’soriginaloperationalsemantics[31] isnotadequateforopenterms. Wediscussedthisissueatlengthin[7],wherefourextensionsofPlotkin’ssemanticsto(possibly)opentermsarecompared andshowntobeequivalent.ThatpaperthenintroducestheexpressionOpenCall-by-Value (shortenedOpenCbV)toreferto themasawhole,aswellasClosedCbV andStrongCbV toconciselyrefertotheclosedandstrongCbV

λ

-calculi.

Thefireballcalculus.The simplestpresentationofOpenCbV(see Proposition 1-2 inSect.2) isthefireballcalculus

λ

fire,

ob-tainedfromtheCbV

λ

-calculusbygeneralizingvaluesintofireballs.Dynamically,

β

-redexescanfireonlywhentheargument isafireball(fireball isapunonfire-able).Fireballsextendvaluesbyaddinginertterms,whicharetermsof(recursive)form xf1

. . .

fn,wherethe fi’sarefireballs.Inerttermsarealwaysopen,andsofireballsaresimplyabstractionsinClosedCbV—

notably,then,onclosedterms

λ

firecoincides withPlotkin’s(Closed)CbV

λ

-calculus.

ThefireballcalculuswasintroducedwithoutanamebyPaoliniandRonchiDellaRocca[30,32],thenrediscovered inde-pendentlyfirstbyGrégoireandLeroy[27],andthenbyAccattoliandSacerdotiCoen[10],whoalsonamedit.

Coqby(open)levels.In2002, GrégoireandLeroyusedthefireballcalculustoimprovetheimplementationoftheCoqproof assistant[27].TheyimplementedStrongCbVbyfactoringsuch ataskthroughOpenCbV.Theydesignan abstractmachine forthefireballcalculus—thatinourpaperiscalledOpenGLAM(seeSect.4fordetails)—andtheniterateittoevaluateStrong CbV by(open)levels: theOpen GLAMis first executed attop level(thatis, out ofall abstractions), andthenre-launched recursively under abstractions.Their studyis itself formalized in Coq, butit lacks an estimation of theefficiency ofthe machine.ItturnsoutthattheOpenGLAMisinefficient,tothepointofbeingunreasonable.

Inordertocontinueourstorysomebasicfactsaboutcostmodelsandabstractmachineshavetoberecalled(see[3] for agentletutorial,and[4] foramoregeneralperspectiveaboutreasonablecostmodelsforthe

λ

-calculus).

Interlude1:sizeexplosion. In

λ

-calculi, thenumberof

β

-stepsisthenaturalcandidateasa timecostmodel.However, itis well-known that

λ

-calculi sufferfroma degeneracy calledsizeexplosion: thereare families ofterms whosesize is linear inn, thatevaluateinn

β

-steps, andwhoseresulthassize exponentialinn.So,thenumberof

β

-stepsdoesnotseem to be areasonable costmodel,becauseitdoesnotevenaccountforthetimetowritedowntheresultofacomputation—the macro-step character of

β

-reductionseems toforbid tocount 1foreach

β

-step.Thisproblemaffectsall

λ

-calculiandall evaluationstrategies.

Interlude2:reasonablecostmodelsandabstractmachines.Despitesizeexplosion,surprisingly,formanystrategiesthenumber of

β

-stepsis areasonabletimecostmodel,sothateachsingle

β

-stepcanbeseenasanelementarycomputation stepand counted as1insuch a model.There isno contradiction:

λ

-calculi can be simulatedinalternative formalismsemploying someformofsharing,suchasabstractmachines.Thesesettingsmanageacompactrepresentationofterms(inparticular,of theresultofevaluation)viamicro-step operations,avoidingsizeexplosion.Showingthatacertain

λ

-calculusisreasonableis usuallydonebysimulatingitwithareasonable abstractmachine,i.e. amachineimplementableonarandomaccessmachine withasymptoticoverheadpolynomial intwo parameters:thenumberof

β

-stepsinthecalculusandthesizeoftheinitial term.Iftheoverheadisbilinear (i.e. linearinbothparameters),themachineandthecalculusitimplementsareefficient.

The designofareasonable abstractmachine dependsvery muchonthekindof

λ

-calculusto beimplemented,as dif-ferent calculiadmit differentformsofsizeexplosionand/or requiremoresophisticatedformsofsharing.Forstrategiesin the closed

λ

-calculus it is enough to use the ordinary technologyfor abstract machines, asfirst shown by Blelloch and

1 InCbVevaluation,afunction’sargumentsareevaluatedbeforebeingpassedtothefunction,sothatβ-redexescanfireonlywhentheirargumentsare

(4)

Greiner [17] (1995),andthenby Sands,Gustavsson,andMoran[33] (2002),and,withothertechniques,bycombiningthe resultsofDalLagoandMartini [20] and[21] (2009).

Letuspointoutsomedetails.Ordinaryabstractmachines(AM)forClosedCbVprovidereasonableimplementations(up tosharing)onrandomaccessmachines(RAM)withabilinear overhead(thatis,linearinthenumberof

β

-stepsand inthe sizeoftheinitialterm,sotheseimplementationsareactuallyefficient).Thesituationcanbedepicted as follows:

Closed CbV RAM AM

bilinear

bilinear bilinear (1)

Withanattentivechoiceofthedatastructuresitisalsopossibletobelogarithmic inthesizeoftheinitialterm,asrecently shownbyAccattoliandBarras[5].

Thecaseofthestrong

λ

-calculusissubtlerandamoresophisticatedsharingisnecessary,asshownbyAccattoliandDal Lago[6].ThetopicofourpaperisthestudyofreasonableabstractmachinesfortheintermediatecaseofOpen CbV. Fireballisreasonable.AccattoliandSacerdotiCoen[10] studiedOpenCbVfromthepointofviewoftimecostmodels.Their workprovidesthreecontributions:

1. Opensizeexplosion:theyshow thatOpen CbVissubtlerthanClosed CbVbyexhibitinga formofsize explosionthat is notpossible inClosed CbV,making Open CbVcloserto StrongCbV ratherthan toClosed CbV. Essentially,thismeans thatordinaryabstractmachinesforOpenCbVdonotprovidereasonableimplementations.ForGrégoireandLeroy’sOpen GLAMthefollowingdiagramholds:

Open CbV /λfire RAM Open GLAM

exponential

bilinear exponential (2)

2. Fireballsarereasonable: they showthat the numberof

β

-steps in

λ

fire isnonetheless a reasonable time cost modelby

exhibitingarefinedabstractmachine,calledGLAMOUr,thattheyprovetobereasonable;

3. Andevenefficient: they also optimizetheGLAMOUr into theUnchaining GLAMOUr, withabilinear overhead,recasting diagram (1) in Open CbV:

Open CbV /λfire RAM Unchaining

GLAMOUr

bilinear

bilinear bilinear (3)

Thisisanoptimal solution.Thespeed-upshownbyAccattoliandBarras[5] (loweringthedependenceonthesizeofthe initialtermtologarithmic)isspecifictotheevaluationofclosedtermsanddoesnotlifttoopenterms.

ThefineartofimplementingOpenCbV. Here we introduce two newabstract machines, the Easy GLAMOUr (in Sect. 5–6) andthe Fast GLAMOUr (in Sect. 7), that are proved to be correctimplementations of Open CbV (more precisely, ofthe right-to-leftevaluationstrategyin

λ

fire,definedinSect.2)withapolynomialandbilinearoverhead,respectively.Ourstudy

refinestheresultsofAccattoliandSacerdotiCoen[10] alongfouraxes:

1. Simplermachines: both the GLAMOUr and the Unchaining GLAMOUr of [10] are sophisticated machines relying on a labelingofterms.Theunchainingoptimizationofthesecondmachineisalsoquiteheavy.Both theEasyGLAMOUrand theFastGLAMOUr,instead,donotneedlabelsandtheFastGLAMOUrisbilinearwithouttheunchainingoptimization. 2. Simpleranalyses:thecorrectnessandcomplexityanalysesofthe(Unchaining)GLAMOUraredevelopedin[10] thanksto

aninformativebutcomplexdecompositionviaexplicitsubstitutions,bymeansofthedistillationmethodology[12].Here, instead,wedecodetheEasyGLAMOUrandtheFastGLAMOUrdirectlytothefireballcalculus,thatturnsouttobemuch simpler.Moreover,thecomplexityanalysisoftheFastGLAMOUr,surprisingly,turnsouttobestraightforward.

3. Modulardecompositionoftheoverhead:weprovideafineanalysisofhowdifferentoptimizationsimpactonthecomplexity oftheoverheadofabstractmachinesforOpenCbV,andhowtheycanbemodularlycomposed,withmodulareffectson theoverhead.Inparticular, we showthat an optimizationconsidered essential in[10], namelysubstitutingabstractions on-demand,isnotmandatoryforreasonablemachines—theEasyGLAMOUrdoesnotimplementitandyetitisreasonable. 4. UnderstandingStrongCbV:we avoid—onpurpose—thestudyofStrongCbV,andyetourstudyprovidesinsightsintothe complexityofimplementingit,independentlyofhowitisdefined.Weshow,indeed,thatsubstitutingabstractions on-demandcanbeavoidedonlyaslongasonestaysinside OpenCbV,whereasitismandatory forStrongCbV.Substituting abstractionson-demand is an optimization introduced by Accattoli and Dal Lago [6] and currentlyno proof assistant implementsit.Saiddifferently,ourworkshowsthatthetechnologycurrentlyinuseinproof assistantsis,atleast theo-retically,unreasonable.

(5)

Table 1

Thefireballcalculusλfire.

Terms t,u,s,r::=x| λx.t|tu

Fireballs f,f,f::= λx.t|i

Inert Terms i,i,i::=x|i f

Evaluation Contexts C::= · |tC|Ct

Rule at Top Level Contextual closure

(λx.t)(λy.u)→βλt{x λy.u} Ct →βλCuif t→βλu

(λx.t)i→βit{x i} Ct →βiCuif t→βiu

Reduction →βf:= →βλ∪ →βi

Summingup,ourworkdoesnot improvetheknownboundontheasymptoticoverheadofabstractmachinesforOpen CbV,astheoneobtainedin[10] isalreadyoptimal.Ourcontributionsinsteadareasimplificationandafinerunderstanding ofthesubtletiesofimplementingOpen CbV:weintroducesimpler butstillreasonable (andinsomecasesevenefficient,as in[10])abstractmachineswhosecomplexityanalysesare elementary,andwecarry anewmodularviewofhowdifferent optimizations impact on the (asymptotic)complexity ofthe overhead.In particular, while [10] shows that Open CbV is subtlerthanClosedCbV,hereweshowthatOpenCbVissimplerthanStrongCbV,andthatdefiningStrongCbVasiterated OpenCbV,asdonebyGrégoireandLeroy[27],mayintroduceanexplosionoftheoverhead,ifdonenaively.

Thisjournalpaperisarevisedandextendedversionof[8].Theadditionswithrespectto[8] are:

Proofs:detailedproofsofallclaims(exceptforsomeonesalreadyprovedintheliterature).Someproofsthatare straight-forwardortriviallyobtainedfromverysimilaronesinthebodyofthispaperaremovedtoAppendixB.

Relatedmachines: definitions and explanations of the abstract machinesclosely related to the new ones, namely the simplebutunreasonableone by Grégoire andLeroy [27], reformulatedaccordingto ourconventionsandnamedOpen GLAM(inSect.4),andthereasonablebutcomplexonesbyAccattoliandSacerdotiCoen[10],namelytheGLAMOUrand theUnchainingGLAMOUr(inSect.9).

Examplesandinsights:weprovidemoreexamplesofmachineexecutionstogetherwithrefinedexplanationsandinsights. In particular, we stress the commutation between evaluation and the substitution of inert terms as the key abstract propertyleadingtoreasonablemachinesforOpenCbV.

Minimalityofthecostmodel:formal evidence that the number ofsteps inthe fireball calculus is a minimal time cost model(inSect.10).Technically speakingwedonot proveminimality—thatwouldrequirea proofofthenon-existence of asymptotically faster implementations, and it is not even clear how one could prove it. Nonetheless, our rigorous examplesshowthatamoreparsimoniouscostmodelwouldrequiresomeradicallystrongerimplementationtechnology. Attheendofthepaper,AppendixAcontainsaglossaryofrewritingtheoryandtheexplanationofsomenotations.

2. Thefireballcalculus

λ

fire&opensizeexplosion

Inthissectionweintroducethefireballcalculus

λ

fire,thepresentationofOpenCbVweworkwithinthispaper,andshow

theexampleofsizeexplosionparticulartotheopensetting.WestudiedalternativepresentationsofOpenCbVin[7,9]. Thefireballcalculus.The fireball calculus

λ

fire is definedin Table1. Theidea is that thevalues ofthe CbV

λ

-calculus—i.e.

abstractions

λ

x

.

t and variables x

,

y

,

z

. . .

—are generalized to fireballs, by extending variables to more general inertterms. Actuallyfireballs(noted f

,

f

,

. . .

)andinertterms(notedi

,

i

,

. . .

)aredefinedbymutualinduction(inTable1).Forinstance,

λ

x

.

y isafireballasanabstraction,whilex, y

x

.

x

)

,xy,and

(

z

x

.

x

))(

zz

)(λ

y

.(

zy

))

arefireballsasinertterms.Allandonly thetermsoftheformxf1

. . .

fn (wheren

0 andallthe fi’sarefireballs)areinert.Themainfeatureofinerttermsisthat

they areopen (withafree “headvariable”),normal(withrespecttoweak evaluation,seebelow),andwhenpluggedina contexttheycannotcreatearedex(inparticular,theyarenotabstractions),hencethename.2

Applicationisleft-associative,sotur standsfortheterm

(

tu

)

r.Termsarealwaysidentifiedupto

α

-equivalenceandthe setoffreevariablesofatermt isdenotedby

fv

(

t

)

:wesaythatt isclosed if

fv

(

t

)

= ∅

,otherwiset isopen.Weuset

{

x u

}

forthetermobtainedbythecapture-avoidingsubstitutionofu foreachfreeoccurrenceofthevariablex int.

Todefineevaluationin

λ

fire,weuseevaluationcontexts (notedC ),i.e. termswithexactlyoneoccurrenceofthehole

·

,

anadditionalplace-holder.WeuseC



t



forthetermobtainedbyreplacingthehole

·

inthecontextC withtheterm t. Evaluation is givenby (non-deterministic) call-by-fireball

β

-reduction

βf: the

β

-rulecan fire, lighting the argument, onlyiftheargumentisafireball(fireball isacatchierversionoffire-able term).Weactuallydistinguishtwosub-rules:one

2 Intheliteraturethereisasimilarnotion,neutralterm,notablyinGirard’sversionofreducibilitycandidates[26] whereitdenotesatermthatisnot

anabstraction.However,theexpressionneutral often(e.g. see[13])referstotermsthatfurthermoreare(strongly)β-normal.Inerttermsareyetanother

notion(non-abstractionsthatareweaklyβ-normal,thatis,therecanbeβ-redexesunderabstractions),whichiswhyweavoidcallingthemneutral.In

(6)

thatlights abstractions,noted

→

βλ,andonethatlights inertterms,noted

→

βi (seeTable1).Reductions

βλ and

βi are justtheclosureoftheroot-steps

→

βλ and

→

βi,respectively,underevaluationcontextsC .Reduction

βf isdefinedasthe unionof

βλ and

βi,orequivalently,astheclosureoftheroot-step

→

βf

= →

βλ

→

βi underevaluationcontexts. Note that,accordingtothedefinitionofevaluationcontexts C ,evaluationisweak (i.e. itdoesnotreduceunderabstractions). Mainpropertiesofthecalculus.Afamous key propertyofClosed CbV(whose evaluationis

βλ restricted toclosedterms) is harmony:given a closed termt,either it divergesor it evaluates to an abstraction, i.e. t is

β

λ-normalifand onlyift

is an abstraction. The fireball calculus

λ

fire satisfies an analogous property in the open setting by replacing abstractions

withfireballs(Proposition1.1).Moreover,thefireballcalculus isaconservativeextension ofClosedCbV:onclosedtermsit collapseson Closed CbV(Proposition 1.2). No other presentationofOpen CbV hasthesegoodproperties,which together withitssimplicityarethereasontoadoptitasthebestpresentationofOpenCbVinordertostudyitsimplementations.

Proposition1(Distinctivepropertiesof

λ

fire).Lett beaterm.

1. Openharmony:t is

β

f-normalifandonlyift isafireball.

2. Conservativeopenextension:t

βfu ifandonlyift

βλu,fort closed.

Proof. 1. (

)Proof by inductionont. Ift isa variableoran abstraction then t isafireball.Otherwise t

=

us forsome termsu and s;since t is

β

f-normal, then u and s are

β

f-normal,andu isnot anabstraction ors is not afireball;by i.h.,u and s arefireballs;summingup,u isan inertterm(becauseitisa fireballthat isnotan abstraction)ands isa fireball,thust

=

us isaninerttermandsoafireball.

(

) By hypothesis,t is an abstraction oran inertterm. If t isan abstraction, it is

β

f-normalsince

βf doesnot reduceunder

λ

’s.Otherwiset isinert,andweprovebyinductiononthedefinitionofinerttermthatt is

β

f-normal.

Ift isavariable,thent isobviously

β

f-normal.

Ift

=

i

x

.

u

)

theni is

β

f-normalbyi.h.,and

λ

x

.

u is

β

f-normalaswehavejustshown;also,i isnotanabstraction, sot is

β

f-normal.

Finally,ift

=

iitheni andiare

β

f-normalbyi.h.,moreoveri isnotanabstraction,hencet is

β

f-normal.

2. (

)Theideaoftheproofisthatinerttermsarealwaysopen,thusclosedfireballsaresimplyabstractions.Formally,the proofisbyinductiononthedefinitionoft

βf u.Cases:

Stepattheroot, i.e. t

= (λ

x

.

s

)

f

→

βf s

{

x f

}

=

u. Since t isclosed,then f isclosed andhence cannot be an inert term,so f isa(closed)abstractionandthust

= (λ

x

.

s

)

f

→

βλs

{

x f

}

=

u.

Applicationleft, i.e. t

=

sr

βf sr

=

u with s

βf s.Sincet is closed,s is soandhences

βλs by i.h.;therefore,

t

=

sr

βλsr

=

u.

Applicationright,i.e. t

=

rs

βf rs

=

u withs

βf s.Analogoustothepreviouscase. (

)Bydefinition,

βλ

⊆ →

βf (recallthatanabstractionisafireball).

2

Therewriting rules of

λ

fire havealsomanygoodoperationalpropertiesthat westudied in[7],summarized inthe

fol-lowingclaim(provedin[7,Proposition 3]).

Proposition2(Operationalpropertiesof

λ

fire,[7]).Thereduction

βf isquasi-diamond.Ifthereisa

β

f-normalizingderivationfrom

atermt,thent cannot

β

f-divergeandall

β

f-normalizingderivationsd fromt havethesamelength

|

d

|

βf,thesamenumber

|

d

|

βλof

β

λ-steps,andthesame number

|

d

|

βiof

β

i-steps.

Right-to-leftevaluation.As expectedfroma calculus,evaluation

βf in

λ

fire isnon-deterministic,because inan application thereisnofixedordertoevaluatetheleftorrightsubterm.Abstractmachineshoweverimplementdeterministic strategies. Wethenfixadeterministicstrategy(whichfires

β

f-redexesfromrighttoleftandistheoneimplementedbythemachines of the next sections). By Proposition 2, the choice of the strategy doesnot impact either on existence of a result (any strategynormalizes,ifthereisanormalform),orontheresultitself(uniquenessofthenormalform)oronthenumberof stepstoreachit.Itdoesimpacthoweveronthedesignofthemachine,whichselects

β

f-redexesfromrighttoleft.

The right-to-leftevaluationstrategy

rβf isdefinedby closing theroot-step

→

βf

= →

βλ

→

βi in Table1 underright

contexts R,aspecialkindofevaluationcontextdefinedby:

Right Contexts R

::= · |

t R

|

R f

(so,

rβf

 →

βf).Thenextlemmaensuresthatourdefinitioniscorrect.Wesaythat

x

.

u

)

f isa

β

f-redex (resp.

f-redex)

in t if t

=

C

(λ

x

.

u

)

f



(resp. t

=

R

(λ

x

.

u

)

f



) forsome evaluation(resp. right)context C (resp. R). Clearly,t is

β

f-normal (resp.

f-normal)ifandonlyift hasno

β

f-redex(resp.

f-redex).

(7)

Lemma1(Propertiesof

rβf).Lett beaterm.

1. Completeness:t hasa

β

f-redexifandonlyift hasan

f-redex. 2. Determinism:t hasatmostone

f-redex.

Proof. 1. (

)Immediate,since

rβf

⊆ →

βf.

(

)LetC betheevaluationcontextoftherightmost

β

f-redexint,i.e. t

=

C

(λ

x

.

r

)

f



andift

=

C

(λ

x

.

r

)

f



forsome C

=

C thentheholeinC is“moreontheright”thaninC.WeshowthatC isarightcontext,byinductiononC .Cases:

(a) Empty,i.e. C

= ·

.Thenclearly C isarightcontext.

(b) Applicationright,i.e. t

=

us andC

=

uC.Astherightmost

β

f-redexint isins,thenCisarightcontextbyi.h.,and soC isarightcontext.

(c) Applicationleft,i.e. t

=

us andC

=

Cs.Astherightmost

β

f-redexint isinu,thenC isarightcontextbyi.h.,while s is

β

f-normalandsoafireballbyopenharmony(Proposition1.1).Thus,C isarightcontext.

2. By induction on t. By completeness of

rβf (Point 1), open harmony (Proposition 1.1) holds for

rβf: a term is

f-normal (i.e. has no

f-redexes) if and only if it is a fireball. We use this fact implicitly in the following case analysis.Ift isavariableoranabstraction,thent isafireball.

Lett beanapplication,i.e. t

=

us.Byi.h.,therearetwocasesfors:

(a) s hasexactlyone

r

β

f-redex.Thent hasan

r

β

f-redex,becauseu

·

isarightcontext.Moreover,no

r

β

f-redexint can lie inu, andt itselfisnotan

f-redex,sinceby openharmony(Proposition1.1)s is nota fireballandso

·

s is notarightcontext.Thus,t hasexactlyone

f-redex.

(b) s hasno

f-redexes.Byi.h.,therearetwocasesforu:

i. u hasexactlyone

f-redex.Thent hasan

f-redex,because

·

s isarightcontextass isafireball.Uniqueness followsfromthefactthats hasno

f-redexesandu isnotanabstraction.

ii. u hasno

r

β

f-redexes.So,u isafireball.Therearetwosub-cases:

u isanabstraction

λ

x

.

r.Thent

= (λ

x

.

r

)

s isan

f-redex,becauses isafireball.Also,therearenoother

f-redexes,asrightcontextsdonotenterabstractionsands isafireball.

u isaninertterm.Sinces isafireball,t isso(asinert)andhencet hasno

f-redexes.

2

Example1.Lett

:= (λ

z

.

z

(

yz

))λ

x

.

x with z

=

y. Then, t

rβf

x

.

x

)(

y

λ

x

.

x

)

rβf y

λ

x

.

x, where the final term y

λ

x

.

x is a fireball(and

β

f-normal),sinceitisaninertterm.

Right-to-leftvs.left-to-right. In implementing Open CbV, an asymmetry between right-to-left andleft-to-right evaluations arises.

In Closed CbV, the two strategies require slightly differentbut essentially identical abstract machines. The reasonis that inthe closedcase

β

λ-redexes aresymmetric: boththeleft andrightsubterms are abstractions,andabstractionsare

recognizedinconstanttimebylookingonlyatthetopmostconstructor.

Switchingtotheopencase,theleft-to-rightstrategybecomesabittrickiertoimplement.Indeed,

β

f-redexesare asym-metric, sincetheright subtermmaybe aninertterm—inert termshavea morecomplexstructure thanabstractions,and theyarenotrecognizable inconstanttime.Consequently,aleft-to-rightmachinecheckstheeasypartfirstandthecomplex second,needingabacktrackingphase afterthecomplexchecktocomebacktotheoriginalredex.Thismechanismisakinto thatofmachinesforstrongevaluationsuchastheStrongMAMin[13].Theright-to-leftmachineinsteaddoesthecomplex partfirst,andsoitdoesnotneedtobacktrack—thissimplicityiswhyweworkwiththeright-to-leftstrategy.

Opensizeexplosion.Fireballs aredelicate,they can easilyexplode. Thesimplestinstanceofopensizeexplosion (notexisting in Closed CbV) is avariation over the famous loopingterm

ω

:= (λ

x

.

xx

)(λ

x

.

xx

)

βλ

ω

βλ

. . .

. In

ω

there isan infinite sequenceofduplications.Inthesizeexplodingfamilythereisasequenceofn nestedduplications.Wedefinetwofamilies, thefamily

{

tn

}

n∈Nofsizeexplodingtermsandthefamily

{

in

}

n∈N ofresultsofevaluating

{

tn

}

n∈N:

t0

:=

y tn+1

:= (λ

x

.

xx

)

tn i0

:=

y in+1

:=

inin

.

Thesize

|

t

|

ofatermt isdefinedinductivelyasexpected(roughly,itcountsthenumberofsymbolsint;moreprecisely, itcountsthenumberofnodesinthetreerepresentationoft):

|

x

|

:=

1 and

x

.

t

|

:= |

t

|

+

1 and

|

tu

|

:= |

t

|

+ |

u

|

+

1.

Proposition3(Opensizeexplosion,[10]).Letn

∈ N

.Thentn

nβiin,moreover

|

tn

|

=

O

(

n

)

,

|

in

|

= (

2n

)

,andinisaninertterm(and so

β

f-normal).

(8)

Proof. Byinductiononn. Thebasecaseistrivial, ast0

=

y

=

i0.Inductivecase:tn+1

= (λ

x

.

xx

)

tn

nβi

x

.

xx

)

in

βiinin

=

in+1,wherethefirstsequenceisobtainedbythei.h. Clearlyin+1 isinert,andtheboundsonthesizesareimmediate.

2

Circumventingopensizeexplosion.Abstractmachinesimplementingthesubstitutionofinertterms,suchastheonedescribed byGrégoireandLeroy[27] (discussedhereinSect.4,whereitiscalledOpenGLAM)areunreasonablebecausefortheterm tn ofthesizeexplodingfamilyinProposition3theycomputethefullresultin,whosesizeisexponentialinn.Thevarious GLAMOUr machinesofthenext sectionsare instead reasonablebecause they avoidthesubstitutionofinertterms,which is justifiedbythefactthatevaluating andsubstitutinginertterms areoperationsthatcommute,asProposition4belowshows. Inordertoprovethat,weneedthenexttwotechnicallemmas.

Lemma2(Fireballsareclosedundersubstitutionandanti-substitutionofinertterms).3Lett beatermandi beaninertterm.

1. t

{

x i

}

isanabstractionifandonlyift isanabstraction; 2. t

{

x i

}

isaninerttermifandonlyift isaninertterm; 3. t

{

x i

}

isafireballifandonlyift isafireball.

Proof. Point1istrivial.Point3isanimmediateconsequenceofPoints1-2.

Concerning Point2, the left-to-right direction (

) is proved by a simple induction on the inert structure of t

{

x i

}

. Conversely,theright-to-leftdirection(

)isprovedbyasimpleinductionontheinertstructureoft.

2

Lemma3(Substitutionofinerttermsdoesnotcreate

β

f-redexes).4Lett

,

u betermsandi beaninertterm.Thereisaterms suchthat: 1. ift

{

x i

}

βλu thent

βλs ands

{

x i

}

=

u;

2. ift

{

x i

}

βiu thent

βis ands

{

x i

}

=

u.

Proof. Byinductiononthedefinitionoft

{

x i

}

βf u (i.e. ontheevaluationcontextclosingtherootredex).

2

Wecannowprovethatevaluationandsubstitutionofinerttermscommute.Saiddifferently,substitutionofinerttermscan alwaysbepostponedandhencesafelyavoided.

Proposition4(Inertsubstitutionsandevaluationcommute).Lett

,

u betermsandi beaninertterm.Then,t

βf u ifandonlyif

t

{

x i

}

βf u

{

x i

}

.Moreprecisely:

1. Inertsubstitutionsdonoterase

β

f-redexes:Ift

βf u thent

{

x i

}

βf u

{

x i

}

.

2. Inertsubstitutionsdonotcreate

β

f-redexes:Ift

{

x i

}

βf u thenthereisatermtsuchthatt

βf tandu

=

t

{

x i

}

.

Proof. Point2isexactlyLemma3,since

βf

= →

βλ

βi.

Point1isprovedbyinductiononthedefinitionoft

βf u.Cases:

Stepattheroot:

1. Abstraction step, i.e. t

= (λ

y

.

s

)

r

→

βλ s

{

y r

}

=

u where r is an abstraction (assume without loss of generality

y

∈ fv(

/

i

)

∪ {

x

}

).Since r

{

x i

}

is anabstraction (Lemma 2.1), t

{

x i

}

= (λ

y

.

s

{

x i

})

r

{

x i

} →

βλs

{

x i

}{

y r

{

x i

}}

=

s

{

y r

}{

x i

}

=

u

{

x i

}

.

2. Inert step, i.e. t

= (λ

y

.

s

)

i

→

βi s

{

y i

}

=

u where i is inert. We can suppose without loss of generality that

y

∈ fv(

/

i

)

∪ {

x

}

.AccordingtoLemma2.2,i

{

x i

}

isinert. So,t

{

x i

}

= (λ

y

.

s

{

x i

})

i

{

x i

}

→

βis

{

x i

}{

y i

{

x i

}}

=

s

{

y i

}{

x i

}

=

u

{

x i

}

.

Applicationright, i.e. t

=

rs

βf rs

=

u with s

βf s. By i.h., s

{

x i

} →

βf s

{

x i

}

, so t

{

x i

}

=

r

{

x i

}

s

{

x i

}

βf

r

{

x i

}

s

{

x i

}

=

u

{

x i

}

.

Applicationleft,i.e. t

=

sr

βf sr

=

u withs

βf s.Analogoustotheapplicationright case,justswitchrightandleft.

2

Proposition4statesthatsubstitutionofinerttermsforvariablescannotcreateorerase

β

f-redexes,whichiswhyitcan beavoided.Thispropertyisdistinctiveofinertterms(hencetheir name).Withgeneralterms(orevenfireballs) insteadof inertones, evaluationandsubstitution donot commute,that isbothpoints ofProposition 4donot hold. Point2isfalse

3 ProofinAppendix,p.27.

(9)

because substitution can create

β

f-redexes,as in

(

xy

)

{

x

λ

z

.

z

}

= (λ

z

.

z

)

y; Point1 isfalse because substitution can erase

β

f-redexes,asin

((λ

x

.

z

)(

xx

))

{

x

δ

}

= (λ

x

.

z

)(δδ)

where

δ

:= λ

y

.

y y.5

Variablesandinertterms. Variables can be seen both as values and inert terms. Here we consider them as inert terms, becauseforabstractmachinesitispracticaltoseevaluesasbeingonlyabstractions.Thesubstitutionofgeneralinertterms causesopensizeexplosion,butofcoursethesubstitutionofvariablesisharmless.Andwhethervariablesaresubstitutedor notisoneoftheparametersthatwillplayaroleinourstudyofabstractmachines,inthefollowingsections.

3. Abstractmachines,implementations,andcomplexityanalyses

Inthissectionweintroducegeneralnotionsaboutabstractmachines,givenwithrespecttoageneric machine

M

anda generic strategy

on

λ

-terms.Thenwegiveanabstractnotionofimplementationandsufficientconditionsforit.Finally, weprovideageneralrecipeforcomplexityanalyses.

Abstractmachinesglossary.

Anabstractmachine

M

isgivenbystates,noteds,andtransitions betweenthem,noted



M;thereflexive-transitiveclosure

of



Misnoted



∗M;

A state is givenby the codeunderevaluation plus some datastructures, whichcan be seen as lists ofitems(the cons operatorforsuchlistsisdenotedby

:

);

Thecodeunderevaluation,aswellastheotherpiecesofcodescatteredinthedatastructures,are

λ

-termsnotconsidered modulo

α

-equivalence;they are overlined,to stressthe differenttreatment of

α

-equivalence; thesize

|

t

|

ofa codet is exactlythesize

|

t

|

ofanytermt

α

-equivalenttot;

Acodet iswell-named if,foreverysub-code

λ

x

.

u oft,thevariablex mayoccuronlyinu (ifatall);

Astateisinitial ifitscodeiswell-namedanditsdatastructuresareempty(anemptylist ofitemsisdenotedby



);

Therefore,thereisabijection

·

◦ (upto

α

-equivalence)between

λ

-termsandinitial states,calledcompilation,sending a

λ

-termt totheinitialstatet◦ onawell-namedcode

α

-equivalenttot;

Anexecution isafinite(possiblyempty)sequenceoftransitionst0



Ms fromaninitialstatet0obtainedbycompilingan (initial)

λ

-termt0;

Astate s isreachable ifthereisanexecutiont0



∗Ms,forsome

λ

-termt0;

Astate s isfinal ifitisreachableandnotransitionsapplytos;

Amachinecomeswithadecoding map

·

fromstatesto

λ

-termsthatoninitialstatesistheinverse(upto

α

-equivalence) ofcompilation,i.e. t

=

t forany

λ

-termt,andso

(

s

)

=

s foranyinitialstates (asitisoftheforms

=

t◦);

Transitionsofamachine

M

aredividedinto

β

-transitions,noted



β,whicharemeanttobemappedto

β

-reductionsteps

bythedecoding,whiletheremainingoverheadtransitions,noted



o,aremappedtoequalities;

Weuse

|

ρ

|

forthelength(i.e. numberoftransitions)ofanexecution

ρ

,and

|

ρ

|

βforthenumberof

β

-transitionsin

ρ

.

Implementations.Any machinehastobe proventoimplementcorrectlythestrategy inthe

λ

-calculus forwhichitis con-ceived. Ournotionofimplementation,tuned towards complexity analyses,claims a perfectmatch between thenumberof

β

-stepsofthestrategyandthenumberof

β

-transitions of the machine execution.

Definition1(Machineimplementation).Anabstractmachine

M

implementsastrategy

on

λ

-termsvia adecoding

·

when, forevery

λ

-termt,thefollowinghold:

1. Executionstoderivations:forany

M

-execution

ρ

:

t



Ms thereexistsa

-derivationd

:

t

s.

2. Derivationstoexecutions:forevery

-derivationd

:

t

u thereexistsa

M

-execution

ρ

:

t



Ms suchthats

=

u. 3.

β

-matching:inbothpreviouspointsthenumber

|

ρ

|

β of

β

-transitionsin

ρ

isexactlythelength

|

d

|

ofd,i.e.

|

d

|

= |

ρ

|

β.

Sufficientconditionforimplementations.Theproofsthatsomemachineimplementsastrategytendtofollowalwaysthesame structure,basedonafewabstractpropertiescollectedhereintothenotionofimplementationsystem.

Definition2(Implementationsystem).Anabstractmachine

M

,astrategy

,andadecoding

·

formanimplementationsystem ifthefollowingconditionshold:

1.

β

-projection:s



βsimpliess

s,foreveryreachablestate s;

2. Overheadtransparency:s



osimpliess

=

s,foreveryreachablestates;

5 Aswell-knowninthetheoryofλ-calculus,Proposition4withordinary(i.e. call-by-name)β-reduction

βinsteadof→βf andgeneraltermsinstead

(10)

3. Overheadtermination:



o terminates,startingfromeveryreachablestate;

4. Determinism:both



M and

aredeterministic;

5. Halt:

M

finalstatesdecodeto

-normalterms.

Now we prove the implementation theorem (Theorem 1), statingthat the conditions required to an implementation system(Definition2)indeedimplythatthemachineimplementsthestrategyviathedecoding(inthesenseofDefinition1). Theexecutions-to-derivations partoftheimplementationtheoremiseasy toprove,essentially

β

-projection andoverhead transparency allowustoprojectasingletransitionontooneornone

-steps,andtheprojectionofexecutionsonto deriva-tionsisobtainedasasimpleinduction.

Thederivations-to-executions partisabitmoredelicate,instead,becausethesimulationof

-stepsintothemachinehas tobedoneupto overheadtransitions.Thefollowinglemmashowshowtheconditionsforimplementationsystemsallowus todothat.Interestingly,allfiveconditionsofDefinition2areusedintheproof.

Lemma4(One-stepsimulation).Let

M

,

,and

·

beamachine,astrategy,andadecodingforminganimplementationsystem.Forany reachablestates of

M

,ifs

u thenthereisastatesof

M

suchthats



o



βsands

=

u.

Proof. For anyreachablestate s of

M

, letnfo

(

s

)

be the normalformof s with respectto



o: such a state existsandis

uniquebecauseoverheadtransitionsterminate(Point3)and

M

isdeterministic(Point4).Since



o ismappedonidentities

(Point 2), one has nfo

(

s

)

=

s. As s is not

-normal by hypothesis, the halt property (Point 5) entails that nfo

(

s

)

is not

final, therefore s



onfo

(

s

)



βs forsome state s, andthus s

=

nfo

(

s

)

s by

β

-projection (Point 1). According tothe

determinismof

(Point4),oneobtainss

=

u.

2

The one-step simulation (Lemma 4) can be extended to the simulation of derivations into the machine by an easy inductiononthelengthofthederivation.

Theorem1(Sufficientconditionforimplementations).Let

(M,

→,

·)

bean implementationsystem.Then,

M

implements

via

·

.

Proof. AccordingtoDefinition1,givena

λ

-termt,wehavetoshowthat:

(i) Executionstoderivationswith

β

-matching: forany

M

-execution

ρ

:

t



Ms there exists a

-derivation d

:

t

s such that

|

d

|

= |

ρ

|

β.

(ii) Derivationstoexecutionswith

β

-matching: forany

-derivationd

:

t

u thereexists a

M

-execution

ρ

:

t



∗Ms such

thats

=

u and

|

d

|

= |

ρ

|

β.

ProofofPoint(i).Byinductionon

|

ρ

|

β

∈ N

.

If

|

ρ

|

β

=

0 then

ρ

:

t



∗os andhencet

=

s byoverheadtransparency(Point2ofDefinition2).Moreover,t

=

t◦ since

decoding is the inverseof compilation on initial states,therefore we are done by taking the empty (i.e. without steps) derivationd withstarting(andend)termt.

Suppose

|

ρ

|

β

>

0:then,

ρ

:

t



∗Ms istheconcatenationofanexecution

ρ



:

t



∗Msfollowedbyanexecution

ρ



:

s



β

s



os.Byi.h. appliedto

ρ

,thereexistsaderivationd

:

t

swith

|

ρ



|

β

= |

d

|

.By

β

-projection(Point1ofDefinition2)

and overheadtransparency (Point 2 of Definition 2) applied to

ρ

, one has d

:

s

s

=

s. Therefore, the derivation d definedastheconcatenationofdandd issuchthatd

:

t

s and

|

d

|

= |

d

|

+ |

d

|

= |

ρ



|

β

+

1

= |

ρ

|

β.

ProofofPoint(ii).Byinductionon

|

d

|

∈ N

.

If

|

d

|

=

0 thent

=

u.Sincedecodingistheinverseofcompilationoninitialstates,onehast

=

t.Wearedonebytaking theempty(i.e. withouttransitions)execution

ρ

withinitial(andend)statet◦.

Suppose

|

d

|

>

0:so,d

:

t

u istheconcatenationofaderivationd

:

t

ufollowedbythestepu

u.Byi.h.,there existsa

M

-execution

ρ



:

t



∗Ms such that s

=

u and

|

d

|

= |

ρ



|

β.Accordingtotheone-step simulation(Lemma4,since

s

u and

(M,

→,

·)

isan implementationsystem),thereisastate s of

M

such thats



o



βs ands

=

u. Therefore,the

execution

ρ

:

t



Ms



o



βs issuchthat

|

ρ

|

β

= |

ρ



|

β

+

1

= |

d

|

+

1

= |

d

|

.

2

TheproofofTheorem1isacleanandabstractgeneralizationoftheconcretereasoningusedin[12,10,2,3,14] forspecific abstractmachinesandstrategies,anditisacontributionofthiswork.

Parametersforcomplexityanalyses.Let

M

beanabstractmachineimplementing astrategy

viaadecoding

·

(Definition1). Bythederivations-to-executions partoftheimplementation(Point2inDefinition1),givenaderivationd

:

t0

nu there is

ashortestexecution

ρ

:

t0



Ms suchthats

=

u.Determiningthecomplexityofamachine

M

amountstoboundtheasymptotic complexityofaconcreteimplementationof

ρ

onarandomaccessmachine(RAM),asafunctionoftwo parameters: 1. Input:thesize

|

t0

|

oftheinitialtermt0ofthederivationd;

(11)

2.

β

-steps/transitions:thelengthn

= |

d

|

ofthederivationd,that coincideswiththenumber

|

ρ

|

β of

β

-transitionsin

ρ

by

the

β

-matchingrequirementforimplementations(Point3inDefinition1).

Amachineisreasonable ifitscomplexity ispolynomial in

|

t0

|

and

|

ρ

|

β,anditisefficient if itislinearinbothparameters.

So,astrategyisreasonable(resp. efficient)ifthereisareasonable(resp. efficient)machineimplementingit.InSect.5-6we studyareasonablemachineimplementingright-to-leftevaluation

rβf in

λ

fire,thusshowingthatitisareasonablestrategy. InSect.7weoptimizethemachinetomakeitefficient.ByProposition2,this implies that every strategy in

λ

fireis efficient.

Recipeforcomplexityanalyses.Inamachine

M

,overheadtransitions



oarefurtherseparatedintotwoclasses:

1. Substitutiontransitions



s:theyareinchargeofthesubstitutionprocess;

2. Commutativetransitions



c:theyareinchargeofsearchingforthenext

β

orsubstitutionredextoreduce.

Then,theestimationofthecomplexityofamachineisdoneinthreesteps:

1. Numberoftransitions: boundingthelength

|

ρ

|

oftheexecution

ρ

,byboundingthenumberofitsoverheadtransitions. Both the number

|

ρ

|

c of commutative transitions and the number

|

ρ

|

s of substitution transitions are—separately—

boundedusingthesize

|

t0

|

oftheinputt0andthenumber

|

ρ

|

β of

β

-transitionsin

ρ

.Forsomemachines,theboundon

|

ρ

|

s turnsouttodependonlyon

|

ρ

|

β.

2. Costofsingletransitions: boundingthecost ofconcretely implementinga single transitionof

M

. Hereit isnecessary to gobeyondtheabstractlevel,making some (high-level)assumptionabouthowcodeanddatastructuresareconcretely represented.Commutativetransitionsaredesignedonpurposetohaveconstant cost.Eachsubstitution transitionhasa costlinearinthesizeoftheinitialtermthankstoan invariant(tobeproved)ensuringthatonlysubtermsoftheinitial termareduplicatedandsubstitutedalonganexecution.Each

β

-transitionhasacostconstantorlinearintheinput. 3. Complexityoftheoverhead:obtainingthetotalboundbycomposingthefirsttwopoints,thatis,bytakingthenumberof

eachkindoftransitiontimesthecostofimplementingit,andsummingoverallkindsoftransitions.

(Linear)logicalreading.Ourpartitioningoftransitionsinto

β

,substitutionandcommutativeonesadmitsaproof-theoretical view, as machine transitions can be seen ascut-elimination steps [15,12]. Substitution and

β

transitions correspond to principalcasesincut-elimination.Moreover,inlinearlogicthe

β

-transitioncorrespondstothemultiplicativecasewhilethe substitutiontransitiontotheexponentialone.See[12] formoredetails.

4. OpenGLAM

In thissection we quicklyrecall theOpenGLAM from Accattoli andSacerdoti Coen[10], i.e. the core(up to syntactic sugar) ofthe abstractmachine introduced by Grégoire andLeroy [27] to improvethe implementation ofCoq. The Open GLAMisthenatural—andyetnaïve—waytoimplementtheright-to-leftstrategy

rβf ofthefireballcalculus

λ

fire.

As we will see, the Open GLAM is an unreasonable implementation of the fireball calculus, because its overhead is exponential in the number of

β

f-steps—essentially, it doesnot circumvent open size explosion (Proposition 3). For this reason, we omitaformal studyofthepropertiesoftheOpen GLAM,preserving ourtechnicalenergies forthe reasonable machines of the next sections. We present it anyway, to help the reader become familiar with abstract machines, and becausetheother machineshavethesamedatastructuresastheOpenGLAMandtransitionsthatareobtainedbysimple tweaksoftheOpenGLAM.

The name Open GLAM comes fromthe Leroy Abstract Machine (LAM), a similar machine implementing Closed CbV introducedin[12].TheadjectiveOpen isduetothefactthatthemachinehandlesalsoopenterms.TheG inGLAMinstead isduetotheuseofglobal (ratherthanlocal)environments.

Datastructures.Themachinesinthispaperareunusualintworespects.

Firstandmoreimportantly,theyuseasingleglobal environmentinsteadoflocalenvironments andclosures.Global envi-ronmentsareusedinafewpapers[23,33,22,12,10,13,2] andinducesimpler,moreabstractmachineswhere

α

-equivalence ispushed tothemeta-level(the operation inthesubstitutiontransition



s forthemachinesinTables 3–5,8–9).This

on-the-fly

α

-renamingisharmlesswithrespecttocomplexityanalyses.Forathoroughcomparisonofdifferentapproaches toenvironmentsandofhowtheyimpactontheimplementationcomplexity,seeAccattoli and Barras [5].

Second,argumentstackscontainpairs ofacodeandastack,toimplementsomeofthemachinetransitionsinconstant time,namelythecommutativeones.

TheconfigurationinagiventimeoftheOpenGLAM(andofthemachinesintheGLAMOUrfamily)isstoredinastate, formallydefinedinTable2asaquadruples

= (

D

,

t

,

π

,

E

)

ofthefollowingdatastructures:

Codet:atermnot consideredupto

α

-equivalence,thisiswhyt isoverlined.

Argumentstack

π

: a listcontaining thearguments ofthe current code.Note that stackitems

φ

are pairs ofthe form x@

π

or

λ

x

.

u@



.Thesepairsallowustoimplementsomeofthetransitionsinconstanttime.Thepairx@

π

(where

π

is

(12)

Table 2

(Ontheleft)Data-structures fortheOpenGLAM(Table3)andthemachinesoftheGLAMOUrfamily(Tables4–9):items

φ,stacksπ,dumps D,globalenvironments E,states s.(Ontheright)Unfolding tEanddecoding·(stacksaredecodedto

contextsinpostfixnotationforplugging,i.e. wewritetπratherthanπt).

Data structures Decoding & Unfolding

Stack item φ, ψ::= λx.u@|x@π

Stack π::=| φ :π Environment E::=| [x φ]:E Dump D::=|D:tπ State s:= (D,t,π,E) := · t:=t t→ [x φ]E:=t{x φ}→ E φ:π:= ·φπ ·→ E:= · (Ct)E:=CEtE (tC)E:=tECE t@π:= tπ Rs:=Dπ→ E where s= (D,t,π,E) D:tπ:=Dt·π s:=Dtπ→ E=RstE where s= (D,t,π,E) Table 3

TransitionsoftheOpenGLAM.Inthesubstitutiontransitions,(φ)αisanywell-namedcodeα-equivalenttoφsuchthatits

boundvariablesarefreshwithrespecttothoseinD,πandE[x φ]E.

Dump Code Stack Global Env. Dump Code Stack Global Env.

D tu π E c1 D:tπ u  E D:tπ λx.u  E c2 D t (λx.u@):π E D:tπ x π E c3 D t (x@π):π E if E(x)= ⊥ D λx.t φ:π E β D t π [x φ]E D x π E[x φ]E s D (φ)α π E[x φ]E

inturnanargumentstack)codestheinertterm



x



π

(definedinTable2—thedecoding

·

isexplainedbelow)obtained byputting x in thecontext obtainedby decoding

π

.The pair

λ

x

.

u@



(where



isthe empty stack) isused toinject abstractionsintopairs,sothatitems

φ

canbeuniformlyseenaspairst@

π

ofacodet andastack

π

.

DumpD:asecondstackthat,togetherwiththeargumentstack

π

,isusedtowalkthroughthecodeandsearchforthe nextredex to reduce.The dump is extended(on the right) withan entryt

π

every time evaluationenters the right subtermu ofanapplicationtu;theentrysavestheleftpartt oftheapplicationandthecurrentstack

π

,torestorethem whentheevaluationofu isover.Thedump D andthestack

π

decodetoarightcontext.

GlobalenvironmentE:alistofexplicit(i.e. delayed)substitutionsstoring the

β

-redexes encounteredsofar.Itisusedto implementmicro-stepevaluation(substitutionforonevariableoccurrenceatatime).WewriteE

(

x

)

= ⊥

ifE hasno en-triesoftheform

[

x

φ

]

.Often

[

x

φ

]

E standsfor

[

x

φ

]

:

E,andbyabuseofnotationweconfuseconsandconcatenation. Notethatthebody

φ

ofanyenvironmententry

[

x

φ

]

isastackitem,notacode.

Transitions.TheOpen GLAMhasone

β

-transitionwhereas overheadtransitionsaredivided upintosubstitution and com-mutativetransitions,seeTable3.

• β

-transition



β: it morally fires the

r

β

f-redex corresponding to

x

.

t

, except that it puts a newdelayed substitu-tion

[

x

φ

]

inthe environment instead ofdoing the meta-level substitution t

{

x

φ

}

ofthe argument

φ

forthe (free) occurrencesofthevariablex inthebodyt oftheabstraction.

Substitutiontransition



s: itsubstitutes thevariableoccurrenceunder evaluationwithan (

α

-renamedcopyofa)code

fromthe environment. It is a micro-step (i.e. linear, in the sense of one occurrence at a time) variant of meta-level substitution.It is invisible on

λ

fire: the decoding produces theterm obtainedby meta-levelsubstitution, so themicro

workdoneby



scannotbeobservedatthecoarsergranularityof

λ

fire.Notethat



sistriggeredwheneverthecurrent

codeisavariableboundintheenvironmenttoany item

φ

:as

φ

isapaircode–stack,



smustdecode

φ

too(see below).

Commutativetransitions



c: theylocateandexpose thenext

f-redexaccordingtothe right-to-leftstrategy, by rear-rangingthedatastructures.Theyareinvisibleonthecalculus.Thetransition



c1 forcesevaluationtoberight-to-lefton

applicationstu:themachineprocessesfirsttherightsubtermu,savingtheleftsub-termt onthedump alongwithits currentstack

π

.Theroleof



c2 and



c3 istobacktracktotheentryontopofthedump.Whentherightsubterm,i.e.

thepairu@

π

ofcurrentcodeandstack,isfinallyinnormalform,itispushedonthestackandthemachinebacktracks. ConditionE

(

x

)

= ⊥

(whichmeansthatthevariablex isnotbound)in



c3 ishowtheOpenGLAMhandlesopenterms.

Notetheabsenceofgarbagecollection:itisheresimplyignored,or,moreprecisely,itisencapsulatedatthemeta-level, inthedecodingfunction

·

.Itiswell-knownthatthisisharmlessforthestudyoftimecomplexity.

Compilinganddecoding. A term t is compiled to the machine initialstate t

= (



,

t

,



,



)

, where t is a well-named code

α

-equivalenttot.Conversely,everymachinestates

= (

D

,

t

,

π

,

E

)

decodestoaterms (seetherightpartofTable2),having theshape Rs



t

E



,wheret

E isthe

λ

-term(calledunfolding)obtainedbyrecursively substituting—atthe meta-level—the entriesoftheglobalenvironment E ont,andRsisarightcontext,obtainedbydecodingthestack

π

andthedump D and thenapplyingtheunfolding

E.Toimprovereadability,stacksaredecodedtocontextsinpostfixnotationforplugging,i.e. wewrite



t



π

ratherthan

π



t



because

π

isacontextthatputsargumentsinfrontoft.Notethatt

=

t foranytermt.

Références

Documents relatifs

Abstract: We present fully abstract encodings of the call-by-name λ-calculus into HOcore, a minimal higher-order process calculus with no name restriction.. We consider

The last two examples are new to this paper: in section 3.4, we present call-by-value trees and show how to compile them into abstract B¨ohm trees, and in section 3.5 we show how to

• Local environments are faster: we analyze local environments in their most well-known incarnation, Krivine Abstract Ma- chine (KAM), pointing out simple and yet unusual

At the level of efficiency, the evaluation of crumbled forms does not require any overhead: crumble abstract machines are linear in the number of steps of the calculus and in the

If a strategy → is reasonable then its length is a reasonable cost model, despite size- explosion: the idea is that the λ -calculus is kept as an abstract model, easy to define

A testing approach is any good only if it uncovers bugs, but we were not expecting to find any in the model presented in the paper, which came equipped with a type soundness

We believe it is possible to automatically derive the encoding from an abstract machine, so that the generated translation is deterministic (up to flags for choice processes, as

The memory consists of two zones of registers: (i) the executable zone containing code registers and (ii) the data zone containing data registers.. The access to both zones