12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646(************************************************************************)(* * The Coq Proof Assistant / The Coq Development Team *)(* v * Copyright INRIA, CNRS and contributors *)(* <O___,, * (see version control and CREDITS file for authors & dates) *)(* \VV/ **************************************************************)(* // * This file is distributed under the terms of the *)(* * GNU Lesser General Public License Version 2.1 *)(* * (see LICENSE file for the text of the license) *)(************************************************************************)openPpopenCErrorsopenUtilopenNamesopenDeclarationsopenEntriesopenLibnamesopenLibobjectopenMod_subst(** {6 Inlining levels} *)(** Rigid / flexible module signature *)type'amodule_signature=|Enforceof'a(** ... : T *)|Checkof'alist(** ... <: T1 <: T2, possibly empty *)(** Which module inline annotations should we honor,
either None or the ones whose level is less or equal
to the given integer *)typeinline=|NoInline|DefaultInline|InlineAtofintletdefault_inline()=Some(Flags.get_inline_level())letinl2intopt=function|NoInline->None|InlineAti->Somei|DefaultInline->default_inline()(** These functions register the visibility of the module and iterates
through its components. They are called by plenty of module functions *)letconsistency_checksexistsdir=ifexiststhenlet_=tryNametab.locate_module(qualid_of_dirpathdir)withNot_found->user_err(DirPath.printdir++str" should already exist!")in()elseifNametab.exists_moduledirthenuser_err(DirPath.printdir++str" already exists.")letrecget_module_path=function|MEidentmp->mp|MEwith(me,_)->get_module_pathme|MEapply(me,_)->get_module_pathmelettype_of_modmpenv=function|true->(Environ.lookup_modulempenv).mod_type|false->(Environ.lookup_modtypempenv).mod_type(** {6 Name management}
Auxiliary functions to transform full_path and kernel_name given
by Lib into ModPath.t and DirPath.t needed for modules
*)letmp_of_knkn=letmp,l=KerName.reprkninMPdot(mp,l)letdir_of_spsp=letdir,id=repr_pathspinadd_dirpath_suffixdirid(** The [ModActions] abstraction represent operations on modules
that are specific to a given stage. Two instances are defined below,
for Synterp and Interp. *)moduletypeModActions=sigtypetypexprtypeenvvalstage:Summary.Stage.tvalsubstobjs_table_name:stringvalmodobjs_table_name:stringvalenter_module:ModPath.t->DirPath.t->int->unitvalenter_modtype:ModPath.t->full_path->int->unitvalopen_module:open_filter->ModPath.t->DirPath.t->int->unitmoduleLib:Lib.StagedLibS(** Create the substitution corresponding to some functor applications *)valcompute_subst:is_mod:bool->env->MBId.tlist->ModPath.t->ModPath.tlist->Entries.inline->MBId.tlist*substitutionendmoduleSynterpActions:ModActionswithtypeenv=unitwithtypetypexpr=Constrexpr.universe_decl_exproption*Constrexpr.constr_expr=structtypetypexpr=Constrexpr.universe_decl_exproption*Constrexpr.constr_exprtypeenv=unitletstage=Summary.Stage.Synterpletsubstobjs_table_name="MODULE-SYNTAX-SUBSTOBJS"letmodobjs_table_name="MODULE-SYNTAX-OBJS"letenter_moduleobj_mpobj_diri=consistency_checksfalseobj_dir;Nametab.push_module(Untili)obj_dirobj_mpletenter_modtypempspi=ifNametab.exists_modtypespthenanomaly(pr_pathsp++str" already exists.");Nametab.push_modtype(Nametab.Untili)spmpletopen_modulefobj_mpobj_diri=consistency_checkstrueobj_dir;ifin_filter~cat:NonefthenNametab.push_module(Nametab.Exactlyi)obj_dirobj_mpmoduleLib=Lib.Synterpletreccompute_subst()mbidsmp_linl=matchmbids,mp_lwith|_,[]->mbids,empty_subst|[],r->user_errPp.(str"Application of a functor with too few arguments.")|mbid::mbids,mp::mp_l->letmbid_left,subst=compute_subst()mbidsmp_linlinmbid_left,join(map_mbidmbidmpempty_delta_resolver)substletcompute_subst~is_mod()mbidsmp1mp_linl=compute_subst()mbidsmp_linlendmoduleInterpActions:ModActionswithtypeenv=Environ.envwithtypetypexpr=Constr.t*UVars.AbstractContext.toption=structtypetypexpr=Constr.t*UVars.AbstractContext.toptiontypeenv=Environ.envletstage=Summary.Stage.Interpletsubstobjs_table_name="MODULE-SUBSTOBJS"letmodobjs_table_name="MODULE-OBJS"(** {6 Current module type information}
This information is stored by each [start_modtype] for use
in a later [end_modtype]. *)letenter_moduleobj_mpobj_diri=()letenter_modtypempspi=()letopen_modulefobj_mpobj_diri=()moduleLib=Lib.Interpletreccompute_substenvmbidssignmp_linl=matchmbids,mp_lwith|_,[]->mbids,empty_subst|[],r->user_errPp.(str"Application of a functor with too few arguments.")|mbid::mbids,mp::mp_l->letfarg_id,farg_b,fbody_b=Modops.destr_functorsigninletmb=Environ.lookup_modulempenvinletmbid_left,subst=compute_substenvmbidsfbody_bmp_linlinletresolver=ifModops.is_functormb.mod_typethenempty_delta_resolverelseModops.inline_delta_resolverenvinlmpfarg_idfarg_bmb.mod_deltainmbid_left,join(map_mbidmbidmpresolver)substletcompute_subst~is_modenvmbidsmp1mp_linl=lettyp=type_of_modmp1envis_modincompute_substenvmbidstypmp_linlendtypemodule_objects={module_prefix:Nametab.object_prefix;module_substituted_objects:Libobject.tlist;module_keep_objects:Libobject.tlist;}(** The [StagedModS] abstraction describes module operations at a given stage. *)moduletypeStagedModS=sigtypetypexprtypeenvvalget_module_sobjs:bool->env->Entries.inline->typexprmodule_alg_expr->substitutive_objectsvalload_module:int->DirPath.t->ModPath.t->substitutive_objects->Libobject.tlist->unitvalimport_modules:export:Lib.export_flag->(open_filter*ModPath.t)list->unitvaladd_leaf:Libobject.t->unitvaladd_leaves:Libobject.tlist->unitvalexpand_aobjs:Libobject.algebraic_objects->Libobject.tlistvalget_applications:typexprmodule_alg_expr->ModPath.t*ModPath.tlistvaldebug_print_modtab:unit->Pp.tmoduleModObjs:sigvalall:unit->module_objectsMPmap.tendend(** Some utilities about substitutive objects :
substitution, expansion *)letsobjs_no_functor(mbids,_)=List.is_emptymbidsletsubst_filteredsub(f,mpasx)=letmp'=subst_mpsubmpinifmp==mp'thenxelsef,mp'letrecsubst_aobjssub=function|Objsoasobjs->leto'=subst_objectssuboinifo==o'thenobjselseObjso'|Ref(mp,sub0)asr->letsub0'=joinsub0subinifsub0'==sub0thenrelseRef(mp,sub0')andsubst_sobjssub(mbids,aobjsassobjs)=letaobjs'=subst_aobjssubaobjsinifaobjs'==aobjsthensobjselse(mbids,aobjs')andsubst_objectssubstseg=letsubst_onenode=matchnodewith|AtomicObjectobj->letobj'=Libobject.subst_object(subst,obj)inifobj'==objthennodeelseAtomicObjectobj'|ModuleObject(id,sobjs)->letsobjs'=subst_sobjssubstsobjsinifsobjs'==sobjsthennodeelseModuleObject(id,sobjs')|ModuleTypeObject(id,sobjs)->letsobjs'=subst_sobjssubstsobjsinifsobjs'==sobjsthennodeelseModuleTypeObject(id,sobjs')|IncludeObjectaobjs->letaobjs'=subst_aobjssubstaobjsinifaobjs'==aobjsthennodeelseIncludeObjectaobjs'|ExportObject{mpl}->letmpl'=List.Smart.map(subst_filteredsubst)mplinifmpl'==mplthennodeelseExportObject{mpl=mpl'}|KeepObject_->assertfalseinList.Smart.mapsubst_oneseg(** The [StagedMod] abstraction factors out the code dealing with modules
that is common to all stages. *)moduleStagedMod(Actions:ModActions)=structtypetypexpr=Actions.typexprtypeenv=Actions.env(** ModSubstObjs : a cache of module substitutive objects
This table is common to modules and module types.
- For a Module M:=N, the objects of N will be reloaded
with M after substitution.
- For a Module M:SIG:=..., the module M gets its objects from SIG
Invariants:
- A alias (i.e. a module path inside a Ref constructor) should
never lead to another alias, but rather to a concrete Objs
constructor.
We will plug later a handler dealing with missing entries in the
cache. Such missing entries may come from inner parts of module
types, which aren't registered by the standard libobject machinery.
*)moduleModSubstObjs:sigvalset:ModPath.t->substitutive_objects->unitvalget:ModPath.t->substitutive_objectsvalset_missing_handler:(ModPath.t->substitutive_objects)->unitend=structlettable=Summary.ref~stage:Actions.stage(MPmap.empty:substitutive_objectsMPmap.t)~name:Actions.substobjs_table_nameletmissing_handler=ref(funmp->assertfalse)letset_missing_handlerf=(missing_handler:=f)letsetmpobjs=(table:=MPmap.addmpobjs!table)letgetmp=tryMPmap.findmp!tablewithNot_found->!missing_handlermpendletexpand_aobjs=function|Objso->o|Ref(mp,sub)->matchModSubstObjs.getmpwith|(_,Objso)->subst_objectssubo|_->assertfalse(* Invariant : any alias points to concrete objs *)letexpand_sobjs(_,aobjs)=expand_aobjsaobjs(** {6 ModObjs : a cache of module objects}
For each module, we also store a cache of
"prefix", "substituted objects", "keep objects".
This is used for instance to implement the "Import" command.
substituted objects :
roughly the objects above after the substitution - we need to
keep them to call open_object when the module is opened (imported)
keep objects :
The list of non-substitutive objects - as above, for each of
them we will call open_object when the module is opened
(Some) Invariants:
* If the module is a functor, it won't appear in this cache.
* Module objects in substitutive_objects part have empty substituted
objects.
* Modules which where created with Module M:=mexpr or with
Module M:SIG. ... End M. have the keep list empty.
*)moduleModObjs:sigvalset:ModPath.t->module_objects->unitvalget:ModPath.t->module_objects(* may raise Not_found *)valall:unit->module_objectsMPmap.tend=structlettable=Summary.ref~stage:Actions.stage(MPmap.empty:module_objectsMPmap.t)~name:Actions.modobjs_table_nameletsetmpobjs=(table:=MPmap.addmpobjs!table)letgetmp=MPmap.findmp!tableletall()=!tableend(** {6 Declaration of module substitutive objects} *)(** Nota: Interactive modules and module types cannot be recached!
This used to be checked here via a flag along the substobjs. *)(** {6 Declaration of module type substitutive objects} *)(** Nota: Interactive modules and module types cannot be recached!
This used to be checked more properly here. *)letload_modtypeispmpsobjs=Actions.enter_modtypempspi;ModSubstObjs.setmpsobjs(** {6 Declaration of substitutive objects for Include} *)letrecload_objecti(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.load_objecti(prefix,o)|ModuleObject(id,sobjs)->letsp,knasname=Lib.make_onameprefixidinload_modulei(dir_of_spsp)(mp_of_knkn)sobjs[]|ModuleTypeObject(id,sobjs)->letname=Lib.make_onameprefixidinlet(sp,kn)=nameinload_modtypeisp(mp_of_knkn)sobjs|IncludeObjectaobjs->load_includei(prefix,aobjs)|ExportObject_->()|KeepObject(id,objs)->letname=Lib.make_onameprefixidinload_keepi(name,objs)andload_objectsiprefixobjs=List.iter(funobj->load_objecti(prefix,obj))objsandload_includei(prefix,aobjs)=leto=expand_aobjsaobjsinload_objectsiprefixoandload_keepi((sp,kn),kobjs)=(* Invariant : seg isn't empty *)letobj_dir=dir_of_spspandobj_mp=mp_of_knkninletprefix=Nametab.{obj_dir;obj_mp;}inletmodobjs=tryModObjs.getobj_mpwithNot_found->assertfalse(* a substobjs should already be loaded *)inassertNametab.(eq_opmodobjs.module_prefixprefix);assert(List.is_emptymodobjs.module_keep_objects);ModObjs.setobj_mp{modobjswithmodule_keep_objects=kobjs};load_objectsiprefixkobjsandload_moduleiobj_dirobj_mpsobjskobjs=letprefix=Nametab.{obj_dir;obj_mp;}inActions.enter_moduleobj_mpobj_diri;ModSubstObjs.setobj_mpsobjs;(* If we're not a functor, let's iter on the internal components *)ifsobjs_no_functorsobjsthenbeginletobjs=expand_sobjssobjsinletmodule_objects={module_prefix=prefix;module_substituted_objects=objs;module_keep_objects=kobjs;}inModObjs.setobj_mpmodule_objects;load_objects(i+1)prefixobjs;load_objects(i+1)prefixkobjsend(** {6 Implementation of Import and Export commands} *)letmark_objectfobj(exports,acc)=(exports,(f,obj)::acc)letreccollect_module(f,mp)acc=try(* May raise Not_found for unknown module and for functors *)letmodobjs=ModObjs.getmpinletprefix=modobjs.module_prefixinletacc=collect_objectsf1prefixmodobjs.module_keep_objectsaccincollect_objectsf1prefixmodobjs.module_substituted_objectsaccwithNot_foundwhenActions.stage=Summary.Stage.Synterp->accandcollect_objectfiprefixobjacc=matchobjwith|ExportObject{mpl}->collect_exportsfimplacc|AtomicObject_|IncludeObject_|KeepObject_|ModuleObject_|ModuleTypeObject_->mark_objectf(prefix,obj)accandcollect_objectsfiprefixobjsacc=List.fold_left(funaccobj->collect_objectfiprefixobjacc)acc(List.revobjs)andcollect_exportf(f',mp)(exports,objsasacc)=matchfilter_andff'with|None->acc|Somef->letexports'=MPmap.updatemp(function|None->Somef|Somef0->letf'=filter_orff0iniffilter_eqf'f0thenSomef0elseSomef')exportsin(* If the map doesn't change there is nothing new to export. *)ifexports==exports'thenaccelsecollect_module(f,mp)(exports',objs)andcollect_exportsfimplacc=ifInt.equali1thenList.fold_left(funaccfmp->collect_exportffmpacc)acc(List.revmpl)elseaccletcollect_modulesmpl=List.fold_left(funaccfmp->collect_modulefmpacc)(MPmap.empty,[])(List.revmpl)letopen_modtypei((sp,kn),_)=letmp=mp_of_knkninletmp'=tryNametab.locate_modtype(qualid_of_pathsp)withNot_found->anomaly(pr_pathsp++str" should already exist!");inassert(ModPath.equalmpmp');Nametab.push_modtype(Nametab.Exactlyi)spmpletrecopen_objectfi(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.open_objectfi(prefix,o)|ModuleObject(id,sobjs)->letname=Lib.make_onameprefixidinletdir=dir_of_sp(fstname)inletmp=mp_of_kn(sndname)inopen_modulefidirmpsobjs|ModuleTypeObject(id,sobjs)->letname=Lib.make_onameprefixidinopen_modtypei(name,sobjs)|IncludeObjectaobjs->open_includefi(prefix,aobjs)|ExportObject{mpl}->open_exportfimpl|KeepObject(id,objs)->letname=Lib.make_onameprefixidinopen_keepfi(name,objs)andopen_modulefiobj_dirobj_mpsobjs=Actions.open_modulefobj_mpobj_diri;(* If we're not a functor, let's iter on the internal components *)ifsobjs_no_functorsobjsthenbeginletmodobjs=ModObjs.getobj_mpinopen_objectsf(i+1)modobjs.module_prefixmodobjs.module_substituted_objectsendandopen_objectsfiprefixobjs=List.iter(funobj->open_objectfi(prefix,obj))objsandopen_includefi(prefix,aobjs)=leto=expand_aobjsaobjsinopen_objectsfiprefixoandopen_exportfimpl=let_,objs=collect_exportsfimpl(MPmap.empty,[])inList.iter(fun(f,o)->open_objectf1o)objsandopen_keepfi((sp,kn),kobjs)=letobj_dir=dir_of_spspandobj_mp=mp_of_knkninletprefix=Nametab.{obj_dir;obj_mp;}inopen_objectsfiprefixkobjsletcache_include(prefix,aobjs)=leto=expand_aobjsaobjsinload_objects1prefixo;open_objectsunfiltered1prefixoletcache_object(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.cache_object(prefix,o)|ModuleObject_->load_object1(prefix,obj)|ModuleTypeObject_->load_object0(prefix,obj)|IncludeObjectaobjs->cache_include(prefix,aobjs)|ExportObject{mpl}->anomalyPp.(str"Export should not be cached")|KeepObject_->anomaly(Pp.str"This module should not be cached!")(* Adding operations with containers *)letadd_leaf_entry=matchActions.stagewith|Summary.Stage.Synterp->Lib.Synterp.add_leaf_entry|Summary.Stage.Interp->Lib.Interp.add_leaf_entryletadd_leafobj=cache_object(Lib.prefix(),obj);add_leaf_entryobjletadd_leavesobjs=letadd_objobj=add_leaf_entryobj;load_object1(Lib.prefix(),obj)inList.iteradd_objobjsletimport_modules~exportmpl=let_,objs=collect_modulesmplinList.iter(fun(f,o)->open_objectf1o)objs;matchexportwith|Lib.Import->()|Lib.Export->letentry=ExportObject{mpl}inadd_leaf_entryentry(** {6 Handler for missing entries in ModSubstObjs} *)(** Since the inner of Module Types are not added by default to
the ModSubstObjs table, we compensate this by explicit traversal
of Module Types inner objects when needed. Quite a hack... *)letmp_idmpid=MPdot(mp,Label.of_idid)letrecregister_mod_objsmpobj=matchobjwith|ModuleObject(id,sobjs)->ModSubstObjs.set(mp_idmpid)sobjs|ModuleTypeObject(id,sobjs)->ModSubstObjs.set(mp_idmpid)sobjs|IncludeObjectaobjs->List.iter(register_mod_objsmp)(expand_aobjsaobjs)|_->()lethandle_missing_substobjsmp=matchmpwith|MPdot(mp',l)->letobjs=expand_sobjs(ModSubstObjs.getmp')inList.iter(register_mod_objsmp')objs;ModSubstObjs.getmp|_->assertfalse(* Only inner parts of module types should be missing *)let()=ModSubstObjs.set_missing_handlerhandle_missing_substobjs(** {6 From module expression to substitutive objects} *)(** Turn a chain of [MSEapply] into the head ModPath.t and the
list of ModPath.t parameters (deepest param coming first).
The left part of a [MSEapply] must be either [MSEident] or
another [MSEapply]. *)letget_applicationsmexpr=letrecgetparams=function|MEidentmp->mp,params|MEapply(fexpr,mp)->get(mp::params)fexpr|MEwith_->user_errPp.(str"Non-atomic functor application.")inget[]mexpr(** Create the objects of a "with Module" structure. *)letrecreplace_module_objectidlmp0objs0mp1objs1=matchidl,objs0with|_,[]->[]|id::idl,(ModuleObject(id',sobjs))::tailwhenId.equalidid'->beginletmp_id=MPdot(mp0,Label.of_idid)inletobjs=matchidlwith|[]->subst_objects(map_mpmp1mp_idempty_delta_resolver)objs1|_->letobjs_id=expand_sobjssobjsinreplace_module_objectidlmp_idobjs_idmp1objs1in(ModuleObject(id,([],Objsobjs)))::tailend|idl,lobj::tail->lobj::replace_module_objectidlmp0tailmp1objs1(** Substitutive objects of a module expression (or module type) *)letrecget_module_sobjsis_modenvinl=function|MEidentmp->beginmatchModSubstObjs.getmpwith|(mbids,Objs_)whennot(ModPath.is_boundmp)->(mbids,Ref(mp,empty_subst))(* we create an alias *)|sobjs->sobjsend|MEwith(mty,WithDef_)->get_module_sobjsis_modenvinlmty|MEwith(mty,WithMod(idl,mp1))->assert(notis_mod);letsobjs0=get_module_sobjsis_modenvinlmtyinifnot(sobjs_no_functorsobjs0)thenuser_errPp.(str"Illegal use of a functor.");(* For now, we expand everything, to be safe *)letmp0=get_module_pathmtyinletobjs0=expand_sobjssobjs0inletobjs1=expand_sobjs(ModSubstObjs.getmp1)in([],Objs(replace_module_objectidlmp0objs0mp1objs1))|MEapply_asme->letmp1,mp_l=get_applicationsmeinletmbids,aobjs=get_module_sobjsis_modenvinl(MEidentmp1)inletmbids_left,subst=Actions.compute_subst~is_modenvmbidsmp1mp_linlin(mbids_left,subst_aobjssubstaobjs)letdebug_print_modtab()=letpr_seg=function|[]->str"[]"|l->str"[."++int(List.lengthl)++str".]"inletpr_modinfompmodobjss=letobjs=modobjs.module_substituted_objects@modobjs.module_keep_objectsins++str(ModPath.to_stringmp)++spc()++pr_segobjsinletmodules=MPmap.foldpr_modinfo(ModObjs.all())(mt())inhov0modulesendmoduleSynterpVisitor:StagedModSwithtypeenv=SynterpActions.envwithtypetypexpr=Constrexpr.universe_decl_exproption*Constrexpr.constr_expr=StagedMod(SynterpActions)moduleInterpVisitor:StagedModSwithtypeenv=InterpActions.envwithtypetypexpr=Constr.t*UVars.AbstractContext.toption=StagedMod(InterpActions)(** {6 Modules : start, end, declare} *)typecurrent_module_syntax_info={cur_mp:ModPath.t;cur_typ:((Constrexpr.universe_decl_exproption*Constrexpr.constr_expr)module_alg_expr*intoption)option;cur_mbids:MBId.tlist;}letdefault_module_syntax_infomp={cur_mp=mp;cur_typ=None;cur_mbids=[]}letopenmod_syntax_info=Summary.refNone~stage:Summary.Stage.Synterp~name:"MODULE-SYNTAX-INFO"(** {6 Current module information}
This information is stored by each [start_module] for use
in a later [end_module]. *)typecurrent_module_info={cur_typ:(module_struct_entry*intoption)option;(** type via ":" *)cur_typs:module_type_bodylist(** types via "<:" *)}letdefault_module_info={cur_typ=None;cur_typs=[]}letopenmod_info=Summary.refdefault_module_info~name:"MODULE-INFO"letstart_librarydir=letmp=Global.start_librarydirinopenmod_info:=default_module_info;openmod_syntax_info:=Some(default_module_syntax_infomp);Lib.start_compilationdirmpletset_openmod_syntax_infoinfo=match!openmod_syntax_infowith|None->anomalyPp.(str"bad init of openmod_syntax_info")|Some_->openmod_syntax_info:=Someinfoletopenmod_syntax_info()=match!openmod_syntax_infowith|None->anomalyPp.(str"missing init of openmod_syntax_info")|Somev->vletvm_state=(* VM bytecode is not needed here *)letvm_handler___()=(),Nonein((),{Mod_typing.vm_handler})moduleRawModOps=structmoduleSynterp=structletbuild_subtypesmtys=List.map(fun(m,ann)->letinl=inl2intoptanninletmte,base,kind=Modintern.intern_module_astModintern.ModTypemin(mte,base,kind,inl))mtysletintern_arg(idl,(typ,ann))=letinl=inl2intoptanninletlib_dir=Lib.library_dp()inlet(mty,base,kind)=Modintern.intern_module_astModintern.ModTypetypinletsobjs=SynterpVisitor.get_module_sobjsfalse()inlmtyinletmp0=get_module_pathmtyinletmap{CAst.v=id}=letdir=DirPath.make[id]inletmbid=MBId.makelib_diridinletmp=MPboundmbidin(* We can use an empty delta resolver because we load only syntax objects *)letsobjs=subst_sobjs(map_mpmp0mpempty_delta_resolver)sobjsinSynterpVisitor.load_module1dirmpsobjs[];mbidinList.mapmapidl,(mty,base,kind,inl)letintern_argsparams=List.mapintern_argparamsletstart_module_coreidargsres=(* Loads the parsing objects in arguments *)letargs=intern_argsargsinletmbids=List.flatten@@List.map(fun(mbidl,_)->mbidl)argsinletres_entry_o,sign=matchreswith|Enforce(res,ann)->letinl=inl2intoptanninlet(mte,base,kind)=Modintern.intern_module_astModintern.ModTyperesinSome(mte,inl),Enforce(mte,base,kind,inl)|Checkresl->None,Check(build_subtypesresl)inletmp=ModPath.MPdot((openmod_syntax_info()).cur_mp,Label.of_idid)inmp,res_entry_o,mbids,sign,argsletstart_moduleexportidargsres=let()=ifOption.has_someexport&¬(CList.is_emptyargs)thenuser_errPp.(str"Cannot import functors.")inletfs=Summary.Synterp.freeze_summaries()inletmp,res_entry_o,mbids,sign,args=start_module_coreidargsresinset_openmod_syntax_info{cur_mp=mp;cur_typ=res_entry_o;cur_mbids=mbids};letprefix=Lib.Synterp.start_moduleexportidmpfsinNametab.(push_dir(Until1)(prefix.obj_dir)(GlobDirRef.DirOpenModuleprefix.obj_mp));mp,args,signletend_module_coreid(m_info:current_module_syntax_info)objectsfs=let{Lib.Synterp.substobjs=substitute;keepobjs=keep;anticipateobjs=special;}=objectsin(* For sealed modules, we use the substitutive objects of their signatures *)letsobjs0,keep,special=matchm_info.cur_typwith|None->([],Objssubstitute),keep,special|Some(mty,inline)->SynterpVisitor.get_module_sobjsfalse()inlinemty,[],specialinSummary.Synterp.unfreeze_summariesfs;letsobjs=let(ms,objs)=sobjs0in(m_info.cur_mbids@ms,objs)in(* We substitute objects if the module is sealed by a signature *)letsobjs=matchm_info.cur_typwith|None->sobjs|Some(mty,_)->subst_sobjs(map_mp(get_module_pathmty)m_info.cur_mpempty_delta_resolver)sobjsinletnode=ModuleObject(id,sobjs)in(* We add the keep objects, if any, and if this isn't a functor *)letobjects=matchkeep,m_info.cur_mbidswith|[],_|_,_::_->special@[node]|_->special@[node;KeepObject(id,keep)]in(* Name consistency check : start_ vs. end_module *)(*
Printf.eprintf "newoname=%s, oldoname=%s\n" (string_of_path (fst newoname)) (string_of_path (fst oldoname));
assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp);
assert (ModPath.equal oldprefix.Nametab.obj_mp mp);
*)(* Printf.eprintf "newoname=%s, oldoname=%s\n" (string_of_path (fst newoname)) (string_of_path (fst oldoname)); *)(* Printf.eprintf "newoname=%s, cur_mp=%s\n" (ModPath.debug_to_string (mp_of_kn (snd newoname))) (ModPath.debug_to_string m_info.cur_mp); *)m_info.cur_mp,objectsletend_module()=letoldprefix,fs,objects=Lib.Synterp.end_module()inletm_info=openmod_syntax_info()inletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinletmp,objects=end_module_coreidm_infoobjectsfsinlet()=SynterpVisitor.add_leavesobjectsin(* Name consistency check : kernel vs. library *)(* CDebug.debug_synterp (fun () -> Pp.(str"prefix=" ++ DirPath.print ((Lib.prefix()).Nametab.obj_dir) ++ str", olddp=" ++ DirPath.print olddp)); *)assert(DirPath.equal(Lib.prefix()).Nametab.obj_dirolddp);mpletget_functor_sobjsis_modinl(mbids,mexpr)=let(mbids0,aobjs)=SynterpVisitor.get_module_sobjsis_mod()inlmexprin(mbids@mbids0,aobjs)letdeclare_moduleidargsresmexpr_o=letfs=Summary.Synterp.freeze_summaries()in(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp=ModPath.MPdot((openmod_syntax_info()).cur_mp,Label.of_idid)inletargs=intern_argsargsinletmbids=List.flatten@@List.mapfstargsinletmty_entry_o=matchreswith|Enforce(mty,ann)->letinl=inl2intoptanninlet(mte,base,kind)=Modintern.intern_module_astModintern.ModTypemtyinEnforce(mte,base,kind,inl)|Checkmtys->Check(build_subtypesmtys)inletmexpr_entry_o=matchmexpr_owith|None->None|Some(mexpr,ann)->let(mte,base,kind)=Modintern.intern_module_astModintern.ModulemexprinSome(mte,base,kind,inl2intoptann)inletsobjs,mp0=matchmexpr_entry_o,mty_entry_owith|None,Check_->assertfalse(* No body, no type ... *)|_,Enforce(typ,_,_,inl_res)->get_functor_sobjsfalseinl_res(mbids,typ),get_module_pathtyp|Some(body,_,_,inl_expr),Check_->get_functor_sobjstrueinl_expr(mbids,body),get_module_pathbodyin(* Undo the simulated interactive building of the module
and declare the module as a whole *)Summary.Synterp.unfreeze_summariesfs;(* We can use an empty delta resolver on syntax objects *)letsobjs=subst_sobjs(map_mpmp0mpempty_delta_resolver)sobjsinignore(SynterpVisitor.add_leaf(ModuleObject(id,sobjs)));mp,args,mexpr_entry_o,mty_entry_oendmoduleInterp=struct(** {6 Auxiliary functions concerning subtyping checks} *)letcheck_submtbsub_mtb_l=letfoldsub_mtb(cst,env)=letstate=((Environ.universesenv,cst),Reductionops.inferred_universes)inletgraph,cst=Subtyping.check_subtypesstateenvmtbsub_mtbin(cst,Environ.set_universesgraphenv)inletcst,_=List.fold_rightfoldsub_mtb_l(Univ.Constraints.empty,Global.env())inGlobal.add_constraintscst(** This function checks if the type calculated for the module [mp] is
a "<:"-like subtype of all signatures in [sub_mtb_l]. Uses only
the global environment. *)letcheck_subtypesmpsub_mtb_l=letmb=tryGlobal.lookup_modulempwithNot_found->assertfalseinletmtb=Modops.module_type_of_modulembincheck_submtbsub_mtb_l(** Same for module type [mp] *)letcheck_subtypes_mtmpsub_mtb_l=letmtb=tryGlobal.lookup_modtypempwithNot_found->assertfalseincheck_submtbsub_mtb_lletcurrent_modresolver()=fst@@Safe_typing.delta_of_senv@@Global.safe_env()letcurrent_struct()=letstruc=Safe_typing.structure_body_of_safe_env@@Global.safe_env()inNoFunctor(List.revstruc)(** Prepare the module type list for check of subtypes *)letbuild_subtypesenvmpargsmtys=let(ctx,ans)=List.fold_left_map(functx(mte,base,kind,inl)->letmte,ctx'=Modintern.interp_module_astenvModintern.ModTypebasemteinletenv=Environ.push_context_set~strict:truectx'envinletctx=Univ.ContextSet.unionctxctx'inletstate=((Environ.universesenv,Univ.Constraints.empty),Reductionops.inferred_universes)inletmtb,(_,cst),_=Mod_typing.translate_modtypestatevm_stateenvmpinl(args,mte)inletctx=Univ.ContextSet.add_constraintscstctxinctx,mtb)Univ.ContextSet.emptymtysin(ans,ctx)(** Process a declaration of functor parameter(s) (Id1 .. Idn : Typ)
i.e. possibly multiple names with the same module type.
Global environment is updated on the fly.
Objects in these parameters are also loaded.
Output is accumulated on top of [acc] (in reverse order). *)letintern_arg(acc,cst)(mbidl,(mty,base,kind,inl))=letenv=Global.env()inlet(mty,cst')=Modintern.interp_module_astenvkindbasemtyinlet()=Global.push_context_set~strict:truecst'inlet()=letstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,(_,cst),_=Mod_typing.translate_modtypestatevm_state(Global.env())baseinl([],mty)inGlobal.add_constraintscstinletenv=Global.env()inletsobjs=InterpVisitor.get_module_sobjsfalseenvinlmtyinletmp0=get_module_pathmtyinletfoldaccmbid=letid=MBId.to_idmbidinletdir=DirPath.make[id]inletmp=MPboundmbidinletresolver=Global.add_module_parametermbidmtyinlinletsobjs=subst_sobjs(map_mpmp0mpresolver)sobjsinInterpVisitor.load_module1dirmpsobjs[];(mbid,mty,inl)::accinletacc=List.fold_leftfoldaccmbidlin(acc,Univ.ContextSet.unioncstcst')(** Process a list of declarations of functor parameters
(Id11 .. Id1n : Typ1)..(Idk1 .. Idkm : Typk)
Global environment is updated on the fly.
The calls to [interp_modast] should be interleaved with these
env updates, otherwise some "with Definition" could be rejected.
Returns a list of mbids and entries (in reversed order).
This used to be a [List.concat (List.map ...)], but this should
be more efficient and independent of [List.map] eval order.
*)letintern_argsparams=letargs,ctx=List.fold_leftintern_arg([],Univ.ContextSet.empty)paramsinList.revargs,ctxletstart_module_coreidargsres=letmp=Global.start_moduleidinletparams,ctx=intern_argsargsinlet()=Global.push_context_set~strict:truectxinletenv=Global.env()inletres_entry_o,subtyps,ctx'=matchreswith|Enforce(mte,base,kind,inl)->let(mte,ctx)=Modintern.interp_module_astenvkindbasemteinletenv=Environ.push_context_set~strict:truectxenvin(* We check immediately that mte is well-formed *)letstate=((Environ.universesenv,Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,(_,cst),_=Mod_typing.translate_modtypestatevm_stateenvmpinl([],mte)inletctx=Univ.ContextSet.add_constraintscstctxinSome(mte,inl),[],ctx|Checkresl->lettyps,ctx=build_subtypesenvmpparamsreslinNone,typs,ctxinlet()=Global.push_context_set~strict:truectx'inmp,res_entry_o,subtyps,params,Univ.ContextSet.unionctxctx'letstart_moduleexportidargsres=letfs=Summary.Interp.freeze_summaries()inletmp,res_entry_o,subtyps,_,_=start_module_coreidargsresinopenmod_info:={cur_typ=res_entry_o;cur_typs=subtyps};let_:Nametab.object_prefix=Lib.Interp.start_moduleexportidmpfsinmpletend_module_coreidm_infoobjectsfs=let{Lib.Interp.substobjs=substitute;keepobjs=keep;anticipateobjs=special;}=objectsin(* For sealed modules, we use the substitutive objects of their signatures *)letsobjs0,keep=matchm_info.cur_typwith|None->([],Objssubstitute),keep|Some(mty,inline)->InterpVisitor.get_module_sobjsfalse(Global.env())inlinemty,[]inletstruc=current_struct()inletrestype'=Option.map(fun(ty,inl)->(([],ty),inl))m_info.cur_typinletstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,(_,cst),_=Mod_typing.finalize_modulestatevm_state(Global.env())(Global.current_modpath())(struc,current_modresolver())restype'inlet()=Global.add_constraintscstinletmp,mbids,resolver=Global.end_modulefsidm_info.cur_typinletsobjs=let(ms,objs)=sobjs0in(mbids@ms,objs)inlet()=check_subtypesmpm_info.cur_typsin(* We substitute objects if the module is sealed by a signature *)letsobjs=matchm_info.cur_typwith|None->sobjs|Some(mty,_)->subst_sobjs(map_mp(get_module_pathmty)mpresolver)sobjsinletnode=ModuleObject(id,sobjs)in(* We add the keep objects, if any, and if this isn't a functor *)letobjects=matchkeep,mbidswith|[],_|_,_::_->special@[node]|_->special@[node;KeepObject(id,keep)]inmp,objectsletend_module()=letoldprefix,fs,objects=Lib.Interp.end_module()inletm_info=!openmod_infoinletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinletmp,objects=end_module_coreidm_infoobjectsfsinlet()=InterpVisitor.add_leavesobjectsin(* Name consistency check : kernel vs. library *)assert(ModPath.equaloldprefix.Nametab.obj_mpmp);mpletget_functor_sobjsis_modenvinl(params,mexpr)=let(mbids,aobjs)=InterpVisitor.get_module_sobjsis_modenvinlmexprin(List.mappi1params@mbids,aobjs)(* TODO cleanup push universes directly to global env *)letdeclare_moduleidargsresmexpr_o=letfs=Summary.Interp.freeze_summaries()in(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp,mty_entry_o,subs,params,ctx=start_module_coreidargsresinletenv=Global.env()inletmexpr_entry_o,inl_expr,ctx'=matchmexpr_owith|None->None,default_inline(),Univ.ContextSet.empty|Some(mte,base,kind,inl)->let(mte,ctx)=Modintern.interp_module_astenvkindbasemteinSomemte,inl,ctxinletenv=Environ.push_context_set~strict:truectx'envinletctx=Univ.ContextSet.unionctxctx'inletentry,inl_res=matchmexpr_entry_o,mty_entry_owith|None,None->assertfalse(* No body, no type ... *)|None,Some(typ,inl)->MType(params,typ),inl|Somebody,otyp->MExpr(params,body,Option.mapfstotyp),Option.catasnd(default_inline())otypinletsobjs,mp0=matchentrywith|MType(_,mte)|MExpr(_,_,Somemte)->get_functor_sobjsfalseenvinl_res(params,mte),get_module_pathmte|MExpr(_,me,None)->get_functor_sobjstrueenvinl_expr(params,me),get_module_pathmein(* Undo the simulated interactive building of the module
and declare the module as a whole *)Summary.Interp.unfreeze_summariesfs;letinl=matchinl_exprwith|None->None|_->inl_resinlet()=Global.push_context_set~strict:truectxinletstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,(_,cst),_=Mod_typing.translate_modulestatevm_state(Global.env())mpinlentryinlet()=Global.add_constraintscstinletmp_env,resolver=Global.add_moduleidentryinlin(* Name consistency check : kernel vs. library *)assert(ModPath.equalmp(mp_of_kn(Lib.make_knid)));assert(ModPath.equalmpmp_env);let()=check_subtypesmpsubsinletsobjs=subst_sobjs(map_mpmp0mpresolver)sobjsinInterpVisitor.add_leaf(ModuleObject(id,sobjs));mpendend(** {6 Module types : start, end, declare} *)moduleRawModTypeOps=structmoduleSynterp=structletstart_modtype_coreidcur_mpargsmtys=letmp=ModPath.MPdot(cur_mp,Label.of_idid)inletargs=RawModOps.Synterp.intern_argsargsinletmbids=List.flatten@@List.map(fun(mbidl,_)->mbidl)argsinletsub_mty_l=RawModOps.Synterp.build_subtypesmtysinmp,mbids,args,sub_mty_lletstart_modtypeidargsmtys=letfs=Summary.Synterp.freeze_summaries()inletmp,mbids,args,sub_mty_l=start_modtype_coreid(openmod_syntax_info()).cur_mpargsmtysinset_openmod_syntax_info{cur_mp=mp;cur_typ=None;cur_mbids=mbids};letprefix=Lib.Synterp.start_modtypeidmpfsinNametab.(push_dir(Until1)(prefix.obj_dir)(GlobDirRef.DirOpenModtypeprefix.obj_mp));mp,args,sub_mty_lletend_modtype_coreidmbidsobjectsfs=let{Lib.Synterp.substobjs=substitute;keepobjs=_;anticipateobjs=special;}=objectsinSummary.Synterp.unfreeze_summariesfs;letmodtypeobjs=(mbids,Objssubstitute)in(special@[ModuleTypeObject(id,modtypeobjs)])letend_modtype()=letoldprefix,fs,objects=Lib.Synterp.end_modtype()inletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinletobjects=end_modtype_coreid(openmod_syntax_info()).cur_mbidsobjectsfsinSynterpVisitor.add_leavesobjects;(openmod_syntax_info()).cur_mpletdeclare_modtypeidargsmtys(mty,ann)=letfs=Summary.Synterp.freeze_summaries()inletinl=inl2intoptannin(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp,mbids,args,sub_mty_l=start_modtype_coreid(openmod_syntax_info()).cur_mpargsmtysinletmte,base,kind=Modintern.intern_module_astModintern.ModTypemtyinletentry=mbids,mteinletsobjs=RawModOps.Synterp.get_functor_sobjsfalseinlentryinletsubst=map_mp(get_module_path(sndentry))mpempty_delta_resolverinletsobjs=subst_sobjssubstsobjsin(* Undo the simulated interactive building of the module type
and declare the module type as a whole *)Summary.Synterp.unfreeze_summariesfs;ignore(SynterpVisitor.add_leaf(ModuleTypeObject(id,sobjs)));mp,args,(mte,base,kind,inl),sub_mty_lendmoduleInterp=structletopenmodtype_info=Summary.ref([]:module_type_bodylist)~name:"MODTYPE-INFO"letstart_modtype_coreidargsmtys=letmp=Global.start_modtypeidinletparams,params_ctx=RawModOps.Interp.intern_argsargsinlet()=Global.push_context_set~strict:trueparams_ctxinletenv=Global.env()inletsub_mty_l,sub_mty_ctx=RawModOps.Interp.build_subtypesenvmpparamsmtysinlet()=Global.push_context_set~strict:truesub_mty_ctxinmp,params,sub_mty_l,Univ.ContextSet.unionparams_ctxsub_mty_ctxletstart_modtypeidargsmtys=letfs=Summary.Interp.freeze_summaries()inletmp,_,sub_mty_l,_=start_modtype_coreidargsmtysinopenmodtype_info:=sub_mty_l;letprefix=Lib.Interp.start_modtypeidmpfsinNametab.(push_dir(Until1)(prefix.obj_dir)(GlobDirRef.DirOpenModtypemp));mpletend_modtype_coreidsub_mty_lobjectsfs=let{Lib.Interp.substobjs=substitute;keepobjs=_;anticipateobjs=special;}=objectsinletmp,mbids=Global.end_modtypefsidinlet()=RawModOps.Interp.check_subtypes_mtmpsub_mty_linletmodtypeobjs=(mbids,Objssubstitute)inletobjects=special@[ModuleTypeObject(id,modtypeobjs)]inmp,objectsletend_modtype()=letoldprefix,fs,objects=Lib.Interp.end_modtype()inletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinletsub_mty_l=!openmodtype_infoinletmp,objects=end_modtype_coreidsub_mty_lobjectsfsinlet()=InterpVisitor.add_leavesobjectsin(* Check name consistence : start_ vs. end_modtype, kernel vs. library *)assert(DirPath.equal(Lib.prefix()).Nametab.obj_dirolddp);assert(ModPath.equaloldprefix.Nametab.obj_mpmp);mpletdeclare_modtypeidargsmtys(mte,base,kind,inl)=letfs=Summary.Interp.freeze_summaries()in(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp,params,sub_mty_l,ctx=start_modtype_coreidargsmtysinletenv=Global.env()inletmte,mte_ctx=Modintern.interp_module_astenvkindbasemteinlet()=Global.push_context_set~strict:truemte_ctxinletenv=Global.env()in(* We check immediately that mte is well-formed *)letstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,(_,mte_cst),_=Mod_typing.translate_modtypestatevm_stateenvmpinl([],mte)inlet()=Global.push_context_set~strict:true(Univ.Level.Set.empty,mte_cst)inletentry=params,mteinletenv=Global.env()inletsobjs=RawModOps.Interp.get_functor_sobjsfalseenvinlentryinletsubst=map_mp(get_module_path(sndentry))mpempty_delta_resolverinletsobjs=subst_sobjssubstsobjsin(* Undo the simulated interactive building of the module type
and declare the module type as a whole *)Summary.Interp.unfreeze_summariesfs;(* We enrich the global environment *)let()=Global.push_context_set~strict:truectxinlet()=Global.push_context_set~strict:truemte_ctxinlet()=Global.push_context_set~strict:true(Univ.Level.Set.empty,mte_cst)inletmp_env=Global.add_modtypeidentryinlin(* Name consistency check : kernel vs. library *)assert(ModPath.equalmp_envmp);(* Subtyping checks *)let()=RawModOps.Interp.check_subtypes_mtmpsub_mty_linInterpVisitor.add_leaf(ModuleTypeObject(id,sobjs));mpendend(** {6 Include} *)moduleRawIncludeOps=structexceptionNoIncludeSelfmoduleSynterp=structletrecinclude_substmpmbids=matchmbidswith|[]->empty_subst|mbid::mbids->letsubst=include_substmpmbidsinjoin(map_mbidmbidmpempty_delta_resolver)substletdeclare_one_include_corecur_mp(me_ast,annot)=letme,base,kind=Modintern.intern_module_astModintern.ModAnyme_astinletis_mod=(kind==Modintern.Module)inletinl=inl2intoptannotinletmbids,aobjs=SynterpVisitor.get_module_sobjsis_mod()inlmeinletsubst_self=tryifList.is_emptymbidsthenraiseNoIncludeSelf;include_substcur_mpmbidswithNoIncludeSelf->empty_substinletbase_mp=get_module_pathmein(* We can use an empty delta resolver on syntax objects *)letsubst=joinsubst_self(map_mpbase_mpcur_mpempty_delta_resolver)inletaobjs=subst_aobjssubstaobjsin(me,base,kind,inl),aobjsletdeclare_one_include(me_ast,annot)=letres,aobjs=declare_one_include_core(openmod_syntax_info()).cur_mp(me_ast,annot)inSynterpVisitor.add_leaf(IncludeObjectaobjs);resletdeclare_includeme_asts=List.mapdeclare_one_includeme_astsendmoduleInterp=structletrecinclude_substenvmpresombidssigninline=matchmbidswith|[]->empty_subst|mbid::mbids->letfarg_id,farg_b,fbody_b=Modops.destr_functorsigninletsubst=include_substenvmpresombidsfbody_binlineinletmp_delta=Modops.inline_delta_resolverenvinlinempfarg_idfarg_bresoinjoin(map_mbidmbidmpmp_delta)substletrecdecompose_functormpltyp=matchmpl,typwith|[],_->typ|_::mpl,MoreFunctor(_,_,str)->decompose_functormplstr|_->user_errPp.(str"Application of a functor with too much arguments.")lettype_of_inclenvis_mod=function|MEidentmp->type_of_modmpenvis_mod|MEapply_asme->letmp0,mp_l=InterpVisitor.get_applicationsmeindecompose_functormp_l(type_of_modmp0envis_mod)|MEwith_->raiseNoIncludeSelf(** Implements [Include F] where [F] has parameters [mbids] to be
instantiated by fields of the current "self" module, i.e. using
subtyping, by the current module itself. *)letdeclare_one_include_core(me,base,kind,inl)=letenv=Global.env()inletme,cst=Modintern.interp_module_astenvkindbasemeinlet()=Global.push_context_set~strict:truecstinletenv=Global.env()inletis_mod=(kind==Modintern.Module)inletcur_mp=Global.current_modpath()inletmbids,aobjs=InterpVisitor.get_module_sobjsis_modenvinlmeinletsubst_self=tryifList.is_emptymbidsthenraiseNoIncludeSelf;lettyp=type_of_inclenvis_modmeinletreso=RawModOps.Interp.current_modresolver()ininclude_substenvcur_mpresombidstypinlwithNoIncludeSelf->empty_substinletbase_mp=get_module_pathmeinletstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inletsign,(),resolver,(_,cst),_=Mod_typing.translate_mse_includeis_modstatevm_state(Global.env())(Global.current_modpath())inlmeinlet()=Global.add_constraintscstinlet()=assert(ModPath.equalcur_mp(Global.current_modpath()))in(* Include Self support *)letmb={mod_mp=cur_mp;mod_expr=();mod_type=RawModOps.Interp.current_struct();mod_type_alg=None;mod_delta=RawModOps.Interp.current_modresolver();mod_retroknowledge=ModTypeRK}inletreccompute_signsign=matchsignwith|MoreFunctor(mbid,mtb,str)->letstate=((Global.universes(),Univ.Constraints.empty),Reductionops.inferred_universes)inlet(_,cst)=Subtyping.check_subtypesstate(Global.env())mbmtbinlet()=Global.add_constraintscstinletmpsup_delta=Modops.inline_delta_resolver(Global.env())inlcur_mpmbidmtbmb.mod_deltainletsubst=Mod_subst.map_mbidmbidcur_mpmpsup_deltaincompute_sign(Modops.subst_signaturesubststr)|NoFunctorstr->()inlet()=compute_signsigninletresolver=Global.add_includemeis_modinlinletsubst=joinsubst_self(map_mpbase_mpcur_mpresolver)insubst_aobjssubstaobjsletdeclare_one_include(me,base,kind,inl)=letaobjs=declare_one_include_core(me,base,kind,inl)inInterpVisitor.add_leaf(IncludeObjectaobjs)letdeclare_includeme_asts=List.iterdeclare_one_includeme_astsendend(** {6 Libraries} *)typelibrary_name=DirPath.t(** A library object is made of some substitutive objects
and some "keep" objects. *)typelibrary_objects=Libobject.tlist*Libobject.tlistmoduleSynterp=structletstart_moduleexportidargsres=RawModOps.Synterp.start_moduleexportidargsresletend_module=RawModOps.Synterp.end_module(** Declare a module in terms of a list of module bodies, by including them.
Typically used for `Module M := N <+ P`.
*)letdeclare_module_includesidargsresmexpr_l=letfs=Summary.Synterp.freeze_summaries()inletmp,res_entry_o,mbids,sign,args=RawModOps.Synterp.start_module_coreidargsresinletmod_info={cur_mp=mp;cur_typ=res_entry_o;cur_mbids=mbids}inletincludes=List.map_left(RawIncludeOps.Synterp.declare_one_include_coremp)mexpr_linletbodies,incl_objs=List.splitincludesinletincl_objs=List.map(funx->IncludeObjectx)incl_objsinletobjects=Lib.Synterp.{substobjs=incl_objs;keepobjs=[];anticipateobjs=[];}inletmp,objects=RawModOps.Synterp.end_module_coreidmod_infoobjectsfsinSynterpVisitor.add_leavesobjects;mp,args,bodies,sign(** Declare a module type in terms of a list of module bodies, by including them.
Typically used for `Module Type M := N <+ P`.
*)letdeclare_modtype_includesidargsresmexpr_l=letfs=Summary.Synterp.freeze_summaries()inletmp,mbids,args,subtyps=RawModTypeOps.Synterp.start_modtype_coreid(openmod_syntax_info()).cur_mpargsresinletincludes=List.map_left(RawIncludeOps.Synterp.declare_one_include_coremp)mexpr_linletbodies,incl_objs=List.splitincludesinletincl_objs=List.map(funx->IncludeObjectx)incl_objsinletobjects=Lib.Synterp.{substobjs=incl_objs;keepobjs=[];anticipateobjs=[];}inletobjects=RawModTypeOps.Synterp.end_modtype_coreidmbidsobjectsfsinSynterpVisitor.add_leavesobjects;mp,args,bodies,subtypsletdeclare_moduleidargsmtysme_l=matchme_lwith|[]->letmp,args,body,sign=RawModOps.Synterp.declare_moduleidargsmtysNoneinassert(Option.is_emptybody);mp,args,[],sign|[me]->letmp,args,body,sign=RawModOps.Synterp.declare_moduleidargsmtys(Someme)inmp,args,[Option.getbody],sign|me_l->declare_module_includesidargsmtysme_lletstart_modtypeidargsmtys=RawModTypeOps.Synterp.start_modtypeidargsmtysletend_modtype=RawModTypeOps.Synterp.end_modtypeletdeclare_modtypeidargsmtysmty_l=matchmty_lwith|[]->assertfalse|[mty]->letmp,args,body,sign=RawModTypeOps.Synterp.declare_modtypeidargsmtysmtyinmp,args,[body],sign|mty_l->declare_modtype_includesidargsmtysmty_lletdeclare_include=RawIncludeOps.Synterp.declare_includeletregister_librarydir(objs:library_objects)=letmp=MPfiledirinletsobjs,keepobjs=objsinSynterpVisitor.load_module1dirmp([],Objssobjs)keepobjsletimport_modules=SynterpVisitor.import_modulesletimport_modulef~exportmp=import_modules~export[f,mp]endmoduleInterp=structletstart_module=RawModOps.Interp.start_moduleletend_module=RawModOps.Interp.end_module(** Declare a module in terms of a list of module bodies, by including them.
Typically used for `Module M := N <+ P`.
*)letdeclare_module_includesidargsresmexpr_l=letfs=Summary.Interp.freeze_summaries()inletmp,res_entry_o,subtyps,_,_=RawModOps.Interp.start_module_coreidargsresinletmod_info={cur_typ=res_entry_o;cur_typs=subtyps}inletincl_objs=List.map_left(funx->IncludeObject(RawIncludeOps.Interp.declare_one_include_corex))mexpr_linletobjects=Lib.Interp.{substobjs=incl_objs;keepobjs=[];anticipateobjs=[];}inletmp,objects=RawModOps.Interp.end_module_coreidmod_infoobjectsfsinInterpVisitor.add_leavesobjects;mp(** Declare a module type in terms of a list of module bodies, by including them.
Typically used for `Module Type M := N <+ P`.
*)letdeclare_modtype_includesidargsresmexpr_l=letfs=Summary.Interp.freeze_summaries()inletmp,_,subtyps,_=RawModTypeOps.Interp.start_modtype_coreidargsresinletincl_objs=List.map_left(funx->IncludeObject(RawIncludeOps.Interp.declare_one_include_corex))mexpr_linletobjects=Lib.Interp.{substobjs=incl_objs;keepobjs=[];anticipateobjs=[];}inletmp,objects=RawModTypeOps.Interp.end_modtype_coreidsubtypsobjectsfsinInterpVisitor.add_leavesobjects;mpletdeclare_moduleidargsmtysme_l=matchme_lwith|[]->RawModOps.Interp.declare_moduleidargsmtysNone|[me]->RawModOps.Interp.declare_moduleidargsmtys(Someme)|me_l->declare_module_includesidargsmtysme_lletstart_modtype=RawModTypeOps.Interp.start_modtypeletend_modtype=RawModTypeOps.Interp.end_modtypeletdeclare_modtypeidargsmtysmty_l=matchmty_lwith|[]->assertfalse|[mty]->RawModTypeOps.Interp.declare_modtypeidargsmtysmty|mty_l->declare_modtype_includesidargsmtysmty_lletdeclare_includeme_asts=ifLib.sections_are_opened()thenuser_errPp.(str"Include is not allowed inside sections.");RawIncludeOps.Interp.declare_includeme_asts(** For the native compiler, we cache the library values *)letregister_librarydircenv(objs:library_objects)digestvmtab=letmp=MPfiledirinlet()=try(* Is this library already loaded ? *)ignore(Global.lookup_modulemp);withNot_found->begin(* If not, let's do it now ... *)letmp'=Global.importcenvvmtabdigestinifnot(ModPath.equalmpmp')thenanomaly(Pp.str"Unexpected disk module name.")endinletsobjs,keepobjs=objsinInterpVisitor.load_module1dirmp([],Objssobjs)keepobjsletimport_modules=InterpVisitor.import_modulesletimport_modulef~exportmp=import_modules~export[f,mp]endletend_library_hook=ref[]letappend_end_library_hookf=end_library_hook:=f::!end_library_hookletend_library_hook()=List.iter(funf->f())(List.rev!end_library_hook)letend_library~output_native_objectsdir=end_library_hook();letprefix,info,lib_stack,lib_stack_syntax=Lib.end_compilationdirinletmp,cenv,vmlib,ast=Global.export~output_native_objectsdirinassert(ModPath.equalmp(MPfiledir));let{Lib.Interp.substobjs=substitute;keepobjs=keep;anticipateobjs=_;}=lib_stackinlet{Lib.Synterp.substobjs=substitute_syntax;keepobjs=keep_syntax;anticipateobjs=_;}=lib_stack_syntaxincenv,(substitute,keep),(substitute_syntax,keep_syntax),vmlib,ast,info(** {6 Iterators} *)letiter_all_interp_segmentsf=letrecapply_objprefixobj=matchobjwith|IncludeObjectaobjs->letobjs=InterpVisitor.expand_aobjsaobjsinList.iter(apply_objprefix)objs|_->fprefixobjinletapply_mod_obj_modobjs=letprefix=modobjs.module_prefixinList.iter(apply_objprefix)modobjs.module_substituted_objects;List.iter(apply_objprefix)modobjs.module_keep_objectsinletapply_nodes(node,os)=List.iter(funo->apply_obj(Lib.node_prefixnode)o)osinMPmap.iterapply_mod_obj(InterpVisitor.ModObjs.all());List.iterapply_nodes(Lib.contents())(** {6 Some types used to shorten declaremods.mli} *)typemodule_params=(lidentlist*(Constrexpr.module_ast*inline))listtypemodule_expr=(Modintern.module_struct_expr*ModPath.t*Modintern.module_kind*Entries.inline)typemodule_params_expr=(MBId.tlist*module_expr)list(** {6 Debug} *)letdebug_print_modtab()=InterpVisitor.debug_print_modtab()(** For printing modules, [process_module_binding] adds names of
bound module (and its components) to Nametab. It also loads
objects associated to it. *)letprocess_module_bindingmbidme=letdir=DirPath.make[MBId.to_idmbid]inletmp=MPboundmbidinletsobjs=InterpVisitor.get_module_sobjsfalse(Global.env())(default_inline())meinletsubst=map_mp(get_module_pathme)mpempty_delta_resolverinletsobjs=subst_sobjssubstsobjsinSynterpVisitor.load_module1dirmpsobjs[];InterpVisitor.load_module1dirmpsobjs[](** Compatibility layer *)letimport_modulef~exportmp=Synterp.import_modulef~exportmp;Interp.import_modulef~exportmpletdeclare_moduleidargsmtysme_l=letmp,args,bodies,sign=Synterp.declare_moduleidargsmtysme_linInterp.declare_moduleidargssignbodiesletstart_moduleexportidargsres=letmp,args,sign=Synterp.start_moduleexportidargsresinInterp.start_moduleexportidargssignletend_module()=let_mp=Synterp.end_module()inInterp.end_module()letdeclare_modtypeidargsmtysmty_l=letmp,args,bodies,subtyps=Synterp.declare_modtypeidargsmtysmty_linInterp.declare_modtypeidargssubtypsbodiesletstart_modtypeidargsmtys=letmp,args,sub_mty_l=Synterp.start_modtypeidargsmtysinInterp.start_modtypeidargssub_mty_lletend_modtype()=let_mp=Synterp.end_modtype()inInterp.end_modtype()letdeclare_includeme_asts=letl=Synterp.declare_includeme_astsinInterp.declare_includellet()=append_end_library_hookProfile_tactic.do_print_results_at_close