123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662(************************************************************************)(* * 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*Univ.AbstractContext.toption=structtypetypexpr=Constr.t*Univ.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_objectsvaldo_module:(int->Nametab.object_prefix->Libobject.tlist->unit)->int->DirPath.t->ModPath.t->substitutive_objects->Libobject.tlist->unitvalload_objects:int->Nametab.object_prefix->Libobject.tlist->unitvalopen_object:open_filter->int->Nametab.object_prefix*Libobject.t->unitvalcollect_modules:(open_filter*ModPath.t)list->open_filterMPmap.t*(open_filter*(Nametab.object_prefix*Libobject.t))list->open_filterMPmap.t*(open_filter*(Nametab.object_prefix*Libobject.t))listvaladd_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} *)(** Iterate some function [iter_objects] on all components of a module *)letdo_moduleiter_objectsiobj_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;iter_objects(i+1)prefixobjs;iter_objects(i+1)prefixkobjsendletdo_module'iter_objectsi((sp,kn),sobjs)=do_moduleiter_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=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)->letname=Lib.make_onameprefixidindo_module'load_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=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->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=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_objectsunfiltered1prefixoandcache_keep((sp,kn),kobjs)=anomaly(Pp.str"This module should not be cached!")letcache_object(prefix,obj)=matchobjwith|AtomicObjecto->Libobject.cache_object(prefix,o)|ModuleObject(id,sobjs)->letname=Lib.make_onameprefixidindo_module'load_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)(* Adding operations with containers *)letadd_leafobj=cache_object(Lib.prefix(),obj);matchActions.stagewith|Summary.Stage.Synterp->Lib.Synterp.add_leaf_entryobj|Summary.Stage.Interp->Lib.Interp.add_leaf_entryobjletadd_leavesobjs=letadd_objobj=beginmatchActions.stagewith|Summary.Stage.Synterp->Lib.Synterp.add_leaf_entryobj|Summary.Stage.Interp->Lib.Interp.add_leaf_entryobjend;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 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*Univ.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->vmoduleRawModOps=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.do_moduleSynterpVisitor.load_objects1dirmpsobjs[];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=letfs=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_modtypestateenvmpinl(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_modtypestate(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.do_moduleInterpVisitor.load_objects1dirmpsobjs[];(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_modtypestateenvmpinl([],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_modulestate(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_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)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_modtypestateenvmpinl([],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_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=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.do_moduleSynterpVisitor.load_objects1dirmp([],Objssobjs)keepobjsletimport_modules~exportmpl=let_,objs=SynterpVisitor.collect_modulesmpl(MPmap.empty,[])inList.iter(fun(f,o)->SynterpVisitor.open_objectf1o)objs;matchexportwith|Lib.Import->()|Lib.Export->letentry=ExportObject{mpl}inLib.Synterp.add_leaf_entryentryletimport_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)digestuniv=letmp=MPfiledirinlet()=try(* Is this library already loaded ? *)ignore(Global.lookup_modulemp);withNot_found->begin(* If not, let's do it now ... *)letmp'=Global.importcenvunivdigestinifnot(ModPath.equalmpmp')thenanomaly(Pp.str"Unexpected disk module name.")endinletsobjs,keepobjs=objsinInterpVisitor.do_moduleInterpVisitor.load_objects1dirmp([],Objssobjs)keepobjsletimport_modules~exportmpl=let_,objs=InterpVisitor.collect_modulesmpl(MPmap.empty,[])inList.iter(fun(f,o)->InterpVisitor.open_objectf1o)objs;matchexportwith|Lib.Import->()|Lib.Export->letentry=ExportObject{mpl}inLib.Interp.add_leaf_entryentryletimport_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,lib_stack,lib_stack_syntax=Lib.end_compilationdirinletmp,cenv,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),ast(** {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->f(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.do_moduleSynterpVisitor.load_objects1dirmpsobjs[];InterpVisitor.do_moduleInterpVisitor.load_objects1dirmpsobjs[](** 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_includel