/
Chapter  Epigram Reloaded A Standalone Typechecker for Chapter  Epigram Reloaded A Standalone Typechecker for

Chapter Epigram Reloaded A Standalone Typechecker for - PDF document

pasty-toler
pasty-toler . @pasty-toler
Follow
377 views
Uploaded On 2015-06-10

Chapter Epigram Reloaded A Standalone Typechecker for - PPT Presentation

We implement a standalone typechecker for ETT in Haskell allowing us to reload existing libraries into the system safely without reelaboration Rather than adopting a rewriting approach to computation we use a glued representation of values pairing 6 ID: 84047

implement standalone

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Chapter Epigram Reloaded A Standalone T..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

potentialforoptimisationsduetothepresenceofdependenttypes[6].ElaborationissupposedtogeneratewelltypedtermsinETT,buthereweimplementastandalonetypecheckerforETTinHaskell.Whydoweneedthis?Firstly,elaborationisexpensive.Wewanttoreloadexistinglibrariesintothesystemwithoutre-elaboratingtheirhigh-levelsource.However,topreservesafetyandconsistency,weshouldmakesurethatthereloadedcodedoestypecheck.Secondly,consumersmaywanttocheckmobileEpigramcodebeforerunningit.Asecurerun-timesystemneednotcontaintheelaborator:anETTcheckerisfaster,smallerandmoretrustworthy.McKinnasuggestedsuchatypetheoryfortradingin`deliverables'[22],programspairedwithproofs,preciselyitcombinescomputationandlogic,withasinglecompactchecker.Morerecentworkonproof-carryingcode[23]furtheremphasizesminimalityofthe`trustedcodebase'.Thirdly,asEpigramevolves,theelaboratorevolveswithit;ETTismuchmorestable.ThepresentworkprovidesanimplementationofETTwhichshouldaccepttheoutputofanyversionoftheelaboratorandactsasatargetlanguagereferenceforanyonewishingtoextendorinteroperatewiththesystem.Wehopethispaperwillserveasausefulresourceforanyonecuriousabouthowdependenttypecheckingcanbedone,especiallyastheapproachwetakeisnecessarilyquitenovel.OurtreatmentofevaluationinETTtakescrucialadvan-tageofHaskell'slazinesstodeliverconsiderableexibilityinhowmuchorlittlecomputationisdone.Ratherthanadoptingaconventionalrewritingapproachtocomputation,weuseagluedrepresentationofvalues,pairingrst-ordersyntaxwithafunctionalrepresentationofitssemantics,computedasrequired.Thissemanticapproachreadilyseparatesb-reductionfrombh-conversion.Wesupportmoreliberalnotionsof`conversionuptoobservation'byallowingnotonlytheh-lawsforl-abstractionsandpairs,butalsoidentifyingallelementsoftheunittype, 1 .Wefurtheridentifyallelementsoftheemptytype, O ,thusmak-ingalltypesrepresentingnegativepropositions P ! O proofirrelevant!TheserulesarenewtoEpigram—thedenition[21]considersonlyb-equality.Addingthemmakesthetheorymoreextensional,acceptingmoresensibleprogramsandsimplifyingelaborationbyallowinggeneralsolutionstomoretypeconstraints.ItisalsoasteppingstonetowardsanObservationalTypeTheorybasedon[2].Thelawsfor 1 and O donottwithCoquandandAbel'ssyntax-directedapproachtoconversionchecking[1],butrequireatype-directedalgorithmlikeours.AcknowledgmentsWegratefullyacknowledgethesupportofEPSRCgrantEP/C512022/1`ObservationalEqualityforDependentlyTypedProgramming'.WealsothankJamesMcKinna,EdwinBradyandPeterMorrisformanyusefuldiscussions,andtheanonymousrefereesfortheirhelpfuladvice.1.2DEPENDENTTYPESANDTYPECHECKINGTheheartofdependenttypetheoryisthetypingruleforapplication: G` f : P x : S : T G` s : S G` f s :[ x 7! s : S ] T Declaredanddenedvariables G` G` x : S x : S 2G G` G` x : S x 7! s : S 2GUniverse G` G`?:? Conversion G` s : S G` S ' T :? G` s : T Localdenition G; x 7! s : S ` t : T G`[ x 7! s : S ] t :[ x 7! s : S ] T Typeformation,introduction,andelimination G` G` 1 :? G` G` hi : 1 G` G` O :? G` z : O G` z Œ: P X :?: X G; x : S ` T :? G` P x : S : T :? G; x : S ` t : T G` l x : S : t : P x : S : T G` f : P x : S : T G` s : S G` f s :[ x 7! s : S ] T G; x : S ` T :? G` S x : S : T :? G` s : S G; x : S ` T :?G` t :[ x 7! s : S ] T G` h s ; t i T : S x : S : T G` p : S x : S : T G` p p0: S G` p p1:[ x 7! p p0: S ] T FIGURE1.2.Typingrules G` t : T synthesised,notjustchecked.Wewrite O 'seliminator,Œ(`naughtE'),and S -typeprojections,p0andp1postxlikeapplication—-theeliminatorfor P -types.Theequalityrules(gure1.3)3includeb-lawswhichallowcomputationsandexpanddenitions,butwealsoaddh-lawsandproof-irrelevanceforcertaintypes,justiedbythefactthatsometermsareindistinguishablebyobservation.Aproof-irrelevanttypehas,asfaraswecantell,atmostoneelement;examplesaretheunittype 1 andtheemptytype O .Theserulescombinetoidentifyallinhabitantsof( A ! 1 )^( B ! O ),forexample.Equality(hencetype-)checkingisdecidableifallcomputationsterminate.Acarefullydesignedlanguagecanachievethisbyexecutingonlytrustedprogramsintypes,butwedonotaddressthisissuehere.Indeed,ourcurrentimplementa-tionuses?:?andhenceadmitsnon-terminationduetoGirard'sparadox[10].Here,wedeliverthecorefunctionalityoftypechecking.Universestraticationandpositivityofinductivedenitionsarewellestablished[14,15]andorthogonaltothesubjectofthisarticle.1.3EPIGRAMANDITSELABORATIONEpigram'shigh-levelsourcecodeiselaboratedincrementallyintoETT.Theelab-oratorproducesthedetailedevidencewhichjustieshigh-levelprogrammingcon- 3Wehaveomittedanumberoftrivialruleshere,e.g.therulesstatingthat'isanequivalenceandanumberofcongruencerules. Thesetypesarereadasschemesforconstructingstructurallyrecursivepro-grams.Epigramhasnohard-wirednotionofpatternmatching—rather,ifyouinvokeaneliminatorviathe`by'construct(,theelaboratorreadsofftheappro-priatepatternsfromitstype.Ifwehaveanappropriatedenitionof + ,wecandeneconcatenationforvectorsusingelim (prexinEpigramsource)asfollows:let x ; y : Nat x + y : Nat x + y (elim x zero + y ) y suc x 0 + y ) suc ( x 0 + y )let xs : Vec m X ; ys : Vec n X vconc xs ys : Vec ( m + n ) X vconc xs ys (elim xs vconc vnil ys ) ys vconc ( vcons x xs 0 ) ys ) vcons x ( vconc xs 0 ys )TheelaboratorthengeneratesthislumpofETT,inferringthe` P 'argumentto xs elim Vec andconstructingtheothertwofromthebranchesoftheprogram. vconc 7! l X :?: l m : Nat : l n : Nat : l xs : Vec m X : l ys : Vec n X : xs elim Vec ( l m : Nat : l xs : Vec m X : P n : Nat : Vec n X ! Vec ( m + n ) X )( l n : Nat : l ys : Vec n X : ys )( l m 0 : Nat : l x : X : l xs 0 : Vec m 0 X : l h : P n : Nat : Vec n X ! Vec ( m 0 + n ) X : l n : Nat : l ys : Vec n X : vcons X ( m 0 + n ) x ( h n ys )) n ys Theelaboratorworksevenharderinmorecomplexsituations,likethis:let xs : Vec ( suc n ) X vtail xs : Vec n X vtail xs (elim xs vtail ( vcons x xs 0 )) xs 0 Here,theunicationonlengthswhicheliminatesthe vnil caseandspecialisesthe vcons caserestsonanoConfusion theorem—constructorsdisjointandinjective—provenbytheelaboratorforeachdatatype,andonthesubst operator—replacingequalwithequal.Thesetechniquesaredetailedin[18,19],buttheireffectistodeliveralargedulltermwhichjustiesthedependentcaseanalysis. vtail 7! l n : Nat : l X :?: l xs : Vec ( suc n ) X : xs elim Vec ( l m : Nat : l ys : Vec m X : P n : Nat : P xs : Vec ( suc n ) X : P q : m = suc n : P q 0 : ys = xs : Vec n X )( l n : Nat : l xs : Vec ( suc n ) X : l q : zero = suc n : l q 0 : vnil = xs : q noConfusion Nat ( Vec n X ))( l n 0 : Nat : l x : X : l xs 0 : Vec n 0 : l h : P n : Nat : P xs : Vec ( suc n ) X : P q : n 0 = suc n : P q 0 : xs 0 = xs : Vec n X : l n : Nat : l xs : Vec ( suc n ) X : l q : suc n 0 = suc n : l q 0 : vcons X n 0 x xs 0 = xs : q noConfusion Nat ( Vec n X )( l q : n 0 = n : q subst ( l n : Nat : P xs 0 : Vec n 0 X : P h : P n : Nat : P xs : Vec ( suc n ) X : P q : n 0 = suc n : P q 0 : xs 0 = xs : Vec n X : P xs : Vec ( suc n ) X : P q 0 : vcons X n 0 x xs 0 = xs : Vec n X )( l xs 0 : Vec n 0 X : l h : P n : Nat : P xs : Vec ( suc n ) X : P q : n 0 = suc n : P q 0 : xs 0 = xs : Vec n X : l xs : Vec ( suc n 0 ) X : l q 0 : vcons X n 0 x xs 0 = xs : q 0 subst ( l xs : Vec ( suc n 0 ) X : Vec n 0 X ) xs 0 ) xs 0 h xs q 0 ))( suc n ) xs ( re Nat ( suc n ))( re ( Vec ( suc n ) X ) xs )Merelycheckingallthesedetailsismuchsimplerthaninferringthemintherstplace.ReloadingETTinvolvesnoneofthecomplexityofimplicitsyntaxhan-dlingordependentpatternmatching.Meanwhile,ourobservationalequalityruleshelptheelaboratorbyallowingmoretypeconstraintstohavegeneralsolutions. 1.4.1NavigationunderbindersTheoperations==andnnprovideameanstonavigateintoandoutofbinders.(==)::Scope!Value!Term--instantiatestheboundvariableofaScopewithaValue(nn)::(Name;String)!Term!Scope--bindsavariablefreeinaTermtomakeaScopeNamespacemanagementusesthetechniquesof[20].NamesarebackwardlistsofStrings,resemblinglongnamesinmodulesystems.typeName=BListStringdataBListx=B0jBListx:/xderivingEqOurworkisalwaysrelativetoarootname:wedeneaCheckingmonadwhichcombinesthethreadingofthisrootandthehandlingoferrors.Forthispresenta-tionwelimitourselvestoMaybeforerrors.newtypeCheckingx=MkCheckingfrunChecking::Name!MaybexginstanceMonadCheckingwherereturnx=MkChecking$l !returnxMkCheckingf��=g=MkChecking$lname!doa fnamerunChecking(ga)nameUsernamechoicesneverinterferewithmachineNamechoices.Moreover,weensurethatdifferenttasksneverchooseclashingnamesbylocallyextendingtherootnameofeachsubtaskwithadifferentsufx.( )::String!Checkingx!Checkingxname (MkCheckingf)=MkChecking$lroot!f(root:/name)root::CheckingNameroot=MkCheckingreturnWhetherwereallyneedtoornot,weuniformlygiveeverysubcomputationadis-tinctlocalname,triviallyguaranteeingtheabsenceofnameclashes.Inparticular,wecanusex roottogenerateafreshnameforafreshvariableifweensurethatxisdistinctfromtheotherlocalnames.1.5CHECKINGTYPESInthissection,weshallshowhowtosynthesisethetypesofexpressionsandcheckthattheyarecorrect.Typecheckingmakesessentialuseofthesemanticsofterms.Wedeferourimplementationofthissemanticsuntilsection1.6:hereweindicateourrequirementsforourrepresentationofValues.Thetypingrulesarerealizedbythreefunctionsinfer,synthandcheck.Firstly,inferinfersthetypeofitsargumentinasyntax-directedmanner. 1.5.1ImplementingtheTypingRulesWewillnowdeneinferinaccordancewiththetypingrulesfromgure1.2.Wematchonthesyntaxofthetermandineachcaseimplementtherulewiththecorrespondingconclusion,performingthechecksinthehypotheses,thencon-structingthetypefromcheckedcomponents.Thebasecasesareeasy:referencescachetheirtypesandconstantshaveconstanttypes—wejustgivethecasefor?.infer(R( :=( :2ty)))=returntyinfer(CStar)=returnvStarThecaseforboundvariablesVineverarises.Wealwaysworkwithclosedterms,instantiatingaboundvariableasweenteritsScope,abstractingitwhenweleave.Localdenitionisacaseinpoint:infer(Let(s;sty)t)=dostyv "sty" checkvStarstysv "s" checkstyvsx "x" rootttyv "tty" infer(t==vdefn((x;sv):2styv))return(vLet(sv:2styv)(val((x;advicet)nnsynttyv)))Wecheckthattyisatypeandthatsinhabitsit.Therulesachievethisindirectlyviacontextvalidityateachleafofthetypingderivation;weperformthecheckonce,beforevdefncreatesthereferencevaluewhichrealisestheextensionofthecontext.Thenewvariablegetsitsfreshnamefrom"x" root,andthecorrespondingvalueisusedtoinstantiatetheboundvariableoft.Oncewehavet'stype,ttyv,weusevLettobuildthetypeofthewholethingfromcheckedcomponents.Valuesdonotsupportthe(nn)operation,soweabstractxfromthesyntaxofttyv,thengenerateasemanticscopewithval.CheckingaP-typerequiresasimilarjourneyunderabinder,buttheresultingtypeisasimple?.infer(Pidomran)=dodomv "dom" checkvStardomx "x" root "ran" checkvStar(ran==vpara(x:2domv))returnvStarWecheckthatdomisatype,thencreateafreshvariableandinstantiatetherange,ensuringthatitalsoisatype.CheckingaS-typeworksthesameway.Meanwhile,totypecheckal,wemustusethetypeinferredunderthebindertogeneratetheP-typeofthefunction,abstractingascopefromitssyntaxaswedidforLet.infer(Ldomt)=dodomv "dom" checkvStardomx "x" rootranv "ran" infer(t==vpara(x:2domv))return(vPidomv(val((x;advicet)nnsynranv))) Justasin`normalisation-by-evaluation'[5],thebehaviourofscopes(for P and S ,notjust l )isdeliveredbytheimplementationlanguage,butifwewanttoreadaValue,wejustprojectitssyntax.Whnfsaregivenasfollows:dataWhnf=WRReference(BList(ElimValue))--SpinejWPiValueScoValjWSiValueScoVal-- P -type, S -typejWLScoValjWPValueValue-- l -abstraction,pairjWCConst--ConstantTheonlyeliminationformsweneedtorepresentarethosewhichoperateonaninertparameter,hencewepackthemtogether,withtheWRconstructor.Boundvariablesdonotoccur,exceptwithintheScopepartofaScoVal.Wedropthetypeannotationson l -abstractionsandpairsastheyhavenooperationaluse.Withthisdenition,operationssuchasisPi,isSiandisZerocanbeimplementeddirectlybypatternmatchingonWhnf.Meanwhile,thecomputationalbehaviourofValuesisgivenbytheoverloaded$$operator:classEliminabletwhere($$)::t!(ElimValue)!tinstanceEliminableValuewheret$$e=(synt:$fmapsyne):+(semt$$e)instanceEliminableWhnfwhereWL( :+f)$$Av=fv--b-reductionbyHaskellapplicationWPx $$P0=semx--projectionsWP y$$P1=semyWRxes$$e=WRx(es:/e)--inertcomputationsWeshallnowuse$$todeliverthefunctionevalwhichmakesvaluesfromcheckedsyntax.Thistooisoverloaded,anditssyntacticaspectreliesontheavailabilityofsubstitutionofclosedtermsforboundvariables.typeEnv=BListValuebproj::BListx!Int!xclassClosetwhereclose::t!Env!Int!t--theIntistherstboundvariabletoreplaceclassCloset)Whnvtwjt!wwherewhnv::t!Env!weval::t!Env!Gluedtwevaltg=(closetg0):+(whnvtg)val::t!Gluedtwvalt=t:+whnvtB0Weexportval,forclosedterms,tothetypechecker.However,evalandwhnv,denedmutually,threadanenvironmentgexplainingtheboundvariables.ByseparatingScopefromTerm,wecansayhowtogounderabinderonce,forall.instanceCloseScopewhereclose(s::t)gi=s::closetg(i+1)--startgfurtherout areEqual((p;q):2( :+WSidomran))=do"fst" areEqual((p$$P0;q$$P0):2dom)"snd" areEqual((p$$P1;q$$P1):2(vLet(p$$P0:2dom)ran))Forgroundtermsoftypesotherthan 1 and O ,wecanonlyhaveinertreferenceswithspines,whichwecompareinaccordancewiththestructuralrules.Werebuildthetypeofaspineasweprocessit,inordertocompareitscomponentscorrectly.areEqual(( :+WRr1as; :+WRr2bs):2 )=doguard(r1r2) spineEqr1(as;bs)return()spineEq:2Reference!(ElimValue;ElimValue)!CheckingValueWepeeleliminatorsuntilwereachthereference,whosetypewepassback.spineEq(r:=( :2ty))(B0;B0)=returntyForapplications,wecheckthatprecedingspinesareequalandanalysethe P -typetheydeliver;wethenconrmthattheargumentsareequalelementsofitsdomainandpassontheinstantiatedrange.spineEqr(as:/Aa;bs:/Ab)=dosty spineEqr(as;bs)(dom;ran) isPisty"eqargs" areEqual((a;b):2dom)return(vLet(a:2dom)ran)ForlikeprojectionsfrompairsweanalysetheS-typefromtheprecedingspinesandpassontheappropriatecomponent,instantiatedifneedbe.spineEqr(as:/P0;bs:/P0)=dosty spineEqr(as;bs)(dom; ) isSistyreturndomspineEqr(as:/P1;bs:/P1)=dosty spineEqr(as;bs)(dom;ran) isSistyreturn(vLet((spiner(as:/P0)):2dom)ran)wherespinerB0=val(Rr)spiner(es:/e)=spineres$$eFor`naughtE',weneedlooknofurther!spineEq (as:/OE;bs:/OE)=returnvAbsurd [6] EdwinBrady.PracticalImplementationofaDependentlyTypedFunctionalPro-grammingLanguage.PhDthesis,UniversityofDurham,2005. [7] EdwinBrady,ConorMcBride,andJamesMcKinna.Inductivefamiliesneednotstoretheirindices.InStefanoBerardi,MarioCoppo,andFerrucioDamiani,editors,TypesforProofsandPrograms,Torino,2003,volume3085ofLNCS,pages115–129.Springer-Verlag,2004. [8] L'´EquipeCoq.TheCoqProofAssistantReferenceManual.http://pauillac.inria.fr/coq/doc/main.html,2001. [9] CatarinaCoquandandThierryCoquand.StructuredTypeTheory.InWorkshoponLogicalFrameworksandMetalanguages,1999. [10] ThierryCoquand.AnanalysisofGirard'sparadox.InProceedingsoftheFirstIEEESymposiumonLogicinComputerScience,Cambridge,Massachussetts,pages227–236,1986. [11] ThierryCoquand.Analgorithmfortestingconversionintypetheory.InG´erardHuetandGordonPlotkin,editors,LogicalFrameworks.CUP,1991. [12] NicolasG.deBruijn.LambdaCalculusnotationwithnamelessdummies:atoolforautomaticformulamanipulation.IndagationesMathematicæ,34:381–392,1972. [13] BenjaminGr´egoireandXavierLeroy.Acompiledimplementationofstrongreduc-tion.InInternationalConferenceonFunctionalProgramming2002,pages235–246.ACMPress,2002. [14] RobertHarperandRandyPollack.Typecheckingwithuniverses.TheoreticalCom-puterScience,89:107–136,1991. [15] ZhaohuiLuo.ComputationandReasoning:ATypeTheoryforComputerScience.OxfordUniversityPress,1994. [16] ZhaohuiLuoandRobertPollack.LEGOProofDevelopmentSystem:User'sManual.TechnicalReportECS-LFCS-92-211,LFCS,1992. [17] PerMartin-L¨of.IntuitionisticTypeTheory.BibliopolisNapoli,1984. [18] ConorMcBride.EliminationwithaMotive.InPaulCallaghan,ZhaohuiLuo,JamesMcKinna,andRobertPollack,editors,TypesforProofsandPrograms(ProceedingsoftheInternationalWorkshop,TYPES'00),volume2277ofLNCS.Springer-Verlag,2002. [19] ConorMcBride,HealfdeneGoguen,andJamesMcKinna.AFewConstructionsonConstructors.InTypesforProofsandPrograms,Paris,2004,LNCS.Springer-Verlag,2005.accepted;toappear. [20] ConorMcBrideandJamesMcKinna.FunctionalPearl:IamnotaNumber:IamaFreeVariable.InHenrikNilsson,editor,ProceedingsoftheACMSIGPLANHaskellWorkshop2004,Snowbird,Utah.ACM,2004. [21] ConorMcBrideandJamesMcKinna.Theviewfromtheleft.JournalofFunctionalProgramming,14(1),2004. [22] JamesMcKinna.Deliverables:ACategoricalApproachtoProgramDevelopmentinTypeTheory.PhDthesis,LFCS,1992. [23] GeorgeC.Necula.Proof-carryingcode.InProceedingsofthe24thACMSIGPLAN-SIGACTSymposiumonPrinciplesofProgrammingLanguages,pages106–119,Paris,January1997.