12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151(************************************************************************)(* * 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()(** 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(MPmap.empty:substitutive_objectsMPmap.t)~name:"MODULE-SUBSTOBJS"letmissing_handler=ref(funmp->assertfalse)letset_missing_handlerf=(missing_handler:=f)letsetmpobjs=(table:=MPmap.addmpobjs!table)letgetmp=tryMPmap.findmp!tablewithNot_found->!missing_handlermpend(** 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_onesegletexpand_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.
*)typemodule_objects={module_prefix:Nametab.object_prefix;module_substituted_objects:Libobject.tlist;module_keep_objects:Libobject.tlist;}moduleModObjs:sigvalset:ModPath.t->module_objects->unitvalget:ModPath.t->module_objects(* may raise Not_found *)valall:unit->module_objectsMPmap.tend=structlettable=Summary.ref(MPmap.empty:module_objectsMPmap.t)~name:"MODULE-OBJS"letsetmpobjs=(table:=MPmap.addmpobjs!table)letgetmp=MPmap.findmp!tableletall()=!tableend(** {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(** {6 Declaration of module substitutive objects} *)(** 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.")letcompute_visibilityexistsi=ifexiststhenNametab.ExactlyielseNametab.Untili(** Iterate some function [iter_objects] on all components of a module *)letdo_moduleexistsiter_objectsiobj_dirobj_mpsobjskobjs=letprefix=Nametab.{obj_dir;obj_mp;}inconsistency_checksexistsobj_dir;Nametab.push_module(compute_visibilityexistsi)obj_dirobj_mp;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;iter_objects(i+1)prefixobjs;iter_objects(i+1)prefixkobjsendletdo_module'existsiter_objectsi((sp,kn),sobjs)=do_moduleexistsiter_objectsi(dir_of_spsp)(mp_of_knkn)sobjs[](** 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=ifNametab.exists_modtypespthenanomaly(pr_pathsp++str" already exists.");Nametab.push_modtype(Nametab.Untili)spmp;ModSubstObjs.setmpsobjs(** {6 Declaration of substitutive objects for Include} *)letrecload_objecti(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.load_objecti(prefix,o)|ModuleObject(id,sobjs)->letname=Lib.make_onameprefixidindo_module'falseload_objectsi(name,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_objectsiprefixkobjs(** {6 Implementation of Import and Export commands} *)letmark_objectfobj(exports,acc)=(exports,(f,obj)::acc)letreccollect_modulesmplacc=List.fold_left(funaccfmp->collect_modulefmpacc)acc(List.revmpl)andcollect_module(f,mp)acc=(* May raise Not_found for unknown module and for functors *)letmodobjs=ModObjs.getmpinletprefix=modobjs.module_prefixinletacc=collect_objectsf1prefixmodobjs.module_keep_objectsaccincollect_objectsf1prefixmodobjs.module_substituted_objectsaccandcollect_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->Some(filter_orff0))exportsin(* If the map doesn't change there is nothing new to export.
It's possible that [filter_and] or [filter_or] mangled precise
filters such that we repeat uselessly, but the important
[Unfiltered] case is handled correctly.
*)ifexports==exports'thenaccelsecollect_module(f,mp)(exports',objs)andcollect_exportsfimplacc=ifInt.equali1thenList.fold_left(funaccfmp->collect_exportffmpacc)acc(List.revmpl)elseaccletopen_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=consistency_checkstrueobj_dir;ifin_filter~cat:NonefthenNametab.push_module(Nametab.Exactlyi)obj_dirobj_mp;(* 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_objectsfiprefixkobjsletreccache_object(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.cache_object(prefix,o)|ModuleObject(id,sobjs)->letname=Lib.make_onameprefixidindo_module'falseload_objects1(name,sobjs)|ModuleTypeObject(id,sobjs)->letname=Lib.make_onameprefixidinlet(sp,kn)=nameinload_modtype0sp(mp_of_knkn)sobjs|IncludeObjectaobjs->cache_include(prefix,aobjs)|ExportObject{mpl}->anomalyPp.(str"Export should not be cached")|KeepObject(id,objs)->letname=Lib.make_onameprefixidincache_keep(name,objs)andcache_include(prefix,aobjs)=leto=expand_aobjsaobjsinload_objects1prefixo;open_objectsunfiltered1prefixoandcache_keep((sp,kn),kobjs)=anomaly(Pp.str"This module should not be cached!")(* Adding operations with containers *)letadd_leafobj=cache_object(Lib.prefix(),obj);Lib.add_leaf_entryobj;()letadd_leavesidobjs=letadd_objobj=Lib.add_leaf_entryobj;load_object1(Lib.prefix(),obj)inList.iteradd_objobjs(** {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 substitution corresponding to some functor applications *)letreccompute_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)subst(** 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_objectidlmp0tailmp1objs1lettype_of_modmpenv=function|true->(Environ.lookup_modulempenv).mod_type|false->(Environ.lookup_modtypempenv).mod_typeletrecget_module_path=function|MEidentmp->mp|MEwith(me,_)->get_module_pathme|MEapply(me,_)->get_module_pathme(** 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_modenvinlmtyinassert(sobjs_no_functorsobjs0);(* 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)inlettyp=type_of_modmp1envis_modinletmbids_left,subst=compute_substenvmbidstypmp_linlin(mbids_left,subst_aobjssubstaobjs)letget_functor_sobjsis_modenvinl(params,mexpr)=let(mbids,aobjs)=get_module_sobjsis_modenvinlmexprin(List.mappi1params@mbids,aobjs)(** {6 Handling of module parameters} *)(** 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=get_module_sobjsfalse(Global.env())(default_inline())meinletsubst=map_mp(get_module_pathme)mpempty_delta_resolverinletsobjs=subst_sobjssubstsobjsindo_modulefalseload_objects1dirmpsobjs[](** 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)(idl,(typ,ann))=letinl=inl2intoptanninletlib_dir=Lib.library_dp()inletenv=Global.env()inlet(mty,base,kind)=Modintern.intern_module_astModintern.ModTypetypinlet(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_modtypestate(Global.env())baseinl([],mty)inGlobal.add_constraintscstinletenv=Global.env()inletsobjs=get_module_sobjsfalseenvinlmtyinletmp0=get_module_pathmtyinletfoldacc{CAst.v=id}=letdir=DirPath.make[id]inletmbid=MBId.makelib_diridinletmp=MPboundmbidinletresolver=Global.add_module_parametermbidmtyinlinletsobjs=subst_sobjs(map_mpmp0mpresolver)sobjsindo_modulefalseload_objects1dirmpsobjs[];(mbid,mty,inl)::accinletacc=List.fold_leftfoldaccidlin(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,ctx(** {6 Auxiliary functions concerning subtyping checks} *)letcheck_submtbsub_mtb_l=letfoldsub_mtb(ocst,env)=letstate=((Environ.universesenv,Univ.Constraints.empty),Reductionops.inferred_universes)inlet_,cst=Subtyping.check_subtypesstateenvmtbsub_mtbin(Univ.Constraints.unionocstcst,Environ.add_constraintscstenv)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_l(** Prepare the module type list for check of subtypes *)letbuild_subtypesenvmpargsmtys=let(ctx,ans)=List.fold_left_map(functx(m,ann)->letinl=inl2intoptanninletmte,base,kind=Modintern.intern_module_astModintern.ModTypeminletmte,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_modtypestateenvmpinl(args,mte)inletctx=Univ.ContextSet.add_constraintscstctxinctx,mtb)Univ.ContextSet.emptymtysin(ans,ctx)letcurrent_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)(** {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"(** {6 Current module type information}
This information is stored by each [start_modtype] for use
in a later [end_modtype]. *)letopenmodtype_info=Summary.ref([]:module_type_bodylist)~name:"MODTYPE-INFO"(** {6 Modules : start, end, declare} *)moduleRawModOps=structletstart_moduleexportidargsresfs=letmp=Global.start_moduleidinletparams,ctx=intern_argsargsinlet()=Global.push_context_set~strict:truectxinletenv=Global.env()inletres_entry_o,subtyps,ctx=matchreswith|Enforce(res,ann)->letinl=inl2intoptanninlet(mte,base,kind)=Modintern.intern_module_astModintern.ModTyperesinlet(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_msestateenvNoneinlmteinletctx=Univ.ContextSet.add_constraintscstctxinSome(mte,inl),[],ctx|Checkresl->lettyps,ctx=build_subtypesenvmpparamsreslinNone,typs,ctxinlet()=Global.push_context_set~strict:truectxinopenmod_info:={cur_typ=res_entry_o;cur_typs=subtyps};letprefix=Lib.start_moduleexportidmpfsinNametab.(push_dir(Until1)(prefix.obj_dir)(GlobDirRef.DirOpenModuleprefix));mpletend_module()=letoldprefix,fs,lib_stack=Lib.end_module()inlet{Lib.substobjs=substitute;keepobjs=keep;anticipateobjs=special;}=lib_stackinletm_info=!openmod_infoin(* 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)->get_module_sobjsfalse(Global.env())inlinemty,[],[]inletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinletstruc=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_modulestate(Global.env())(Global.current_modpath())(struc,None,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)]inlet()=add_leavesidobjectsin(* Name consistency check : start_ vs. end_module, kernel vs. library *)assert(DirPath.equal(Lib.prefix()).Nametab.obj_dirolddp);assert(ModPath.equaloldprefix.Nametab.obj_mpmp);mp(* TODO cleanup push universes directly to global env *)letdeclare_moduleidargsresmexpr_ofs=(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp=Global.start_moduleidinletparams,ctx=intern_argsargsinletenv=Global.env()inletenv=Environ.push_context_set~strict:truectxenvinletmty_entry_o,subs,inl_res,ctx'=matchreswith|Enforce(mty,ann)->letinl=inl2intoptanninlet(mte,base,kind)=Modintern.intern_module_astModintern.ModTypemtyinlet(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_msestateenvNoneinlmteinletctx=Univ.ContextSet.add_constraintscstctxinSomemte,[],inl,ctx|Checkmtys->lettyps,ctx=build_subtypesenvmpparamsmtysinNone,typs,default_inline(),ctxinletenv=Environ.push_context_set~strict:truectx'envinletctx=Univ.ContextSet.unionctxctx'inletmexpr_entry_o,inl_expr,ctx'=matchmexpr_owith|None->None,default_inline(),Univ.ContextSet.empty|Some(mexpr,ann)->let(mte,base,kind)=Modintern.intern_module_astModintern.Modulemexprinlet(mte,ctx)=Modintern.interp_module_astenvkindbasemteinSomemte,inl2intoptann,ctxinletenv=Environ.push_context_set~strict:truectx'envinletctx=Univ.ContextSet.unionctxctx'inletentry=matchmexpr_entry_o,mty_entry_owith|None,None->assertfalse(* No body, no type ... *)|None,Sometyp->MType(params,typ)|Somebody,otyp->MExpr(params,body,otyp)inletsobjs,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.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_modulestate(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)sobjsinadd_leaf(ModuleObject(id,sobjs));mpend(** {6 Module types : start, end, declare} *)moduleRawModTypeOps=structletstart_modtypeidargsmtysfs=letmp=Global.start_modtypeidinletarg_entries_r,cst=intern_argsargsinlet()=Global.push_context_set~strict:truecstinletenv=Global.env()inletsub_mty_l,cst=build_subtypesenvmparg_entries_rmtysinlet()=Global.push_context_set~strict:truecstinopenmodtype_info:=sub_mty_l;letprefix=Lib.start_modtypeidmpfsinNametab.(push_dir(Until1)(prefix.obj_dir)(GlobDirRef.DirOpenModtypeprefix));mpletend_modtype()=letoldprefix,fs,lib_stack=Lib.end_modtype()inletolddp,id=split_dirpatholdprefix.Nametab.obj_dirinlet{Lib.substobjs=substitute;keepobjs=_;anticipateobjs=special;}=lib_stackinletsub_mty_l=!openmodtype_infoinletmp,mbids=Global.end_modtypefsidinlet()=check_subtypes_mtmpsub_mty_linletmodtypeobjs=(mbids,Objssubstitute)inlet()=add_leavesid(special@[ModuleTypeObject(id,modtypeobjs)])in(* 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(mty,ann)fs=letinl=inl2intoptannin(* We simulate the beginning of an interactive module,
then we adds the module parameters to the global env. *)letmp=Global.start_modtypeidinletparams,arg_ctx=intern_argsargsinlet()=Global.push_context_set~strict:truearg_ctxinletenv=Global.env()inletmte,base,kind=Modintern.intern_module_astModintern.ModTypemtyinletmte,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_msestateenvNoneinlmteinlet()=Global.push_context_set~strict:true(Univ.Level.Set.empty,mte_cst)inletenv=Global.env()inletentry=params,mteinletsub_mty_l,sub_mty_ctx=build_subtypesenvmpparamsmtysinlet()=Global.push_context_set~strict:truesub_mty_ctxinletenv=Global.env()inletsobjs=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.unfreeze_summariesfs;(* We enrich the global environment *)let()=Global.push_context_set~strict:truearg_ctxinlet()=Global.push_context_set~strict:truemte_ctxinlet()=Global.push_context_set~strict:true(Univ.Level.Set.empty,mte_cst)inlet()=Global.push_context_set~strict:truesub_mty_ctxinletmp_env=Global.add_modtypeidentryinlin(* Name consistency check : kernel vs. library *)assert(ModPath.equalmp_envmp);(* Subtyping checks *)let()=check_subtypes_mtmpsub_mty_linadd_leaf(ModuleTypeObject(id,sobjs));mpend(** {6 Include} *)moduleRawIncludeOps=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.")exceptionNoIncludeSelflettype_of_inclenvis_mod=function|MEidentmp->type_of_modmpenvis_mod|MEapply_asme->letmp0,mp_l=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(me_ast,annot)=letenv=Global.env()inletme,base,kind=Modintern.intern_module_astModintern.ModAnyme_astinletme,cst=Modintern.interp_module_astenvkindbasemeinlet()=Global.push_context_set~strict:truecstinletenv=Global.env()inletis_mod=(kind==Modintern.Module)inletcur_mp=Lib.current_mp()inletinl=inl2intoptannotinletmbids,aobjs=get_module_sobjsis_modenvinlmeinletsubst_self=tryifList.is_emptymbidsthenraiseNoIncludeSelf;lettyp=type_of_inclenvis_modmeinletreso=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_modstate(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=current_struct();mod_type_alg=None;mod_delta=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)inletaobjs=subst_aobjssubstaobjsincache_include(Lib.prefix(),aobjs);Lib.add_leaf_entry(IncludeObjectaobjs)letdeclare_includeme_asts=List.iterdeclare_one_includeme_astsend(** {6 Module operations handling summary freeze/unfreeze} *)letprotect_summariesf=letfs=Summary.freeze_summaries~marshallable:falseintryffswithreraise->(* Something wrong: undo the whole process *)letreraise=Exninfo.capturereraiseinlet()=Summary.unfreeze_summariesfsinExninfo.iraisereraiseletstart_moduleexportidargsres=protect_summaries(RawModOps.start_moduleexportidargsres)letend_module=RawModOps.end_moduleletdeclare_moduleidargsmtysme_l=letdeclare_mefs=matchme_lwith|[]->RawModOps.declare_moduleidargsmtysNonefs|[me]->RawModOps.declare_moduleidargsmtys(Someme)fs|me_l->ignore(RawModOps.start_moduleNoneidargsmtysfs);RawIncludeOps.declare_includeme_l;RawModOps.end_module()inprotect_summariesdeclare_meletstart_modtypeidargsmtys=protect_summaries(RawModTypeOps.start_modtypeidargsmtys)letend_modtype=RawModTypeOps.end_modtypeletdeclare_modtypeidargsmtysmty_l=letdeclare_mtfs=matchmty_lwith|[]->assertfalse|[mty]->RawModTypeOps.declare_modtypeidargsmtysmtyfs|mty_l->ignore(RawModTypeOps.start_modtypeidargsmtysfs);RawIncludeOps.declare_includemty_l;RawModTypeOps.end_modtype()inprotect_summariesdeclare_mtletdeclare_includeme_asts=ifGlobal.sections_are_opened()thenuser_errPp.(str"Include is not allowed inside sections.");protect_summaries(fun_->RawIncludeOps.declare_includeme_asts)(** {6 Libraries} *)typelibrary_name=DirPath.t(** A library object is made of some substitutive objects
and some "keep" objects. *)typelibrary_objects=Libobject.tlist*Libobject.tlist(** For the native compiler, we cache the library values *)letregister_librarydircenv(objs:library_objects)digestuniv=letmp=MPfiledirinlet()=try(* Is this library already loaded ? *)ignore(Global.lookup_modulemp);withNot_found->(* If not, let's do it now ... *)letmp'=Global.importcenvunivdigestinifnot(ModPath.equalmpmp')thenanomaly(Pp.str"Unexpected disk module name.");inletsobjs,keepobjs=objsindo_modulefalseload_objects1dirmp([],Objssobjs)keepobjsletstart_librarydir=letmp=Global.start_librarydirinopenmod_info:=default_module_info;Lib.start_compilationdirmpletend_library_hook=refignoreletappend_end_library_hookf=letold_f=!end_library_hookinend_library_hook:=fun()->old_f();f()letend_library~output_native_objectsdir=!end_library_hook();letprefix,lib_stack=Lib.end_compilationdirinletmp,cenv,ast=Global.export~output_native_objectsdirinassert(ModPath.equalmp(MPfiledir));let{Lib.substobjs=substitute;keepobjs=keep;anticipateobjs=_;}=lib_stackincenv,(substitute,keep),astletimport_modules~exportmpl=let_,objs=collect_modulesmpl(MPmap.empty,[])inList.iter(fun(f,o)->open_objectf1o)objs;matchexportwith|Lib.Import->()|Lib.Export->Lib.add_leaf_entry(ExportObject{mpl})letimport_modulef~exportmp=import_modules~export[f,mp](** {6 Iterators} *)letiter_all_segmentsf=letrecapply_objprefixobj=matchobjwith|IncludeObjectaobjs->letobjs=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->f(Lib.node_prefixnode)o)osinMPmap.iterapply_mod_obj(ModObjs.all());List.iterapply_nodes(Lib.contents())(** {6 Some types used to shorten declaremods.mli} *)typemodule_params=(lidentlist*(Constrexpr.module_ast*inline))list(** {6 Debug} *)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())inhov0modules