12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469(* elpi: embedded lambda prolog interpreter *)(* license: GNU Lesser General Public License Version 2.1 or later *)(* ------------------------------------------------------------------------- *)openElpi_utilopenElpi_parseropenElpi_runtimeopenElpi_compilermoduletypeRuntime=(moduletypeofRuntime_trace_off)letr=ref(moduleRuntime_trace_off:Runtime)letset_runtimeb=beginmatchbwith|true->r:=(moduleRuntime:Runtime)|false->r:=(moduleRuntime_trace_off:Runtime)end;letmoduleR=(val!r)inUtil.set_spaghetti_printerUtil.pp_constR.Pp.pp_constantletset_traceargv=letargs=Trace_ppx_runtime.Runtime.parse_argvargvinset_runtime!Trace_ppx_runtime.Runtime.debug;argsmoduleSetup=structmoduleStrMap=Util.StrMaptypestate_descriptor=Data.State.descriptortypequotations_descriptor=Compiler_data.QuotationHooks.descriptorreftypehoas_descriptor=Data.HoasHooks.descriptorreftypecalc_descriptor=Data.CalcHooks.descriptorrefletdefault_state_descriptor=Data.State.new_descriptor()letdefault_quotations_descriptor=Compiler_data.QuotationHooks.new_descriptor()letdefault_hoas_descriptor=Data.HoasHooks.new_descriptor()letdefault_calc_descriptor=Data.CalcHooks.new_descriptor()typebuiltins=Compiler.builtinstypeelpi={parser:(moduleParse.Parser);resolver:?cwd:string->unit:string->unit->string;header:Compiler.header}typeflags=Compiler.flagsletinit?(versions=Elpi_util.Util.StrMap.empty)?(flags=Compiler.default_flags)?(state=default_state_descriptor)?(quotations=default_quotations_descriptor)?(hoas=default_hoas_descriptor)?(calc=default_calc_descriptor)~builtins?file_resolver():elpi=(* At the moment we can only init the parser once *)letfile_resolver=matchfile_resolverwith|Somex->x|None->fun?cwd:_~unit:_()->raise(Failure"'accumulate' is disabled since Setup.init was not given a ~file_resolver.")inletparser=(moduleParse.Make(structletversions=versionsletresolver=file_resolverend):Parse.Parser)inData.Global_symbols.lock();letheader_src=builtins|>List.map(fun(fname,decls)->(* This is a bit ugly, since we print and then parse... *)letb=Buffer.create1024inletfmt=Format.formatter_of_bufferbinData.BuiltInPredicate.documentfmtdecls(List.rev!calc);Format.pp_print_flushfmt();lettext=Buffer.contentsbinletlexbuf=Lexing.from_stringtextinletmoduleP=(valparser)intryP.program_from~loc:(Util.Loc.initialfname)lexbufwithParse.ParseError(loc,msg)->List.iteri(funis->Printf.eprintf"%4d: %s\n"(i+1)s)(Re.Str.(split_delim(regexp_string"\n")text));begintryPrintf.eprintf"Excerpt of %s:\n%s\n"fname(String.subtextloc.Util.Loc.line_starts_atUtil.Loc.(loc.source_stop-loc.line_starts_at))with_->(* loc could be bogus *)();end;Util.anomaly~locmsg)inletheader=tryCompiler.header_of_ast~flags~parserstate!quotations!hoas!calcbuiltins(List.concatheader_src)withCompiler_data.CompileError(loc,msg)->Util.anomaly?locmsgin{parser;header;resolver=file_resolver}lettrace=set_traceletusage=Trace_ppx_runtime.Runtime.usagetypewarning_id=Util.warning_id=LinearVariable|UndeclaredGlobal|FlexClause|ImplicationPrecedenceletset_warn=Util.set_warnletset_error=Util.set_errorletset_anomaly=Util.set_anomalyletset_type_error=Util.set_type_errorletset_std_formatter=Util.set_std_formatterletset_err_formatterfmt=Util.set_err_formatterfmt;Trace_ppx_runtime.Runtime.(set_trace_outputTTYfmt)endmoduleEA=AstmoduleAst=structtypeprogram=Ast.Program.ttypequery=Ast.Goal.tmoduleLoc=Util.LocmoduleGoal=Ast.GoalmoduleScope=Compiler_data.ScopemoduleTerm=Compiler_data.ScopedTerm.QTermmoduleType=Compiler_data.ScopedTypeExpression.SimpleTypemoduleName=structincludeAst.Functypeconstant=intletis_globalfi=equalf(Util.Constants.Map.findiData.Global_symbols.table.c2s|>Data.Symbol.get_func)endmoduleOpaque=Util.CDataendmoduleParse=structletprogram~elpi:{Setup.parser}~files=letmoduleP=(valparser)inList.(concat(map(funfile->P.program~file)files))letprogram_from~elpi:{Setup.parser}~locbuf=letmoduleP=(valparser)inP.program_from~locbufletgoal~elpi:{Setup.parser}~loc~text=letmoduleP=(valparser)inP.goal~loc~textletgoal_from~elpi:{Setup.parser}~locbuf=letmoduleP=(valparser)inP.goal_from~locbufexceptionParseError=Elpi_parser.Parser_config.ParseErrorletresolve_file~elpi:{Setup.resolver}=resolverletstd_resolver=Elpi_util.Util.std_resolverendmoduleED=DatamoduleData=structtypeterm=Data.termtypeconstraints=Data.constraintstypestate=Data.State.ttypepretty_printer_context=ED.pp_ctxmoduleStrMap=Util.StrMaptypesolution={assignments:termStrMap.t;constraints:constraints;state:state;pp_ctx:pretty_printer_context;relocate_assignment_to_runtime:target:Compiler.program->depth:int->string->(term,string)Stdlib.Result.t}typehyp=Data.clause_src={hdepth:int;hsrc:term}typehyps=hyplistendmoduleCompile=structtypeprogram=Compiler.programtypequery=Compiler.querytypeexecutable=ED.executabletypescoped_program=Compiler.scoped_programtypecompilation_unit=Compiler.checked_compilation_unittypecompilation_unit_signature=Compiler.checked_compilation_unit_signatureexceptionCompileError=Compiler_data.CompileErrorletto_setup_flagsx=xletprogram?(flags=Compiler.default_flags)~elpi:{Setup.header}l=Compiler.program_of_ast~flags~header(List.flattenl)letempty_base~elpi:{Setup.header}=Compiler.empty_base~headerletquerys_pt=Compiler.query_of_asts_pt(funst->st)lettotal_type_checking_timeq=Compiler.total_type_checking_timeqlettotal_det_checking_timeq=Compiler.total_det_checking_timeqmoduleStrSet=Util.StrSettypeflags=Compiler.flags={defined_variables:StrSet.t;print_units:bool;time_typechecking:bool;skip_det_checking:bool;}letdefault_flags=Compiler.default_flagsletoptimize=Compiler.optimize_queryletscope?(flags=Compiler.default_flags)~elpi:{Setup.header}a=Compiler.scoped_of_ast~flags~headeraletunit?(flags=Compiler.default_flags)~elpi:{Setup.header}~base?builtinsx=Compiler.unit_of_scoped~flags~header?builtinsx|>Compiler.check_unit~flags~baseletextend?(flags=Compiler.default_flags)~baseu=Compiler.append_unit~flags~baseuletsignatureu=Compiler.signature_of_checked_compilation_unituletextend_signature?(flags=Compiler.default_flags)~baseu=Compiler.append_unit_signature~flags~baseumoduleIntervalTree=Compiler.IntervalTreetypetype_=Compiler.type_letpp_type_=Compiler.pp_type_typeinfo=Compiler.info={defined:Ast.Loc.toption;type_:type_option}letpp_info=Compiler.pp_infolethover=Compiler.hoverendmoduleExecute=structtypeoutcome=SuccessofData.solution|Failure|NoMoreStepsletrecuvar2discard~deptht=letopenEDinletmoduleR=(val!r)inmatchR.deref_head~depthtwith|App(c,x,xs)->mkAppc(uvar2discard~depthx)(List.map(uvar2discard~depth)xs)|Cons(x,xs)->mkCons(uvar2discard~depthx)(uvar2discard~depthxs)|Lamx->mkLam(uvar2discard~depth:(depth+1)x)|Builtin(c,xs)->mkBuiltinc(List.map(uvar2discard~depth)xs)|UVar_|AppUVar_->mkDiscard|Arg_|AppArg_->assertfalse|Const_|Nil|CData_|Discard->tletmap_outcomefull_derefhmove=function|ED.Failure->Failure|ED.NoMoreSteps->NoMoreSteps|ED.Success{ED.assignments;constraints;state;pp_ctx;state_for_relocation=(idepth,from);}->Success{assignments;constraints;state;pp_ctx;relocate_assignment_to_runtime=(fun~target~depths->Compiler.relocate_closed_term~from(Util.StrMap.findsassignments|>full_deref~depth:idepth|>uvar2discard~depth:idepth)~to_:target|>Stdlib.Result.map(hmove?oc:None~from:depth~to_:depth));}letonce?max_steps?delay_outside_fragmentp=letmoduleR=(val!r)inmap_outcomeR.full_derefR.hmove@@R.execute_once?max_steps?delay_outside_fragmentpletloop?delay_outside_fragmentp~more~pp=letmoduleR=(val!r)inR.execute_loop?delay_outside_fragmentp~more~pp:(funto->ppt(map_outcomeR.full_derefR.hmoveo))endmodulePp=structlettermpp_ctxft=(* XXX query depth *)letmoduleR=(val!r)inletopenRinPp.uppterm~pp_ctx0[]~argsdepth:0[||]ftletconstraintspp_ctxfc=letmoduleR=(val!r)inletopenRinUtil.pplist~boxed:true(pp_stuck_goal~pp_ctx)""fcletstate=ED.State.ppletprogramfc=letmoduleR=(val!r)inletopenRinCompiler.pp_program(fun~pp_ctx~depth->Pp.uppterm~pp_ctxdepth[]~argsdepth:0[||])fcletgoalfc=letmoduleR=(val!r)inletopenRinCompiler.pp_goal(fun~pp_ctx~depth->Pp.uppterm~pp_ctxdepth[]~argsdepth:0[||])fcmoduleAst=structletprogram=EA.Program.ppletquery=EA.Goal.ppendend(****************************************************************************)moduleConversion=structtypety_ast=ED.Conversion.ty_ast=TyNameofstring|TyAppofstring*ty_ast*ty_astlisttypeextra_goal=ED.Conversion.extra_goal=..typeextra_goal+=|Unify=ED.Conversion.Unifytypeextra_goals=extra_goallisttype'aembedding='aED.Conversion.embeddingtype'areadback='aED.Conversion.readbacktype'at='aED.Conversion.t={ty:ty_ast;pp_doc:Format.formatter->unit->unit;pp:Format.formatter->'a->unit;embed:'aembedding;(* 'a -> term *)readback:'areadback;(* term -> 'a *)}exceptionTypeErr=ED.Conversion.TypeErrendmoduleContextualConversion=ED.ContextualConversionmoduleRawOpaqueData=structtypename=stringtypedoc=stringtype'adeclaration={name:name;doc:doc;pp:Format.formatter->'a->unit;compare:'a->'a->int;hash:'a->int;hconsed:bool;constants:(name*'a)list;(* global constants of that type, eg "std_in" *)}typet=Util.CData.ttype'acdata={cin:'a->Data.term;cino:'a->Ast.Opaque.t;isc:t->bool;cout:t->'a;name:string;}letconversion_of_cdata~name?(doc="")~constants_map~values_map~constants~pp({Util.CData.cin;isc;cout;name=c})=letty=Conversion.TyNamenameinletcinox=cinxinletcinx=letmoduleR=(val!r)intryR.mkConst(values_mapx)withNot_found->ED.Term.CData(cinx)inletembed~depth:_statex=state,cinx,[]inletreadback~depthstatet=letmoduleR=(val!r)inletopenRinmatchderef_head~depthtwith|ED.Term.CDatacwheniscc->state,coutc,[]|ED.Term.Constiastwheni<0->begintrystate,Util.Constants.Map.findiconstants_map,[]withNot_found->raise(Conversion.TypeErr(ty,depth,t))end|t->raise(Conversion.TypeErr(ty,depth,t))inletpp_docfmt()=ifdoc<>""thenbeginED.BuiltInPredicate.pp_commentfmt("% "^doc);Format.fprintffmt"@\n";end;Format.fprintffmt"@[<hov 2>kind %s type.@]@\n@\n"name;List.iter(fun(variant,(c,_))->Format.fprintffmt"@[<hov 2>external symbol %s : %s = \"%d\".@]@\n"cnamevariant)constantsin{cin;cino;cout;isc;name=c},{Conversion.embed;readback;ty;pp_doc;pp}letconversion_of_cdata(typea)~name?doc?(constants=[])~compare~ppcd=letmoduleVM=Map.Make(structtypet=aletcompare=compareend)inletconstants_map,values_map,constants=List.fold_right(fun(n,v)(cm,vm,cl)->letc,variant=ED.Global_symbols.declare_overloaded_global_symbolninUtil.Constants.Map.addcvcm,VM.addvcvm,(variant,(n,v))::cl)constants(Util.Constants.Map.empty,VM.empty,[])inletvalues_mapx=VM.findxvalues_mapinconversion_of_cdata~name?doc~constants_map~values_map~constants:(List.revconstants)~ppcdletdeclare{name;doc;pp;compare;hash;hconsed;constants;}=letcdata=Util.CData.declare{data_compare=compare;data_pp=pp;data_hash=hash;data_name=name;data_hconsed=hconsed;}inconversion_of_cdata~name~doc~constants~compare~ppcdataletmorph1{cin;cout}fx=cin(f(coutx))letmorph2{cin;cout}fxy=cin(f(coutx)(couty))letmap{cout}{cin}fx=cin(f(coutx))letty2{isc}xy=iscx&&iscylethcons=Util.CData.hconsletname=Util.CData.namelethash=Util.CData.hashletcompare=Util.CData.compareletshow=Util.CData.showletpp=Util.CData.ppletequal=Util.CData.equalletint=let{Util.CData.cin;cout;isc;name}=ED.C.intin{cin=(funx->ED.mkCData(cinx));cino=cin;cout;isc;name}letis_int=ED.C.is_intletto_int=ED.C.to_intletof_int=ED.C.of_intletfloat=let{Util.CData.cin;cout;isc;name}=ED.C.floatin{cin=(funx->ED.mkCData(cinx));cino=cin;cout;isc;name}letis_float=ED.C.is_floatletto_float=ED.C.to_floatletof_float=ED.C.of_floatletstring=let{Util.CData.cin;cout;isc;name}=ED.C.stringin{cin=(funx->ED.mkCData(cinx));cino=cin;cout;isc;name}letis_string=ED.C.is_stringletto_string=ED.C.to_stringletof_string=ED.C.of_stringletloc=let{Util.CData.cin;cout;isc;name}=ED.C.locin{cin=(funx->ED.mkCData(cinx));cino=cin;cout;isc;name}letis_loc=ED.C.is_locletto_loc=ED.C.to_locletof_loc=ED.C.of_locendmoduleOpaqueData=structtypename=stringtypedoc=stringtype'adeclaration='aRawOpaqueData.declaration={name:name;doc:doc;pp:Format.formatter->'a->unit;compare:'a->'a->int;hash:'a->int;hconsed:bool;constants:(name*'a)list;(* global constants of that type, eg "std_in" *)}letdeclarex=snd@@RawOpaqueData.declarexendmoduleBuiltInData=structletint=snd@@RawOpaqueData.conversion_of_cdata~name:"int"~compare:(funxy->x-y)~pp:(funfmtx->Util.CData.ppfmt(ED.C.int.Util.CData.cinx))ED.C.intletfloat=snd@@RawOpaqueData.conversion_of_cdata~name:"float"~compare:Float.compare~pp:(funfmtx->Util.CData.ppfmt(ED.C.float.Util.CData.cinx))ED.C.floatletstring=snd@@RawOpaqueData.conversion_of_cdata~name:"string"~compare:String.compare~pp:(funfmtx->Util.CData.ppfmt(ED.C.string.Util.CData.cinx))ED.C.stringletloc=snd@@RawOpaqueData.conversion_of_cdata~name:"loc"~compare:Util.Loc.compare~pp:(funfmtx->Util.CData.ppfmt(ED.C.loc.Util.CData.cinx))ED.C.locletpolyty=letembed~depth:_statex=state,x,[]inletreadback~depthstatet=state,t,[]in{Conversion.embed;readback;ty=Conversion.TyNamety;pp=(funfmt_->Format.fprintffmt"<poly>");pp_doc=(funfmt()->())}letany=poly"any"letfresh_copytdepth=letmoduleR=(val!r)inletopenRinletopenEDinletrecauxdt=matchderef_head~depth:(depth+d)twith|Lamt->mkLam(aux(d+1)t)|Constcasx->ifc<0||c>=depththenxelseraiseConversion.(TypeErr(TyName"closed term",depth+d,x))|App(c,x,xs)->ifc<0||c>=depththenmkAppc(auxdx)(List.map(auxd)xs)elseraiseConversion.(TypeErr(TyName"closed term",depth+d,x))|(UVar_|AppUVar_)asx->raiseConversion.(TypeErr(TyName"closed term",depth+d,x))|Arg_|AppArg_->assertfalse|Builtin(c,xs)->mkBuiltinc(List.map(auxd)xs)|CData_asx->x|Cons(hd,tl)->mkCons(auxdhd)(auxdtl)|Nilasx->x|Discardasx->xin(aux0t,depth)letclosedty=letty=Conversion.(TyNamety)inletembed~depthstate(x,from)=letmoduleR=(val!r)inletopenRinstate,hmove~from~to_:depth?oc:Nonex,[]inletreadback~depthstatet=state,fresh_copytdepth,[]in{Conversion.embed;readback;ty;pp=(funfmt(t,d)->letmoduleR=(val!r)inletopenRinPp.upptermd[]~argsdepth:dED.empty_envfmtt);pp_doc=(funfmt()->())}letmap_accfsl=letrecauxaccextras=function|[]->s,List.revacc,List.(concat(revextra))|x::xs->lets,x,gls=fsxinaux(x::acc)(gls::extra)sxsinaux[][]slletlistd=letembed~depthsl=letmoduleR=(val!r)inletopenRinlets,l,eg=map_acc(d.Conversion.embed~depth)slins,list_to_lp_listl,eginletreadback~depthst=letmoduleR=(val!r)inletopenRinmap_acc(d.Conversion.readback~depth)s(lp_list_to_list~deptht)inletppfmtl=Format.fprintffmt"[%a]"(Util.pplistd.pp~boxed:true"; ")lin{Conversion.embed;readback;ty=TyApp("list",d.ty,[]);pp;pp_doc=(funfmt()->())}endmoduleElpi=structtypet=ED.uvarletpp=Compiler.pp_uvar_bodyletshowm=Format.asprintf"%a"ppmletpp_raw=Compiler.pp_uvar_body_rawletshow_rawm=Format.asprintf"%a"pp_rawmletequalh1h2=h1==h2lethash=ED.uvar_idletfresh_name=leti=ref0infun()->incri;Printf.sprintf"_uvk_%d_"!iletfresh()=Ast.Name.from_string@@fresh_name()letalloc_Elpinamestate=letmoduleR=(val!r)instate,(ED.oref~depth:0ED.dummy)letmake?namestate=matchnamewith|None->alloc_Elpi(fresh_name())state|Somename->trystate,Util.StrMap.findname(ED.State.getCompiler.uvkstate)withNot_found->letstate,k=alloc_ElpinamestateinED.State.updateCompiler.uvkstate(Util.StrMap.addnamek),kletget~namestate=trySome(Util.StrMap.findname(ED.State.getCompiler.uvkstate))withNot_found->NoneendmoduleRawData=structtypeconstant=Util.constanttypebuiltin=ED.builtin_predicate=Cut|And|Impl|ImplBang|RImpl|Pi|Sigma|Eq|Match|Findall|Delay|Hostofconstanttypeterm=ED.Term.termtypeview=(* Pure subterms *)|Constofconstant(* global constant or a bound var *)|Lamofterm(* lambda abstraction, i.e. x\ *)|Appofconstant*term*termlist(* application (at least 1 arg) *)(* Optimizations *)|Consofterm*term(* :: *)|Nil(* [] *)(* FFI *)|Builtinofbuiltin*termlist(* call to a built-in predicate *)|CDataofRawOpaqueData.t(* external data *)(* Unassigned unification variables *)|UnifVarofElpi.t*termlist[@@warning"-37"]letreclook~deptht=letmoduleR=(val!r)inletopenRinmatchderef_head~depthtwith|ED.Term.Arg_|ED.Term.AppArg_->assertfalse|ED.Term.AppUVar(ub,args)whenub.vardepth==0->UnifVar(ub,args)|ED.Term.AppUVar(ub,args)->look~depth(R.expand_appuvub~depth~args)|ED.Term.UVar(ub,ano)->look~depth(R.expand_uvub~depth~ano)|ED.Term.Discard->letub=ED.oref~depth:0ED.dummyinUnifVar(ub,R.mkinterval0depth0)|ED.Term.Lam_ast->beginmatchR.eta_contract_flex~depthtwith|None->Obj.magict(* HACK: view is a "subtype" of Term.term *)|Somet->look~depthtend|x->Obj.magicx(* HACK: view is a "subtype" of Term.term *)letkool=function|UnifVar(ub,args)->ED.Term.AppUVar(ub,args)|x->Obj.magicx[@@inline]letmkConstn=letmoduleR=(val!r)inR.mkConstnletmkLam=ED.Term.mkLamletmkApp=ED.Term.mkAppletmkAppGlobalixxs=ifi>=0thenUtil.anomaly"mkAppGlobal: got a bound variable";ED.Term.mkAppixxsletmkAppBoundixxs=ifi<0thenUtil.anomaly"mkAppBound: got a global constant";ED.Term.mkAppixxsletmkCons=ED.Term.mkConsletmkNil=ED.Term.mkNilletmkDiscard=ED.Term.mkDiscardletmkBuiltincl=ED.Term.mkBuiltinclletmkCData=ED.Term.mkCDataletmkAppBoundLxl=ifx<0thenUtil.anomaly"mkAppBoundL: got a global constant";letmoduleR=(val!r)inR.mkAppLxlletmkAppGlobalLxl=ifx>=0thenUtil.anomaly"mkAppBoundL: got a bound variable";letmoduleR=(val!r)inR.mkAppLxlletmkGlobali=ifi>=0thenUtil.anomaly"mkGlobal: got a bound variable";mkConstiletmkBoundi=ifi<0thenUtil.anomaly"mkBound: got a global constant";mkConstiletcmp_builtin=ED.compare_builtin_predicateletmkAppMoreArgs~depthhdargs=letmoduleR=(val!r)inletopenRinmatchderef_head~depthhd,argswith|Constc,[]->hd|Constc,x::xs->mkAppcxxs|App(c,x,xs),_->mkAppcx(xs@args)|Arg_,[]->hd|Arg(i,ano),xs->AppArg(i,mkinterval0ano0@xs)|AppArg(i,args),xs->AppArg(i,args@xs)|_->assertfalseletisApp~depthhd=letmoduleR=(val!r)inletopenRinmatchderef_head~depthhdwith|App_->true|_->falsemoduleConstants=structletdeclare_global_symbol?variantx=beginmatchvariantwith|Somen->ifn<1thenUtil.error"declare_global_symbol: variants are >= 0"|None->()end;ED.Global_symbols.declare_global_symbol?variantxletshowc=Util.Constants.showcletorc=ED.Global_symbols.orcmoduleMap=Util.Constants.MapmoduleSet=Util.Constants.Setendletof_hypx=xletof_hypsx=xtypehyp=Data.hyp={hdepth:int;hsrc:term}typehyps=hyplisttypeblockers=Elpi.tlisttypesuspended_goal=ED.suspended_goal={context:hyps;goal:int*term;blockers:blockers;}letconstraintsl=letmoduleR=(val!r)inletopenRinUtil.map_filter(fun(x:ED.stuck_goal)->get_suspended_goalx.ED.blockersx.ED.kind)lletno_constraints=[]letmkUnifVarub~argsstate=ifargs=[]thenED.Term.mkUVarub0elseED.Term.mkAppUVarubargstypeConversion.extra_goal+=|RawGoal=ED.Conversion.RawGoalletset_extra_goals_postprocessing?(descriptor=Setup.default_hoas_descriptor)x=ED.HoasHooks.set_extra_goals_postprocessing~descriptorxletnew_hoas_descriptor=ED.HoasHooks.new_descriptorendmoduleFlexibleData=structmoduleElpi=ElpimoduletypeHost=sigtypetvalcompare:t->t->intvalpp:Format.formatter->t->unitvalshow:t->stringend(* Bijective map between elpi UVar and host equivalent *)letuvmap_no=ref0moduleMap=functor(T:Host)->structopenUtilmoduleH2E=Map.Make(T)typet={h2e:Elpi.tH2E.t;e2h:T.tIntMap.t}letempty={h2e=H2E.empty;e2h=IntMap.empty}letadduvv{h2e;e2h}=leth2e=H2E.addvuvh2ein{h2e;e2h=IntMap.add(ED.uvar_iduv)ve2h}letelpiv{h2e}=H2E.findvh2elethostub{e2h}=IntMap.find(ED.uvar_idub)e2hletremove_bothubv{h2e;e2h}=leth2e=H2E.removevh2ein{h2e;e2h=IntMap.remove(ED.uvar_idub)e2h}letremove_elpikm=letv=hostkminremove_bothkvmletremove_hostvm=lethandle=elpivminremove_bothhandlevmletfilterf{h2e;e2h}=lete2h=IntMap.filter(funubv->fv(H2E.findvh2e))e2hinleth2e=H2E.filterfh2ein{h2e;e2h}letfoldf{h2e}acc=letmoduleR=(val!r)inletopenRinletget_val{ED.Term.contents=ub}=ifub!=ED.dummythenSome(deref_head~depth:0ub)elseNoneinH2E.fold(funkukacc->fkuk(get_valuk)acc)h2eaccletuvn=incruvmap_no;!uvmap_noletppfmt(m:t)=letppkuv_()=Format.fprintffmt"@[<h>%a@ <-> %a@]@ "T.ppkElpi.ppuvinFormat.fprintffmt"@[<hov>";foldppm();Format.fprintffmt"@]";;letshowm=Format.asprintf"%a"ppmletuvmap=ED.State.declare~descriptor:ED.elpi_state_descriptor~name:(Printf.sprintf"elpi:uvm:%d"uvn)~pp~clause_compilation_is_over:(funx->empty)~compilation_is_over:(funx->Somex)~execution_is_over:(funx->Somex)~init:(fun()->empty)()endmoduletypeShow=Util.Showletuvar={Conversion.ty=Conversion.TyName"uvar";pp_doc=(funfmt()->Format.fprintffmt"Unification variable, as the uvar keyword");pp=(funfmt(k,_)->Format.fprintffmt"%a"Elpi.ppk);embed=(fun~depths(k,args)->s,RawData.mkUnifVark~argss,[]);readback=(fun~depthstatet->matchRawData.look~depthtwith|RawData.UnifVar(k,args)->state,(k,args),[]|_->raise(Conversion.TypeErr(TyName"uvar",depth,t)));}endmoduleAlgebraicData=structincludeED.BuiltInPredicate.ADTtypename=stringtypedoc=stringletallocate_constructorsx=letmoduleR=(val!r)inED.BuiltInPredicate.ADT.allocate_constructors~look:R.deref_head~mkinterval:R.mkinterval~mkConst:R.mkConst~alloc:FlexibleData.Elpi.make~mkUnifVar:RawData.mkUnifVarxletdeclare_allocatedallocx=letmoduleR=(val!r)inED.BuiltInPredicate.ADT.declare_allocated~look:R.deref_head~mkinterval:R.mkinterval~mkConst:R.mkConst~alloc:FlexibleData.Elpi.make~mkUnifVar:RawData.mkUnifVarallocxletdeclarex=beginmatchx.ED.BuiltInPredicate.ADT.tywith|TyApp(s,_,_)->Util.error("Declaration of "^s^" requires allocate_constructors + declare_allocated")|TyName_->()end;letx=ED.BuiltInPredicate.ADT.Declxinletalloc=allocate_constructorsxindeclare_allocatedallocxendmoduleBuiltInPredicate=structtypeonce=depth:int->Data.term->Data.state->Data.stateincludeED.BuiltInPredicateexceptionNo_clause=ED.No_clauseletmkDatax=DataxletioargCa=letopenContextualConversionin{awithpp=(funfmt->functionDatax->a.ppfmtx|NoData->Format.fprintffmt"_");embed=(fun~depthhypscstsstate->function|Datax->a.embed~depthhypscstsstatex|NoData->assertfalse);readback=(fun~depthhypscstsstatet->letmoduleR=(val!r)inletopenRinletrecauxt=matchderef_head~depthtwith|ED.Term.Arg_|ED.Term.AppArg_->assertfalse|ED.Term.UVar_|ED.Term.AppUVar_|ED.Term.Discard->state,NoData,[]|ED.Term.Lam_->beginmatchR.eta_contract_flex~depthtwith|None->state,NoData,[]|Somet->auxtend|_->letstate,x,gls=a.readback~depthhypscstsstatetinstate,mkDatax,glsinauxt);}letioarga=letopenContextualConversionin!<(ioargC(!>a))letioargC_flexa=letopenContextualConversionin{awithpp=(funfmt->functionDatax->a.ppfmtx|NoData->Format.fprintffmt"_");embed=(fun~depthhypscstsstate->function|Datax->a.embed~depthhypscstsstatex|NoData->assertfalse);readback=(fun~depthhypscstsstatet->letmoduleR=(val!r)inletopenRinmatchderef_head~depthtwith|ED.Term.Arg_|ED.Term.AppArg_->assertfalse|ED.Term.Discard->state,NoData,[]|_->letstate,x,gls=a.readback~depthhypscstsstatetinstate,mkDatax,gls);}letioarg_flexa=letopenContextualConversionin!<(ioargC_flex(!>a))letioarg_any=letopenConversionin{BuiltInData.anywithpp=(funfmt->function|Datax->BuiltInData.any.ppfmtx|NoData->Format.fprintffmt"_");embed=(fun~depthstate->function|Datax->state,x,[]|NoData->assertfalse);readback=(fun~depthstatet->letmoduleR=(val!r)inmatchR.deref_head~depthtwith|ED.Term.Discard->state,NoData,[]|_->state,Datat,[]);}moduleNotation=structlet(!:)x=(),Somexlet(+!)ab=a,Someblet(?:)x=(),xlet(+?)ab=a,bendletbeta~depthtargs=letmoduleR=(val!r)inletopenRinderef_apparg~from:depth~to_:depth?oc:NonetargsmoduleHOAdaptors=structtype'apred1=Data.term*'aConversion.ttype('a,'b)pred2=Data.term*'aConversion.t*'bConversion.ttype('a)pred2a=Data.term*'aConversion.ttype('a,'b,'c)pred3=Data.term*'aConversion.t*'bConversion.t*'cConversion.ttype('a,'b)pred3a=Data.term*'aConversion.t*'bConversion.tletpred1_tyx=Conversion.TyApp("->",x.Conversion.ty,[Conversion.TyName"(func)"])letpred1x={Conversion.ty=pred1_tyx;readback=(fun~depthstatee->state,(e,x),[]);embed=(fun~depthstate(x,_)->state,x,[]);pp=(funfmt(x,_)->Format.fprintffmt"<pred1>");pp_doc=(funfmt()->())}letpred2_tyxy=Conversion.(TyApp("->",x.Conversion.ty,[TyApp("->",y.Conversion.ty,[Conversion.TyName"prop"])]))letpred2xy={Conversion.ty=pred2_tyxy;readback=(fun~depthstatee->state,(e,x,y),[]);embed=(fun~depthstate(x,_,_)->state,x,[]);pp=(funfmt(x,_,_)->Format.fprintffmt"<pred2>");pp_doc=(funfmt()->())}letpred3_tyxyz=Conversion.(TyApp("->",x.Conversion.ty,[TyApp("->",y.Conversion.ty,[TyApp("->",z.Conversion.ty,[Conversion.TyName"prop"])])]))letpred3xyz={Conversion.ty=pred3_tyxyz;readback=(fun~depthstatee->state,(e,x,y,z),[]);embed=(fun~depthstate(x,_,_,_)->state,x,[]);pp=(funfmt(x,_,_,_)->Format.fprintffmt"<pred3>");pp_doc=(funfmt()->())}letpred2a_tyxa=Conversion.(TyApp("->",x.Conversion.ty,[TyApp("->",Conversion.TyNamea,[TyApp("->",Conversion.TyNamea,[Conversion.TyName"prop"])])]))letpred2axa={Conversion.ty=pred2a_tyxa;readback=(fun~depthstatee->state,(e,x),[]);embed=(fun~depthstate(x,_)->state,x,[]);pp=(funfmt(x,_)->Format.fprintffmt"<pred2a>");pp_doc=(funfmt()->())}letpred3a_tyxya=Conversion.(TyApp("->",x.Conversion.ty,[TyApp("->",y.Conversion.ty,[TyApp("->",Conversion.TyNamea,[TyApp("->",Conversion.TyNamea,[Conversion.TyName"prop"])])])]))letpred3axya={Conversion.ty=pred3a_tyxya;readback=(fun~depthstatee->state,(e,x,y),[]);embed=(fun~depthstate(x,_,_)->state,x,[]);pp=(funfmt(x,_,_)->Format.fprintffmt"<pred3a>");pp_doc=(funfmt()->())}letfilter1~once~depth~filter(f,c1)mstate=letgls=ref[]inletst=refstateinletm=filter(funx->tryletstate,x,gls0=c1.Conversion.embed~depth!stxinifgls0<>[]thengls:=gls0::!gls;letstate=once~depth(beta~depthf[x])stateinst:=state;truewithNo_clause->false)min!st,m,List.concat@@List.rev!glsletfilter2~once~depth~filter(f,c1,c2)mstate=letgls=ref[]inletst=refstateinletm=filter(funxy->tryletstate,x,gls0=c1.Conversion.embed~depth!stxinletstate,y,gls1=c2.Conversion.embed~depthstateyinifgls0<>[]||gls1<>[]thengls:=gls1::gls0::!gls;letstate=once~depth(beta~depthf[x;y])stateinst:=state;truewithNo_clause->false)min!st,m,List.concat@@List.rev!glsletmap1~once~depth~map(f,c1,c2)mstate=letgls=ref[]inletst=refstateinletm=map(funx->letstate,x,gls0=c1.Conversion.embed~depth!stxinletstate,y=FlexibleData.Elpi.makestateinlety=RawData.mkUnifVary~args:(List.initdepthRawData.mkConst)stateinletstate=once~depth(beta~depthf[x;y])stateinletstate,y,gls1=c2.Conversion.readback~depthstateyinifgls0<>[]||gls1<>[]thengls:=gls1::gls0::!gls;st:=state;y)min!st,m,List.concat@@List.rev!glsletmap2~once~depth~map(f,c1,c2,c3)mstate=letgls=ref[]inletst=refstateinletm=map(funxy->letstate,x,gls0=c1.Conversion.embed~depth!stxinletstate,y,gls1=c2.Conversion.embed~depthstateyinletstate,z=FlexibleData.Elpi.makestateinletz=RawData.mkUnifVarz~args:(List.initdepthRawData.mkConst)stateinletstate=once~depth(beta~depthf[x;y;z])stateinletstate,z,gls2=c3.Conversion.readback~depthstatezinifgls0<>[]||gls1<>[]||gls2<>[]thengls:=gls2::gls1::gls0::!gls;st:=state;z)min!st,m,List.concat@@List.rev!glsletfold1~once~depth~fold(f,c1)mastate=letgls=ref[]inletst=refstateinleta=fold(funxa->letstate,x,gls0=c1.Conversion.embed~depth!stxinletstate,y=FlexibleData.Elpi.makestateinlety=RawData.mkUnifVary~args:(List.initdepthRawData.mkConst)stateinifgls0<>[]thengls:=gls0::!gls;letstate=once~depth(beta~depthf[x;a;y])stateinst:=state;y)main!st,a,List.concat@@List.rev!glsletfold2~once~depth~fold(f,c1,c2)mastate=letgls=ref[]inletst=refstateinleta=fold(funxya->letstate,x,gls0=c1.Conversion.embed~depth!stxinletstate,y,gls1=c2.Conversion.embed~depthstateyinletstate,z=FlexibleData.Elpi.makestateinletz=RawData.mkUnifVarz~args:(List.initdepthRawData.mkConst)stateinletstate=once~depth(beta~depthf[x;y;a;z])stateinifgls0<>[]||gls1<>[]thengls:=gls1::gls0::!gls;st:=state;z)main!st,a,List.concat@@List.rev!glsendendmoduleBuiltIn=structincludeED.BuiltInPredicateletdeclare~file_namel=file_name,lletdocument_fmtfmt?(calc=Setup.default_calc_descriptor)(_,l)=ED.BuiltInPredicate.documentfmtl(List.rev!calc)letdocument_file?header:_?(calc=Setup.default_calc_descriptor)(name,l)=letoc=open_outnameinletfmt=Format.formatter_of_out_channelocinED.BuiltInPredicate.documentfmtl(List.rev!calc);Format.pp_print_flushfmt();close_outocendmoduleState=structincludeED.Stateletnew_state_descriptor=ED.State.new_descriptor(* From now on, we pretend there is no difference between terms at
compilation time and terms at execution time (in the API) *)letdeclare~name~pp~init~start=ED.State.declare~descriptor:Setup.default_state_descriptor~name~pp~init~clause_compilation_is_over:(funx->x)~goal_compilation_begins:(funx->startx)~compilation_is_over:(funx->Somex)~execution_is_over:(funx->Somex)()letdeclare_component?(descriptor=Setup.default_state_descriptor)~name~pp~init~start()=ED.State.declare~descriptor~name~pp~init~clause_compilation_is_over:(funx->x)~goal_compilation_begins:(funx->startx)~compilation_is_over:(funx->Somex)~execution_is_over:(funx->Somex)()endmoduleRawQuery=structletcompile_termpf=Compiler.query_of_scoped_termp(funs->lets,t=fsins,Compiler_data.ScopedTerm.of_simple_term_loct)letcompile_raw_termpf=Compiler.query_of_raw_termpfletterm_to_raw_termsp?ctx~deptht=letcheck=ED.State.getED.while_compilingsinCompiler.compile_term_to_raw_term~checksp?ctx~depth@@Compiler_data.ScopedTerm.of_simple_term_loctletcompile_ast=Compiler.query_of_ast(* let mk_Arg = Compiler.mk_Arg
let is_Arg = Compiler.is_Arg *)letglobal_name_to_constantstates=Compiler.global_name_to_constantstatesendmoduleQuotation=structtypequotation=Compiler_data.QuotationHooks.quotationincludeCompilerletdeclare_backtick?(descriptor=Setup.default_quotations_descriptor)~name(f:quotation)=Compiler_data.QuotationHooks.declare_backtick_compilation~descriptornamefletdeclare_singlequote?(descriptor=Setup.default_quotations_descriptor)~namef=Compiler_data.QuotationHooks.declare_singlequote_compilation~descriptornamefletset_default_quotation?(descriptor=Setup.default_quotations_descriptor)x=Compiler_data.QuotationHooks.set_default_quotation~descriptorxletregister_named_quotation?(descriptor=Setup.default_quotations_descriptor)~namex=Compiler_data.QuotationHooks.register_named_quotation~descriptor~namexletnew_quotations_descriptor=Compiler_data.QuotationHooks.new_descriptorendmoduleCalc=structletnew_calc_descriptor=ED.CalcHooks.new_descriptortypeoperation_declaration={symbol:string;infix:bool;args:stringlistlist;code:ED.termlist->ED.term;}letcompile_operation_declaration{symbol;infix;args;code}=letty_declargs=letc,variant=ED.Global_symbols.declare_overloaded_global_symbolsymbolinletty_decl=ifinfixthenPrintf.sprintf"external symbol (%s) : %s = \"%d\". "symbol(String.concat" -> "args)variantelsePrintf.sprintf"external symbol %s : %s = \"%d\"."symbol(String.concat" -> "args)variantinc,{ED.CalcHooks.ty_decl=ty_decl;code}inList.mapty_declargsletregister~descriptord=lete=compile_operation_declarationdindescriptor:=e@!descriptorletregister_evaln(symbol,tys)code=letinfix,n=n<0,absninletargs=tys|>List.map(funty->List.init(n+1)(fun_->ty))in[{symbol;infix;args;code}]letregister_eval_tysymboltycode=letinfix=falseinletargs=[ty]in[{symbol;infix;args;code}]letregister_evalsnlf=List.map(funi->register_evalnif)l|>List.flattenletdefault_calc=letopenUtilinletopenRawOpaqueDatainList.flatten[register_evals~-2["-",["A"];"i-",["int"];"r-",["float"]](function|[CDatax;CDatay]whenty2intxy->(morph2int(-)xy)|[CDatax;CDatay]whenty2floatxy->(morph2float(-.)xy)|_->type_error"Wrong arguments to -/i-/r-");register_evals~-2["+",["int";"float"];"i+",["int"];"r+",["float"]](function|[CDatax;CDatay]whenty2intxy->(morph2int(+)xy)|[CDatax;CDatay]whenty2floatxy->(morph2float(+.)xy)|_->type_error"Wrong arguments to +/i+/r+");register_eval~-2("*",["int";"float"])(function|[CDatax;CDatay]whenty2intxy->(morph2int(*)xy)|[CDatax;CDatay]whenty2floatxy->(morph2float(*.)xy)|_->type_error"Wrong arguments to *");register_eval~-2("/",["float"])(function|[CDatax;CDatay]whenty2floatxy->(morph2float(/.)xy)|_->type_error"Wrong arguments to /");register_eval~-2("mod",["int"])(function|[CDatax;CDatay]whenty2intxy->(morph2int(mod)xy)|_->type_error"Wrong arguments to mod");register_eval~-2("div",["int"])(function|[CDatax;CDatay]whenty2intxy->(morph2int(/)xy)|_->type_error"Wrong arguments to div");register_eval~-2("^",["string"])(function|[CDatax;CDatay]whenty2stringxy->of_string(to_stringx^to_stringy)|_->type_error"Wrong arguments to ^");register_evals~-1["~",["int";"float"];"i~",["int"];"r~",["float"]](function|[CDatax]whenis_intx->(morph1int(~-)x)|[CDatax]whenis_floatx->(morph1float(~-.)x)|_->type_error"Wrong arguments to ~/i~/r~");register_evals1["abs",["int";"float"];"iabs",["int"];"rabs",["float"]](function|[CDatax]whenis_intx->(mapintintabsx)|[CDatax]whenis_floatx->(mapfloatfloatabs_floatx)|_->type_error"Wrong arguments to abs/iabs/rabs");register_evals2["max",["int";"float"]](function|[CDatax;CDatay]whenty2intxy->(morph2intmaxxy)|[CDatax;CDatay]whenty2floatxy->(morph2floatmaxxy)|_->type_error"Wrong arguments to abs/iabs/rabs");register_evals2["min",["int";"float"]](function|[CDatax;CDatay]whenty2intxy->(morph2intminxy)|[CDatax;CDatay]whenty2floatxy->(morph2floatminxy)|_->type_error"Wrong arguments to abs/iabs/rabs");register_eval1("sqrt",["float"])(function|[CDatax]whenis_floatx->(mapfloatfloatsqrtx)|_->type_error"Wrong arguments to sqrt");register_eval1("sin",["float"])(function|[CDatax]whenis_floatx->(mapfloatfloatsinx)|_->type_error"Wrong arguments to sin");register_eval1("cos",["float"])(function|[CDatax]whenis_floatx->(mapfloatfloatcosx)|_->type_error"Wrong arguments to cosin");register_eval1("arctan",["float"])(function|[CDatax]whenis_floatx->(mapfloatfloatatanx)|_->type_error"Wrong arguments to arctan");register_eval1("ln",["float"])(function|[CDatax]whenis_floatx->(mapfloatfloatlogx)|_->type_error"Wrong arguments to ln");register_eval_ty"int_to_real"["int";"float"](function|[CDatax]whenis_intx->(mapintfloatfloat_of_intx)|_->type_error"Wrong arguments to int_to_real");register_eval_ty"floor"["float";"int"](function|[CDatax]whenis_floatx->(mapfloatint(funx->int_of_float(floorx))x)|_->type_error"Wrong arguments to floor");register_eval_ty"ceil"["float";"int"](function|[CDatax]whenis_floatx->(mapfloatint(funx->int_of_float(ceilx))x)|_->type_error"Wrong arguments to ceil");register_eval_ty"truncate"["float";"int"](function|[CDatax]whenis_floatx->(mapfloatinttruncatex)|_->type_error"Wrong arguments to truncate");register_eval_ty"size"["string";"int"](function|[CDatax]whenis_stringx->of_int(String.length(to_stringx))|_->type_error"Wrong arguments to size");register_eval_ty"chr"["int";"string"](function|[CDatax]whenis_intx->of_string(String.make1(char_of_int(to_intx)))|_->type_error"Wrong arguments to chr");register_eval_ty"rhc"["string";"int"](function|[CDatax]whenis_stringx&&String.length(to_stringx)=1->of_int(int_of_char(to_stringx).[0])|_->type_error"Wrong arguments to rhc");register_eval_ty"string_to_int"["string";"int"](function|[CDatax]whenis_stringx->of_int(int_of_string(to_stringx))|_->type_error"Wrong arguments to string_to_int");register_eval_ty"int_to_string"["int";"string"](function|[CDatax]whenis_intx->of_string(string_of_int(to_intx))|_->type_error"Wrong arguments to int_to_string");register_eval_ty"substring"["string";"int";"int";"string"](function|[CDatax;CDatai;CDataj]whenis_stringx&&ty2intij->letx=to_stringxandi=to_intiandj=to_intjinifi>=0&&j>=0&&String.lengthx>=i+jthenof_string(String.subxij)elsetype_error"Wrong arguments to substring"|_->type_error"Wrong argument type to substring");register_eval_ty"real_to_string"["float";"string"](function|[CDatax]whenis_floatx->of_string(string_of_float(to_floatx))|_->type_error"Wrong arguments to real_to_string")]let()=List.iter(register~descriptor:Setup.default_calc_descriptor)default_calcleteval~depthstatex=lettable=ED.State.getED.CalcHooks.evalstateinletlookup_evalc=Util.Constants.Map.findctableinletmoduleR=(val!r)inletopenRinletrecevaldeptht=matchderef_head~depthtwith|Lam_->Util.type_error"Evaluation of a lambda abstraction"|Builtin_->Util.type_error"Evaluation of built-in predicate"|App(hd,arg,args)->letf=trylookup_evalhdwithNot_found->function|[]->assertfalse|x::xs->ED.mkApphdxxsinletargs=List.map(funx->evaldepthx)(arg::args)infargs|AppUVar_|UVar_|Discard->Util.error"Evaluation of a non closed term. Maybe delay this predicate call and declare a constraint."|Arg_|AppArg_->Util.anomaly"Evaluation of a stack term"|Consthdasx->letf=trylookup_evalhdwithNot_found->fun_->xinf[]|(Nil|Cons_asx)->Util.type_error("Lists cannot be evaluated: "^ED.show_termx)|CData_asx->xinevaldepthxletcalc=letopenBuiltIninletopenContextualConversioninletopenBuiltInPredicate.Notationin[LPDoc" -- Evaluation --";LPCode":functional pred (is) o:A, i:A.";LPCode"X is Y :- calc Y X.";MLCode(Pred("calc",In(BuiltInData.poly"A","Expr",Out(BuiltInData.poly"A","Out",Read(unit_ctx,"unifies Out with the value of Expr. It can be used in tandem with spilling, eg [f {calc (N + 1)}]"))),(funt_~depth__state->!:(eval~depthstatet))),DocAbove);]endmoduleUtils=structletlp_list_to_list~deptht=letmoduleR=(val!r)inletopenRinlp_list_to_list~depthtletlist_to_lp_listtl=letmoduleR=(val!r)inletopenRinlist_to_lp_listtlletget_assignment{ED.contents=t}=letmoduleR=(val!r)inift==ED.dummythenNoneelseSometletmove~from~to_t=letmoduleR=(val!r)inletopenRinhmove~from~to_?oc:Nonetletbeta=BuiltInPredicate.betaleterror=Util.errorlettype_error=Util.type_errorletanomaly=Util.anomalyletwarn=Util.warnletclause_of_term?name?graft~depthlocterm=letopenEAinletmoduleData=ED.TerminletmoduleR=(val!r)inletopenRinletshowi=Format.asprintf"%a"(R.Pp.pp_constant?pp_ctx:None)iinletbuggy_loc=locin(* Format.eprintf "clause: %a\n" ( Pp.uppterm depth [] ~argsdepth:0 ED.empty_env ) term; *)letrecauxdctxt=matchderef_head~depth:dtwith|Data.Constiwheni>=0&&i<depth->error"program_of_term: the term is not closed"|Data.Constiwheni<0->Term.mkConbuggy_loc(showi)|Data.Consti->Util.IntMap.findictx|Data.Lamt->lets="x"^string_of_intdinletctx=Util.IntMap.addd(Term.mkConbuggy_locs)ctxinTerm.mkLambuggy_locsbuggy_locNone(aux(d+1)ctxt)|Data.App(c,x,xs)->letc=auxdctx(R.mkConstc)inletx=auxdctxxinletxs=List.map(auxdctx)xsinTerm.mkApploc(c::x::xs)|(Data.Arg_|Data.AppArg_)->assertfalse|Data.Cons(hd,tl)->lethd=auxdctxhdinlettl=auxdctxtlinTerm.mkSeq[hd;tl]|Data.Nil->Term.mkNilbuggy_loc|Data.Builtin(c,xs)->letc=Term.mkConbuggy_loc(ED.show_builtin_predicate(fun?table->show)c)inletxs=List.map(auxdctx)xsinTerm.mkApploc(c::xs)|Data.CDatax->Term.mkCbuggy_locx|(Data.UVar_|Data.AppUVar_)->error"program_of_term: the term contains uvars"|Data.Discard->Term.mkConbuggy_loc"_"inletattributes=(matchnamewithSomex->[Namex]|None->[])@(matchgraftwith|Some(`After,x)->[Afterx]|Some(`Before,x)->[Beforex]|Some(`Replace,x)->[Replacex]|Some(`Remove,x)->[Removex]|None->[])in[Program.Clause{Clause.loc=loc;attributes;body=auxdepthUtil.IntMap.emptyterm;needs_spilling=()}]letterm_to_raw_termsp?ctx~deptht=Compiler.runtime_hack_term_to_raw_termsp?ctx~depth@@Compiler_data.ScopedTerm.of_simple_term_loctletmap_acc=BuiltInData.map_accmoduletypeShow=Util.ShowmoduletypeShowKey=Util.ShowKeymoduletypeShow1=Util.Show1moduleMap=Util.MapmoduleSet=Util.SetmoduleIntSet=Util.IntSetmoduleLocSet:Util.Set.Swithtypeelt=Ast.Loc.t=Util.Set.Make(Ast.Loc)letversion_parser=Util.version_parserleterror_cmp_flex~deptht1t2=error"cmp_term on non-ground terms"letreccmp_term~deptht1t2=letopenRawDatainmatchlook~deptht1,look~deptht2with|Nil,Nil->0|Nil,(Cons_|Const_|App_|Lam_|Builtin_|CData_|UnifVar_)->-1|Cons(x,xs),Cons(y,ys)->letcmp_x=cmp_term~depthxyinifcmp_x==0thencmp_term~depthxsyselsecmp_x|Cons_,(Const_|App_|Lam_|Builtin_|CData_|UnifVar_)->-1|Cons_,Nil->1|Constc1,Constc2->c1-c2|Const_,(App_|Lam_|Builtin_|CData_|UnifVar_)->-1|Const_,(Cons_|Nil)->1|Lamt1,Lamt2->cmp_term~depth:(depth+1)t1t2|Lam_,(App_|Builtin_|CData_|UnifVar_)->-1|Lam_,(Const_|Cons_|Nil)->1|App(c1,x,xs),App(c2,y,ys)->letcmp_c1=c1-c2inifcmp_c1==0thenletcmp_x=cmp_term~depthxyinifcmp_x==0thencmp_terms~depthxsyselsecmp_xelsecmp_c1|App_,(Builtin_|CData_|UnifVar_)->-1|App_,(Lam_|Const_|Cons_|Nil)->1|Builtin(c1,xs),Builtin(c2,ys)->letcmp_c1=cmp_builtinc1c2inifcmp_c1==0thencmp_terms~depthxsyselsecmp_c1|Builtin_,(CData_|UnifVar_)->-1|Builtin_,(App_|Lam_|Const_|Cons_|Nil)->1|CDatad1,CDatad2->RawOpaqueData.compared1d2|CData_,UnifVar_->-1|CData_,(Builtin_|App_|Lam_|Const_|Cons_|Nil)->1|UnifVar(b1,xs),UnifVar(b2,ys)->ifFlexibleData.Elpi.equalb1b2thenifcmp_terms~depthxsys==0then0elseerror_cmp_flex~deptht1t2elseerror_cmp_flex~deptht1t2|UnifVar_,(CData_|Builtin_|App_|Lam_|Const_|Cons_|Nil)->1andcmp_terms~depthl1l2=matchl1,l2with|[],[]->0|[],_::_->-1|_::_,[]->1|x::xs,y::ys->letcmp_x=cmp_term~depthxyinifcmp_x==0thencmp_terms~depthxsyselsecmp_xletreccheck_ground~deptht=letopenRawDatainmatchlook~depthtwith|Nil|Const_|CData_->()|Lamt->check_ground~depth:(depth+1)t|Cons(x,xs)->check_ground~depthx;check_ground~depthxs|Builtin(_,l)->List.iter(check_ground~depth)l|App(_,x,xs)->check_ground~depthx;List.iter(check_ground~depth)xs|UnifVar_->raiseBuiltInPredicate.No_clauseendmoduleRawPp=structlettermdepthfmtt=letmoduleR=(val!r)inletopenRinPp.upptermdepth[]~argsdepth:0ED.empty_envfmttletconstraintsfc=letmoduleR=(val!r)inletopenRinUtil.pplist~boxed:true(pp_stuck_goal?pp_ctx:None)""fcletlist=Util.pplistmoduleDebug=structlettermdepthfmtt=letmoduleR=(val!r)inletopenRinPp.pptermdepth[]~argsdepth:0ED.empty_envfmttletshow_term=ED.show_termendend