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�
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,FrancebUniversityofBath,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
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 and1 InCbVevaluation,afunction’sargumentsareevaluatedbeforebeingpassedtothefunction,sothatβ-redexescanfireonlywhentheirargumentsare
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 modelbyexhibitingarefinedabstractmachine,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.OurstudyrefinestheresultsofAccattoliandSacerdotiCoen[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.
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&opensizeexplosionInthissectionweintroducethefireballcalculus
λ
fire,thepresentationofOpenCbVweworkwithinthispaper,andshowtheexampleofsizeexplosionparticulartotheopensetting.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.Themainfeatureofinerttermsisthatthey areopen (withafree “headvariable”),normal(withrespecttoweak evaluation,seebelow),andwhenpluggedina contexttheycannotcreatearedex(inparticular,theyarenotabstractions),hencethename.2
Applicationisleft-associative,sotur standsfortheterm
(
tu)
r.Termsarealwaysidentifieduptoα
-equivalenceandthe setoffreevariablesofatermt isdenotedbyfv
(
t)
:wesaythatt isclosed iffv
(
t)
= ∅
,otherwiset isopen.Weuset{
x u}
forthetermobtainedbythecapture-avoidingsubstitutionofu foreachfreeoccurrenceofthevariablex int.Todefineevaluationin
λ
fire,weuseevaluationcontexts (notedC ),i.e. termswithexactlyoneoccurrenceofthehole·
,anadditionalplace-holder.WeuseC
tforthetermobtainedbyreplacingthehole·
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:one2 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
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 onlyiftis an abstraction. The fireball calculus
λ
fire satisfies an analogous property in the open setting by replacing abstractionswithfireballs(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 inthefol-lowingclaim(provedin[7,Proposition 3]).
Proposition2(Operationalpropertiesof
λ
fire,[7]).Thereduction→
βf isquasi-diamond.Ifthereisaβ
f-normalizingderivationfromatermt,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 underrightcontexts R,aspecialkindofevaluationcontextdefinedby:
Right Contexts R
::= · |
t R|
R f(so,
→
rβf→
βf).Thenextlemmaensuresthatourdefinitioniscorrect.Wesaythat(λ
x.
u)
f isaβ
f-redex (resp.rβ
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.rβ
f-normal)ifandonlyift hasnoβ
f-redex(resp.rβ
f-redex).Lemma1(Propertiesof
→
rβf).Lett beaterm.1. Completeness:t hasa
β
f-redexifandonlyift hasanrβ
f-redex. 2. Determinism:t hasatmostonerβ
f-redex.Proof. 1. (
⇐
)Immediate,since→
rβf⊆ →
βf.(
⇒
)LetC betheevaluationcontextoftherightmostβ
f-redexint,i.e. t=
C(λ
x.
r)
fandift=
C(λ
x.
r)
fforsome 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 isrβ
f-normal (i.e. has norβ
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 hasanr
β
f-redex,becauseu·
isarightcontext.Moreover,nor
β
f-redexint can lie inu, andt itselfisnotanrβ
f-redex,sinceby openharmony(Proposition1.1)s is nota fireballandso·
s is notarightcontext.Thus,t hasexactlyonerβ
f-redex.(b) s hasno
rβ
f-redexes.Byi.h.,therearetwocasesforu:i. u hasexactlyone
rβ
f-redex.Thent hasanrβ
f-redex,because·
s isarightcontextass isafireball.Uniqueness followsfromthefactthats hasnorβ
f-redexesandu isnotanabstraction.ii. u hasno
r
β
f-redexes.So,u isafireball.Therearetwosub-cases:•
u isanabstractionλ
x.
r.Thent= (λ
x.
r)
s isanrβ
f-redex,becauses isafireball.Also,therearenootherrβ
f-redexes,asrightcontextsdonotenterabstractionsands isafireball.•
u isaninertterm.Sinces isafireball,t isso(asinert)andhencet hasnorβ
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,andabstractionsarerecognizedinconstanttimebylookingonlyatthetopmostconstructor.
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).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 ifandonlyift
{
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 generalityy
∈ 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 thaty
∈ 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}
→
βfr
{
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. Point2isfalse3 ProofinAppendix,p.27.
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.5Variablesandinertterms. 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.
•
AnabstractmachineM
isgivenbystates,noteds,andtransitions betweenthem,notedM;thereflexive-transitiveclosureof
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)sequenceoftransitionst◦0∗Ms fromaninitialstatet◦0obtainedbycompilingan (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◦);•
TransitionsofamachineM
aredividedintoβ
-transitions,notedβ,whicharemeanttobemappedtoβ
-reductionstepsbythedecoding,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 thereexistsaM
-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
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 ofM
,ifs→
u thenthereisastatesofM
suchthats∗oβsands=
u.Proof. For anyreachablestate s of
M
, letnfo(
s)
be the normalformof s with respectto o: such a state existsandisuniquebecauseoverheadtransitionsterminate(Point3)and
M
isdeterministic(Point4).Sinceo 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 notfinal, therefore s
∗onfo(
s)
βs forsome state s, andthus s=
nfo(
s)
→
s byβ
-projection (Point 1). According tothedeterminismof
→
(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: foranyM
-executionρ
:
t◦∗Ms there exists a→
-derivation d:
t→
∗s such that|
d|
= |
ρ
|
β.(ii) Derivationstoexecutionswith
β
-matching: forany→
-derivationd:
t→
∗u thereexists aM
-executionρ
:
t◦∗Ms suchthats
=
u and|
d|
= |
ρ
|
β.ProofofPoint(i).Byinductionon
|
ρ
|
β∈ N
.If
|
ρ
|
β=
0 thenρ
:
t◦∗os andhencet◦=
s byoverheadtransparency(Point2ofDefinition2).Moreover,t=
t◦ sincedecoding 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 existsaM
-executionρ
:
t◦∗Ms such that s=
u and|
d|
= |
ρ
|
β.Accordingtotheone-step simulation(Lemma4,sinces
→
u and(M,
→,
·)
isan implementationsystem),thereisastate s ofM
such thats∗oβs ands=
u. Therefore,theexecution
ρ
:
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 isashortestexecution
ρ
:
t◦0∗Ms suchthats=
u.DeterminingthecomplexityofamachineM
amountstoboundtheasymptotic complexityofaconcreteimplementationofρ
onarandomaccessmachine(RAM),asafunctionoftwo parameters: 1. Input:thesize|
t0|
oftheinitialtermt0ofthederivationd;2.
β
-steps/transitions:thelengthn= |
d|
ofthederivationd,that coincideswiththenumber|
ρ
|
β ofβ
-transitionsinρ
bythe
β
-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
,overheadtransitionsoarefurtherseparatedintotwoclasses: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,bytakingthenumberofeachkindoftransitiontimesthecostofimplementingit,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 operationtα inthesubstitutiontransitions forthemachinesinTables 3–5,8–9).Thison-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π
isTable 2
(Ontheleft)Data-structures fortheOpenGLAM(Table3)andthemachinesoftheGLAMOUrfamily(Tables4–9):items
φ,stacksπ,dumps D,globalenvironments E,states s.(Ontheright)Unfolding t↓Eanddecoding·(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:=C→ Et→ E (tC)→ E:=t→ EC→ E t@π:= tπ Rs:=Dπ→ E where s= (D,t,π,E) D:t♦π:=Dt·π s:=Dtπ→ E=Rst→ E 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 ther
β
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.•
Substitutiontransitions: itsubstitutes thevariableoccurrenceunder evaluationwithan (α
-renamedcopyofa)codefromthe 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 themicroworkdoneby
scannotbeobservedatthecoarsergranularityofλ
fire.Notethatsistriggeredwheneverthecurrentcodeisavariableboundintheenvironmenttoany item
φ
:asφ
isapaircode–stack,smustdecodeφ
too(see below).•
Commutativetransitionsc: theylocateandexpose thenextrβ
f-redexaccordingtothe right-to-leftstrategy, by rear-rangingthedatastructures.Theyareinvisibleonthecalculus.Thetransitionc1 forcesevaluationtoberight-to-leftonapplicationstu:themachineprocessesfirsttherightsubtermu,savingtheleftsub-termt onthedump alongwithits currentstack
π
.Theroleofc2 andc3 istobacktracktotheentryontopofthedump.Whentherightsubterm,i.e.thepairu@
π
ofcurrentcodeandstack,isfinallyinnormalform,itispushedonthestackandthemachinebacktracks. ConditionE(
x)
= ⊥
(whichmeansthatthevariablex isnotbound)inc3 ishowtheOpenGLAMhandlesopenterms.Notetheabsenceofgarbagecollection:itisheresimplyignored,or,moreprecisely,itisencapsulatedatthemeta-level, inthedecodingfunction
·
.Itiswell-knownthatthisisharmlessforthestudyoftimecomplexity.Compilinganddecoding. A term t is compiled to the machine initialstate t◦