12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2019 Nomadic Labs. <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)moduleNum=structtypet=Intofint|Floatoffloatletppppf=letopenFormatinfunctionInti->pp_print_intppfi|Floatf->pp_print_floatppffletadds1s2=match(s1,s2)with|Intx,Inty->Int(x+y)|Intx,Floaty->Float(floatx+.y)|Floatx,Inty->Float(x+.floaty)|Floatx,Floaty->Float(x+.y)letmuls1s2=match(s1,s2)with|Intx,Inty->Int(x*y)|Intx,Floaty->Float(floatx*.y)|Floatx,Inty->Float(x*.floaty)|Floatx,Floaty->Float(x*.y)letcompares1s2=match(s1,s2)with|Intx,Inty->Int.comparexy|Intx,Floaty->Float.compare(floatx)y|Floatx,Inty->Float.comparex(floaty)|Floatx,Floaty->Float.comparexyendmoduleTy=structtype_t=|Unit:unitt|Num:Num.tt|Int:intt|Float:floatt|String:stringt|Bool:boolt|Arrow:'at*'bt->('a->'b)tletunit=Unitletnum=Numletint=Intletfloat=Floatletstring=Stringletbool=Boolletarrowt1t2=Arrow(t1,t2)type(_,_)eq=Refl:('a,'a)eqletrecequal:typeab.at->bt->(a,b)eqoption=funab->match(a,b)with|Unit,Unit->SomeRefl|Num,Num->SomeRefl|Int,Int->SomeRefl|Bool,Bool->SomeRefl|Float,Float->SomeRefl|String,String->SomeRefl|Arrow(t11,t12),Arrow(t21,t22)->(matchequalt11t21with|None->None|SomeRefl->(matchequalt12t22withNone->None|SomeRefl->SomeRefl))|_->NoneendmoduletypeS=sigtype'areprtypesizevalsize_ty:sizeTy.tvaltrue_:boolreprvalfalse_:boolreprvalint:int->sizereprvalfloat:float->sizereprval(+):sizerepr->sizerepr->sizereprvalsat_sub:sizerepr->sizerepr->sizereprval(*):sizerepr->sizerepr->sizereprval(/):sizerepr->sizerepr->sizereprvalmax:sizerepr->sizerepr->sizereprvalmin:sizerepr->sizerepr->sizereprvallog2:sizerepr->sizereprvalsqrt:sizerepr->sizereprvalfree:name:Free_variable.t->sizereprvallt:sizerepr->sizerepr->boolreprvaleq:sizerepr->sizerepr->boolreprvalshift_left:sizerepr->int->sizereprvalshift_right:sizerepr->int->sizereprvallam':name:string->'aTy.t->('arepr->'brepr)->('a->'b)reprvallam:name:string->(sizerepr->'arepr)->(size->'a)reprvalapp:('a->'b)repr->'arepr->'breprvallet_:name:string->'arepr->('arepr->'brepr)->'breprvalif_:boolrepr->sizerepr->sizerepr->sizereprend(* ------------------------------------------------------------------------- *)(* Various useful implementations of the signatures above. *)moduleVoid:Swithtype'arepr=unitandtypesize=unit=structtype'arepr=unittypesize=unitletsize_ty=Ty.unitlettrue_=()letfalse_=()letfloat_=()letint_=()let(+)__=()letsat_sub__=()let(*)__=()let(/)__=()letmax__=()letmin__=()letshift_left__=()letshift_right__=()letlog2()=()letsqrt()=()letfree~name=ignorenameletlt__=()leteq__=()letlam'~name_ty_=ignorenameletlam~name_=ignorenameletapp__=()letlet_~name__=ignorenameletif____=()endmodulePp:Swithtype'arepr=stringandtypesize=string=structtype'arepr=stringtypesize=stringletsize_ty=Ty.stringlettrue_="true"letfalse_="false"letfloat=string_of_floatletint=string_of_intlet(+)xy=Format.asprintf"(%s + %s)"xyletsat_subxy=Format.asprintf"(sat_sub %s %s)"xylet(*)xy=Format.asprintf"(%s * %s)"xylet(/)xy=Format.asprintf"(%s / %s)"xyletmaxxy=Format.asprintf"(max %s %s)"xyletminxy=Format.asprintf"(min %s %s)"xyletshift_leftxi=Format.asprintf"(%s lsl %d)"xiletshift_rightxi=Format.asprintf"(%s lsr %d)"xiletlog2x=Format.asprintf"(log2 %s)"xletsqrtx=Format.asprintf"(sqrt %s)"xletfree~name=Format.asprintf"free(%a)"Free_variable.ppnameletltxy=Format.asprintf"(%s < %s)"xyleteqxy=Format.asprintf"(%s = %s)"xyletlam'~name_tyf=Format.asprintf"fun %s -> %s"name(fname)letlam~name=lam'~namesize_tyletappfarg=Format.asprintf"((%s) %s)"fargletlet_~namemf=Format.asprintf"let %s = %s in %s"namem(fname)letif_condiftiff=Format.asprintf"(if %s then %s else %s)"condiftiffendmoduleFree_variables:Swithtype'arepr=Free_variable.Set.tandtypesize=unit=structopenFree_variabletype'arepr=Set.ttypesize=unitletsize_ty=Ty.unitletlift_binopxy=Set.unionxylettrue_=Set.emptyletfalse_=Set.emptyletfloat_=Set.emptyletint_=Set.emptylet(+)=lift_binopletsat_sub=lift_binoplet(*)=lift_binoplet(/)=lift_binopletmax=lift_binopletmin=lift_binopletshift_leftx_i=xletshift_rightx_i=xletlog2x=xletsqrtx=xletfree~name=Set.singletonnameletlt=lift_binopleteq=lift_binopletlam'~name_tyf=ignorename;fSet.emptyletlam~name=lam'~namesize_tyletappfarg=Set.unionfargletlet_~namemf=ignorename;letin_scope=fSet.emptyinSet.unionmin_scopeletif_condiftiff=Set.unioncond(Set.unioniftiff)endmoduleType=structtypesize=Num.tletsize_ty=Ty.numtype'arepr='aTy.tlettrue_=Ty.boolletfalse_=Ty.boolletfloat_=Ty.numletint_=Ty.numlet(+)__=Ty.numletsat_sub__=Ty.numlet(*)__=Ty.numlet(/)__=Ty.numletmax__=Ty.numletmin__=Ty.numletshift_left__=Ty.numletshift_right__=Ty.numletlog2_=Ty.numletsqrt_=Ty.numletfree~name:_=Ty.numletlt__=Ty.boolleteq__=Ty.boolletlam'~name:_tyf=Ty.arrowty(fty)letlam~name=lam'~namesize_tyletappfa=matchfwith|Ty.Arrow(f,t)->assert(f=a);tletlet_~name:_vf=fvletif__t_=tendmoduleArg_names=structtypesize=unitletsize_ty=Ty.unittype'arepr=|Bool:boolrepr|Size:sizerepr|Lambda:string*('arepr->'brepr)->('a->'b)reprletarg_name(Lambda(arg,_))=argletunwrap_bool(Lambda(_,f))=fBoolletunwrap_size(Lambda(_,f))=fSizelettrue_=Boolletfalse_=Boolletfloat_=Sizeletint_=Sizelet(+)__=Sizeletsat_sub__=Sizelet(*)__=Sizelet(/)__=Sizeletmax__=Sizeletmin__=Sizeletshift_left__=Sizeletshift_right__=Sizeletlog2_=Sizeletsqrt_=Sizeletfree~name:_=Sizeletlt__=Boolleteq__=Boolletlam'~name_tyf=Lambda(name,f)letlam~name=lam'~namesize_tyletapp(Lambda(_,f))x=fxletlet_~name:_vf=fv(* We can't decide which branch to pick. This choice is arbitrary. *)letif__t_=tendletsat_sub_floatxy=max0.(x-.y)letsat_sub_intxy=max0(x-y)moduleEval:Swithtype'arepr='aandtypesize=float=structexceptionTerm_contains_free_variableofFree_variable.ttype'arepr='atypesize=floatletsize_ty=Ty.floatletlift_binopopxy=opxylettrue_=trueletfalse_=falseletfloatx=xletintx=float_of_intxlet(+)=lift_binop(+.)letsat_sub=lift_binopsat_sub_floatlet(*)=lift_binop(*.)let(/)=lift_binop(/.)letmax=lift_binopmaxletmin=lift_binopminletshift_leftxi=x*.(2.**float_of_inti)letshift_rightxi=x/.(2.**float_of_inti)letlog2x=logx/.log2.letsqrt=sqrtletfree~name=raise(Term_contains_free_variablename)letltxy=x<yleteqxy=x=yletlam'~name_tyf=ignorename;fletlam~name=lam'~namesize_tyletappfarg=fargletlet_~namemf=ignorename;fmletif_condiftiff=ifcondtheniftelseiffend(* Evaluating implementation. Expects terms to evaluate
to affine combinations with free variables as coefficients.
Fails otherwise.
Takes a substitution as a parameter. *)typeaffine={linear_comb:Free_variable.Sparse_vec.t;const:float}moduleAffine_ops=structmoduleV=Free_variable.Sparse_vecletis_consta=V.is_emptya.linear_comblet(+)a1a2={linear_comb=V.adda1.linear_comba2.linear_comb;const=a1.const+.a2.const;}letsmulc{linear_comb;const}={linear_comb=V.smulclinear_comb;const=c*.const}end(* Substitution for free variables *)typesubst=Free_variable.t->floatoptionexceptionEval_linear_combinationofstringlet()=Printexc.register_printer(funexn->matchexnwith|Eval_linear_combinations->Some(Format.asprintf"Eval_linear_combination: cannot convert node %s"s)|_->None)moduleEval_linear_combination_impl:sigincludeSvalrun:subst->sizerepr->affineend(* multiset of strings = formal linear combinations with integer coefficients *)=structtypesize=floatletsize_ty=Ty.floattype'arepr=subst->'aresultand'aresult=Affine:affine->sizeresult|Bool:bool->boolresultlettrue__=Booltrueletfalse__=Boolfalseletinti_=Affine{const=float_of_inti;linear_comb=Free_variable.Sparse_vec.zero}letfloatf_=Affine{const=f;linear_comb=Free_variable.Sparse_vec.zero}let(+)(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinAffineAffine_ops.(a1+a2)letsat_sub(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1&&Affine_ops.is_consta2thenAffine{linear_comb=Free_variable.Sparse_vec.zero;const=sat_sub_floata1.consta2.const;}elseraise(Eval_linear_combination"sat_sub")let(*)(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1thenAffine(Affine_ops.smula1.consta2)elseifAffine_ops.is_consta2thenAffine(Affine_ops.smula2.consta1)elseraise(Eval_linear_combination"*")let(/)(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta2thenAffine(Affine_ops.smul(1./.a2.const)a1)elseraise(Eval_linear_combination"/")letmax(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1&&Affine_ops.is_consta2thenAffine{linear_comb=Free_variable.Sparse_vec.zero;const=maxa1.consta2.const;}elseraise(Eval_linear_combination"max")letmin(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1&&Affine_ops.is_consta2thenAffine{linear_comb=Free_variable.Sparse_vec.zero;const=mina1.consta2.const;}elseraise(Eval_linear_combination"min")letlog2(x:sizerepr)subst=let(Affinea)=xsubstinifAffine_ops.is_constathenAffine{linear_comb=Free_variable.Sparse_vec.zero;const=loga.const/.log2.;}elseraise(Eval_linear_combination"log2")letsqrt(x:sizerepr)subst=let(Affinea)=xsubstinifAffine_ops.is_constathenAffine{linear_comb=Free_variable.Sparse_vec.zero;const=sqrta.const}elseraise(Eval_linear_combination"sqrt")letfree~namesubst=matchsubstnamewith|Someconst->Affine{const;linear_comb=Free_variable.Sparse_vec.zero}|None->Affine{const=0.0;linear_comb=Free_variable.Sparse_vec.of_list[(name,1.0)];}letlt(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1&&Affine_ops.is_consta2thenBool(a1.const<a2.const)elseraise(Eval_linear_combination"lt")leteq(x1:sizerepr)(x2:sizerepr)subst=let(Affinea1)=x1substinlet(Affinea2)=x2substinifAffine_ops.is_consta1&&Affine_ops.is_consta2thenBool(a1.const=a2.const)elseraise(Eval_linear_combination"eq")letshift_left__=raise(Eval_linear_combination"shift_left")letshift_right__=raise(Eval_linear_combination"shift_right")letlam'~name:__ty_f_subst=raise(Eval_linear_combination"lambda")letlam~name=lam'~namesize_tyletapp_bound_body_subst=raise(Eval_linear_combination"app")letlet_~name:_boundbodysubst=bodyboundsubstletif_(cond:boolrepr)(ift:sizerepr)(iff:sizerepr):sizerepr=funsubst->let(Boolb)=condsubstinifbtheniftsubstelseiffsubstletrun:subst->sizerepr->affine=funsubstrepr->let(Affineres)=reprsubstinresend(* ------------------------------------------------------------------------- *)(* Implementation _transformers_. *)moduletypeTransform=functor(X:S)->sigincludeSwithtypesize=X.sizevalprj:'arepr->'aX.reprendtypetransform=(moduleTransform)letcompose(f:transform)(g:transform):transform=letmoduleF=(valf)inletmoduleG=(valg)inletmoduleG_circ_F(X:S)=structmoduleFX=F(X)moduleGFX=G(FX)includeGFXletprjterm=FX.prj(GFX.prjterm)endin(moduleG_circ_F)(* Identity transform *)moduleIdentity:Transform=functor(X:S)->structincludeXletprjx=xendmoduleSubst(P:sigvalsubst:Free_variable.t->floatend):Transform=functor(X:S)->structincludeXletprjx=xletfree~name=X.float(P.substname)endmoduleHashtbl=Stdlib.Hashtbltype'ahash_consed={repr:'a;hash:int;tag:int}moduleHash_cons:Transform=functor(X:S)->structtypesize=X.sizeletsize_ty=X.size_tytype'arepr='aX.reprhash_consedtypeunique_term_identifier=|Int_tagof{i:int}(* not a tag, actual data! *)|Float_tagof{f:float}(* not a tag, actual data! *)|Add_tagofint*int|Sat_sub_tagofint*int|Mul_tagofint*int|Div_tagofint*int|Max_tagofint*int|Min_tagofint*int|Log2_tagofint|Sqrt_tagofint|Free_tagof{name:Free_variable.t}letprj{repr;_}=repr(* A hashtable for memoizing terms of type `size repr`. We don't
bother hash-consing the rest: this is the sublanguage were sharing
is most useful. *)letsize_table:(int,sizerepr*unique_term_identifier)Hashtbl.t=Hashtbl.create101letfresh=letc=ref~-1infun()->incrc;!cletinsert_if_not_present(term_thunk:unit->sizeX.repr)(uti:unique_term_identifier)=lethash=Hashtbl.hashutiinmatchHashtbl.find_allsize_tablehashwith|[]->lethash_consed={repr=term_thunk();hash;tag=fresh()}inHashtbl.addsize_tablehash(hash_consed,uti);hash_consed|bindings->(matchList.find_opt(fun(_,uti')->uti=uti')bindingswith|None->lethash_consed={repr=term_thunk();hash;tag=fresh()}inHashtbl.addsize_tablehash(hash_consed,uti);hash_consed|Some(res,_)->res)letlift2_nohashfxy=lethash=-1in{repr=fx.repry.repr;hash;tag=fresh()}letfalse_={repr=X.false_;hash=-1;tag=fresh()}lettrue_={repr=X.true_;hash=-1;tag=fresh()}letfloat(f:float)=insert_if_not_present(fun()->X.floatf)(Float_tag{f})letint(i:int)=insert_if_not_present(fun()->X.inti)(Int_tag{i})let(+)xy=insert_if_not_presentX.(fun()->x.repr+y.repr)(Add_tag(x.tag,y.tag))letsat_subxy=insert_if_not_presentX.(fun()->sat_subx.repry.repr)(Sat_sub_tag(x.tag,y.tag))let(*)xy=insert_if_not_presentX.(fun()->x.repr*y.repr)(Mul_tag(x.tag,y.tag))let(/)xy=insert_if_not_presentX.(fun()->x.repr/y.repr)(Div_tag(x.tag,y.tag))letmaxxy=insert_if_not_presentX.(fun()->maxx.repry.repr)(Max_tag(x.tag,y.tag))letminxy=insert_if_not_presentX.(fun()->minx.repry.repr)(Min_tag(x.tag,y.tag))letlog2x=insert_if_not_presentX.(fun()->log2x.repr)(Log2_tagx.tag)letsqrtx=insert_if_not_presentX.(fun()->sqrtx.repr)(Sqrt_tagx.tag)letfree~name=insert_if_not_presentX.(fun()->free~name)(Free_tag{name})letltxy={repr=X.ltx.repry.repr;hash=-1;tag=fresh()}leteqxy={repr=X.eqx.repry.repr;hash=-1;tag=fresh()}(* The functions below are _not_ hash-consed. *)letshift_leftxi=lethash=-1in{repr=X.shift_leftx.repri;hash;tag=fresh()}letshift_rightxi=lethash=-1in{repr=X.shift_rightx.repri;hash;tag=fresh()}letunlift_fun:typeab.(arepr->brepr)->aX.repr->bX.repr=funfx->(f{repr=x;hash=-1;tag=fresh()}).reprletlam'~nametybody={repr=X.lam'~namety(unlift_funbody);hash=-1;tag=fresh()}letlam~name=lam'~namesize_tyletappfarg=lift2_nohashX.appfargletlet_~nameboundbody={repr=X.let_~namebound.repr(unlift_funbody);hash=-1;tag=fresh();}letif_condiftiff={repr=X.if_cond.reprift.repriff.repr;hash=-1;tag=fresh()}end(* [Beta_normalize] evaluates beta-redexes. *)moduleBeta_normalize:Transform=functor(X:S)->structtypesize=X.sizeletsize_ty=X.size_ty(* A value is either a lambda that can be statically evaluated
(case [Static_lam]) or any value that will be
dynamically evaluated (case [Dynamic]). *)type'arepr=|Static_lam:{name:string;ty:'aTy.t;(* type of the argument *)lam:'aX.repr->'brepr;}->('a->'b)repr|Dynamic:'aX.repr->'areprletdyn(x:'aX.repr):'arepr=Dynamicxletrecprj:typea.arepr->aX.repr=funx->matchxwith|Static_lam{name;ty;lam}->X.lam'~namety(funarg->prj(lamarg))|Dynamicd->dletlift1fx=matchxwithDynamicd->dyn(fd)|_->assertfalseletlift2fxy=match(x,y)with|Dynamicd,Dynamice->dyn(fde)|_->assertfalseletfalse_=dynX.false_lettrue_=dynX.true_letfloatf=dyn(X.floatf)letinti=dyn(X.inti)let(+)xy=lift2X.(+)xyletsat_subxy=lift2X.sat_subxylet(*)xy=lift2X.(*)xylet(/)xy=lift2X.(/)xyletmaxxy=lift2X.maxxyletminxy=lift2X.minxyletshift_leftxi=lift1(funx->X.shift_leftxi)xletshift_rightxi=lift1(funx->X.shift_rightxi)xletlog2x=lift1X.log2xletsqrtx=lift1X.sqrtxletfree~name=dyn(X.free~name)letltxy=lift2X.ltxyleteqxy=lift2X.eqxyletlam':name:string->'aTy.t->('arepr->'brepr)->('a->'b)repr=fun~nametyf->letlamarg=f(dynarg)inStatic_lam{name;ty;lam}letlam~name=lam'~namesize_tyletapp:typeab.(a->b)repr->arepr->brepr=funfarg->matchfwith|Static_lam{lam;_}->lam(prjarg)|Dynamicdyn_f->Dynamic(X.appdyn_f(prjarg))letlet_:typeab.name:string->arepr->(arepr->brepr)->brepr=fun~namemf->Dynamic(X.let_~name(prjm)(funx->prj(f(dynx))))letif_condiftiff=Dynamic(X.if_(prjcond)(prjift)(prjiff))end(* As the type indicates, this is a simplified CPS transform designed to
lift let-bindings out of subexpressions. Warning: this transformation
does not check that the ~name arguments (used for pretty printing)
are globally distinct for let bindings. *)moduleLet_lift:Transform=functor(X:S)->structtypesize=X.sizeletsize_ty=X.size_tytype'acps={cont:'b.('a->'bX.repr)->'bX.repr}type'arepr='aX.reprcpsletprjterm=term.cont(funx->x)letretx={cont=(funk->kx)}letlift_binopopxy={cont=(funk->x.cont(funx->y.cont(funy->k(opxy))))}letlift_unopopx={cont=(funk->x.cont(funx->k(opx)))}letfalse_=retX.false_lettrue_=retX.true_letfloatf=ret(X.floatf)letinti=ret(X.inti)let(+)=lift_binopX.(+)letsat_sub=lift_binopX.sat_sublet(*)=lift_binopX.(*)let(/)=lift_binopX.(/)letmax=lift_binopX.maxletmin=lift_binopX.minletshift_leftxi={cont=(funk->x.cont(funx->k(X.shift_leftxi)))}letshift_rightxi={cont=(funk->x.cont(funx->k(X.shift_rightxi)))}letlog2=lift_unopX.log2letsqrt=lift_unopX.sqrtletfree~name=ret(X.free~name)letlt=lift_binopX.ltleteq=lift_binopX.eqletlam'~namety(f:'arepr->'brepr)={cont=(funk->k(X.lam'~namety(funx->prj(f(retx)))))}letlam~name=lam'~namesize_tyletappfarg={cont=(funk->k(X.app(prjf)(prjarg)))}letlet_~name(m:'arepr)(f:'arepr->'brepr):'brepr={cont=(funk->X.let_~name(prjm)(funmres->k(prj(f(retmres)))));}letif_condiftiff={cont=(funk->cond.cont(funcond->k@@X.if_cond(prjift)(prjiff)));}end(* Instantiate model over partially evaluating & hash-consing cost
function DSL *)moduleHash_cons_vector=Hash_cons(Eval_linear_combination_impl)moduleEval_to_vector=Beta_normalize(Hash_cons_vector)moduleFold_constants(X:S)=structtypesize=X.sizeletsize_ty=X.size_tytype'amaybe_const=|Int:int->sizemaybe_const|Float:float->sizemaybe_const|Bool:bool->boolmaybe_const|Not_const:'aX.repr->'amaybe_consttype'arepr='amaybe_constletprj:typea.amaybe_const->aX.repr=function|Inti->X.inti|Floatf->X.floatf|Boolfalse->X.false_|Booltrue->X.true_|Not_constterm->termletinjx=Not_constxletfalse_=Boolfalselettrue_=Booltrueletfloatf=Floatfletinti=Intiletarith_opop_iop_fop_xxy=match(x,y)with|Inti,Intj->Int(op_iij)|Floati,Floatj->Float(op_fij)|Inti,Floatj->Float(op_f(float_of_inti)j)|Floati,Intj->Float(op_fi(float_of_intj))|Not_constterm,Inti->Not_const(op_xterm(X.inti))|Inti,Not_constterm->Not_const(op_x(X.inti)term)|Not_constterm,Floati->Not_const(op_xterm(X.floati))|Floati,Not_constterm->Not_const(op_x(X.floati)term)|Not_constx,Not_consty->Not_const(op_xxy)|Bool_,_|_,Bool_->assertfalselet(+)xy=match(x,y)with|Int0,term|Float0.0,term|term,Int0|term,Float0.0->term|_->arith_op(+)(+.)X.(+)xylet(*)xy=match(x,y)with|Int0,_|Float0.0,_|_,Int0|_,Float0.0->Int0|Int1,term|Float1.0,term|term,Int1|term,Float1.0->term|_->arith_op(*)(*.)X.(*)xyletsat_subxy=match(x,y)with|term,Int0|term,Float0.0->term|_->arith_opsat_sub_intsat_sub_floatX.sat_subxylet(/)xy=match(x,y)with|term,Int1->term|term,Float1.0->term(* The next cases are here to avoid introducing floating point constants from the division *)|Inti,Intj->Not_constX.(inti/intj)|Floati,Floatj->Not_constX.(floati/floatj)|Inti,Floatj->Not_constX.(inti/floatj)|Floati,Intj->Not_constX.(floati/intj)|_->arith_op(/)(/.)X.(/)xyletmax=arith_opmaxmaxX.maxletmin=arith_opminminX.minletshift_leftxs=inj@@matchxwith|Inti->X.(shift_left(inti)s)|Floatf->X.(shift_left(floatf)s)|Not_constterm->X.(shift_leftterms)|Bool_->assertfalseletshift_rightxs=inj@@matchxwith|Inti->X.(shift_right(inti)s)|Floatf->X.(shift_right(floatf)s)|Not_constterm->X.(shift_rightterms)|Bool_->assertfalseletlog2x=matchxwith|Int1->Int0|Inti->inj@@X.(log2(inti))|Float1.->Float0.|Floatf->inj@@X.(log2(floatf))|Not_constterm->inj@@X.(log2term)|Bool_->assertfalseletsqrtx=inj@@matchxwith|Inti->X.(sqrt(inti))|Floatf->X.(sqrt(floatf))|Not_constterm->X.(sqrtterm)|Bool_->assertfalseletfree~name=Not_const(X.free~name)letltxy=match(x,y)with|Inti,Intj->Bool(i<j)|Floati,Floatj->Bool(i<j)|Floati,Intj->Bool(i<float_of_intj)|Inti,Floatj->Bool(float_of_inti<j)|Not_constterm,Inti->Not_constX.(ltterm(inti))|Inti,Not_constterm->Not_constX.(lt(inti)term)|Not_constterm,Floati->Not_constX.(ltterm(floati))|Floati,Not_constterm->Not_constX.(lt(floati)term)|Not_constx,Not_consty->Not_constX.(ltxy)|Bool_,_|_,Bool_->assertfalseleteqxy=match(x,y)with|Inti,Intj->Bool(i=j)|Floati,Floatj->Bool(i=j)|Floati,Intj->Bool(i=float_of_intj)|Inti,Floatj->Bool(float_of_inti=j)|Not_constterm,Inti->Not_constX.(eqterm(inti))|Inti,Not_constterm->Not_constX.(eq(inti)term)|Not_constterm,Floati->Not_constX.(eqterm(floati))|Floati,Not_constterm->Not_constX.(eq(floati)term)|Not_constx,Not_consty->Not_constX.(eqxy)|Bool_,_|_,Bool_->assertfalseletlam'~namety(f:'arepr->'brepr)=Not_const(X.lam'~namety(funx->prj(f(injx))))letlam~name=lam'~namesize_tyletappfarg=Not_const(X.app(prjf)(prjarg))letlet_~name(typea)(m:arepr)(f:arepr->'brepr):'brepr=matchmwith|Int_|Float_|Bool_->(* let x = const in e => e[const/x] *)fm|Not_const_->Not_const(X.let_~name(prjm)(funx->prj(f(injx))))letif_condiftiff=matchcondwith|Booltrue->ift|Boolfalse->iff|Not_constterm->Not_const(X.if_term(prjift)(prjiff))|Int_|Float_->assertfalseend