123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356(**************************************************************************)(* *)(* Copyright 2013 OCamlPro *)(* *)(* All rights reserved. This file is distributed under the terms of *)(* the Lesser GNU Public License version 3.0. *)(* *)(* This software is distributed in the hope that it will be useful, *)(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)(* Lesser GNU General Public License for more details. *)(* *)(**************************************************************************)(* - Types - *)openIndexTypes(* This type is used to pass the full structure to functions building sub-trees,
so that they can (lazily) lookup type or module type indirections in scope.
Values of this type should have the form {[
[ [Module;Submodule], lazy subtrie_at_Module.Submodule;
[Module], lazy subtrie_at_Module;
[], lazy subtrie_at_Root ]
]}
*)typeparents=(stringlist*tLazy.t)list(* - Utility functions - *)openIndexMisc#ifOCAML_VERSION>=(5,3,0)modulePrinttyp=Out_type#endifletorig_file_name=function|Cmtf|Cmtif|Cmif->fletequal_kindk1k2=matchk1,k2with|Type,Type|Value,Value|Exception,Exception|OpenType,OpenType|Field_,Field_|Variant_,Variant_|Method_,Method_|Module,Module|ModuleType,ModuleType|Class,Class|ClassType,ClassType|Keyword,Keyword->true|Type,_|Value,_|Exception,_|OpenType,_|Field_,_|Variant_,_|Method_,_|Module,_|ModuleType,_|Class,_|ClassType,_|Keyword,_->falselethas_kindkinfo=equal_kindkinfo.kind(* - Trie loading and manipulation functions - *)(* Used as path separator *)letdot=char_of_int0letfix_path_prefixstripnew_pfx=letrectlnn=function|[]->[]|_::tlasl->ifn>0thentln(n-1)tlelselinletrev_pfx=List.revnew_pfxinfunid->{idwithpath=List.rev_appendrev_pfx(tlnstripid.path)}letfix_orig_path_prefix strip new_pfx =letrectlnn=function|[]->[]|_::tlasl->ifn>0thentln(n-1)tlelselinletrev_pfx=List.revnew_pfxinfunid->{idwithorig_path =List.rev_appendrev_pfx(tln stripid.orig_path)}letoverriding_merget1t2=letf=(IndexTrie.filter_keys((<>)dot)t2)inIndexTrie.fold0(funtpath values->lett=List.fold_left(funtv->IndexTrie.addtpathv)(IndexTrie.unsettpath)valuesinifList.exists(function|{kind=Module|ModuleType|Class|ClassType}->true|_->false)valuesthenletsubpath=path@[dot]inIndexTrie.graft_lazy tsubpath(lazy(IndexTrie.subt2subpath))else t)ft1let open_module?(cleanup_path=false)tpath=letstrip_path =fix_path_prefix (List.lengthpath)[]inletsubmodule=IndexTrie.subt(modpath_to_key path)inletsubmodule=ifcleanup_path then IndexTrie.map(fun_key->strip_path)submoduleelsesubmodulein(* IndexTrie.merge ~values:(fun _ v -> v) t submodule -- keeps hidden values in subtrees *)overriding_mergetsubmoduleletalias?(cleanup_path=false)toriginalias =let subtree=IndexTrie.subt(modpath_to_key origin)inletsubtree=letstrip_path =fix_path_prefix (List.lengthorigin)aliasinifcleanup_paththenIndexTrie.map(fun_key->strip_path)subtreeelsesubtreeinIndexTrie.graftt(modpath_to_keyalias)subtree(* Pops comments from a list of comments (string * loc) to find the ones that
are associated to a given location. Also returns the remaining comments after
the location. *)letassociate_comment?(after_only=false)commentslocnextloc=ifloc=Location.nonethenNone,comments elseletlstart=loc.Location.loc_start.Lexing.pos_lnumandlend =loc.Location.loc_end.Lexing.pos_lnuminletisnextc=nextloc<>Location.none&&nextloc.Location.loc_start.Lexing.pos_cnum<c.Location.loc_end.Lexing.pos_cnuminletrecaux=function|[]->None,[]|(comment,cloc)::comments->letcstart=cloc.Location.loc_start.Lexing.pos_lnumandcend=cloc.Location.loc_end.Lexing.pos_lnuminifcend<lstart-1||cstart<lend&&after_onlythenauxcommentselseifcstart>lend+1||isnextcloc||cstart>lstart&&cend<lend (* keep inner comments *)thenNone,(comment,cloc)::commentselseifString.lengthcomment<2||comment.[0]<>'*'||comment.[1]='*'thenauxcommentselseletcomment=String.trim(String.subcomment1(String.lengthcomment-1))inmatchauxcommentswith|None,comments->Somecomment,comments|Somec,comments->Some (String.concat"\n"[comment;c]),commentsinauxcommentsletty_of_sig_item =letopenPrinttypinfunction|Types.Sig_value(id,decl,_)->tree_of_value_descriptioniddecl|Types.Sig_type(id,decl,rs,_)->tree_of_type_declarationid declrs|Types.Sig_typext(id,decl,es,_)->tree_of_extension_constructoriddecles|Types.Sig_module(id,_,{Types.md_type},rs,_)->tree_of_moduleidmd_typers|Types.Sig_modtype(id,decl,_)->tree_of_modtype_declaration iddecl|Types.Sig_class(id,decl,rs,_)->tree_of_class_declaration iddecl rs|Types.Sig_class_type(id,decl,rs,_)-> tree_of_cltype_declarationiddeclrs(* -- Qualifying types -- *)let ns={Outcometree.printed_name=s}letnn{Outcometree.printed_name}=printed_name(* The types may contain unqualified identifiers.
We need to do some (lazy) lookup in the trie to qualify them, so that
for example [M.empty] shows up as [M.t] and not just [t] *)letqualify_ty(parents:parents)ty=letqualifyident=letpath=letrecget_path =function|Outcometree.Oide_identname->[nnname]|Outcometree.Oide_dot(path,s)-> get_pathpath@[s]|Outcometree.Oide_apply(p1,_p2)->get_pathp1inget_pathidentinletkey=modpath_to_key~enddot:falsepathinletreclookup=function|[]|([],_)::_->ident|((path1::pathn),lazyt)::parents->ifnot(List.exists(has_kindType)(IndexTrie.find_alltkey))thenlookupparentselseletrecadd_pfx=function|Outcometree.Oide_dot(idp,s)->Outcometree.Oide_dot(add_pfxidp,s)|Outcometree.Oide_apply(idp,idp2)->Outcometree.Oide_apply(add_pfxidp,idp2)|Outcometree.Oide_idents->letparentpath=List.fold_left(funaccmodl->Outcometree.Oide_dot(acc,modl))(Outcometree.Oide_ident(npath1))pathninOutcometree.Oide_dot(parentpath,nns)inadd_pfxidentinlookupparentsinletrecaux=(* Some kind of Outcometree.map_ty *)letopenOutcometreeinfunction|Otyp_abstract->Otyp_abstract#ifOCAML_VERSION>=(5,1,0)|Otyp_alias{non_gen;aliased;alias}->Otyp_alias{non_gen;aliased=auxaliased;alias}#else|Otyp_alias (ty,str)->Otyp_alias (auxty,str)#endif|Otyp_arrow(str,ty1,ty2)->Otyp_arrow(str,auxty1,auxty2)#ifOCAML_VERSION>=(5,1,0)|Otyp_class(id,tylist)->Otyp_class (qualifyid,List.mapauxtylist)#else|Otyp_class(bl,id,tylist)->Otyp_class(bl,qualifyid,List.mapauxtylist)#endif|Otyp_constr(id,tylist)->Otyp_constr(qualify id,List.mapauxtylist)|Otyp_manifest(ty1,ty2)->Otyp_manifest(auxty1,auxty2)#ifOCAML_VERSION >=(5,5,0)|Otyp_object{fields;row}->letrow=match rowwith|Orow_closed|Orow_open_anonymous->row|Orow_openty->Orow_open(auxty)inOtyp_object{fields=List.map(fun(str,ty)->str,auxty)fields;row}#elifOCAML_VERSION>=(5,1,0)|Otyp_object{fields;open_row}->Otyp_object{fields=List.map(fun(str,ty)->str,auxty)fields;open_row}#else|Otyp_object (strtylist,blopt)->Otyp_object(List.map(fun(str,ty)->str,auxty)strtylist,blopt)#endif|Otyp_record (strbltylist)->#if OCAML_VERSION>=(5,4,0)Otyp_record (List.map(fun{olab_name;olab_mut;olab_atomic;olab_type}->{olab_name;olab_mut;olab_atomic;olab_type=auxolab_type})strbltylist)#elifOCAML_VERSION>=(5,3,0)Otyp_record(List.map(fun{olab_name;olab_mut;olab_type}->{olab_name;olab_mut;olab_type=auxolab_type})strbltylist)#elseOtyp_record(List.map(fun(str,bl,ty)->str,bl,auxty)strbltylist)#endif|Otyp_stuffstr->Otyp_stuffstr|Otyp_sum(strtylisttyoptlist)->Otyp_sum#ifOCAML_VERSION>=(4,14,0)(List.map(fun{ocstr_name=str;ocstr_args=tylist;ocstr_return_type=tyopt}->{ocstr_name=str;ocstr_args=List.mapauxtylist;ocstr_return_type =matchtyoptwithSomety->Some(auxty)|None-> None})#else(List.map(fun(str,tylist,tyopt)->str,List.mapauxtylist,match tyopt withSomety->Some(auxty)|None-> None)#endifstrtylisttyoptlist)#ifOCAML_VERSION>=(5,4,0)|Otyp_tupletylist->Otyp_tuple(List.map(fun(label,x)->(label,auxx))tylist)#else|Otyp_tuple(tylist)->Otyp_tuple (List.mapauxtylist)#endif|Otyp_var(bl,str)->Otyp_var(bl,str)#ifOCAML_VERSION>=(5,1,0)|Otyp_variant(var,bl2,strlistopt)->Otyp_variant(var,bl2,strlistopt)#else|Otyp_variant(bl,var,bl2,strlistopt)->Otyp_variant(bl,var,bl2,strlistopt)#endif|Otyp_poly(str,ty)->Otyp_poly(str,auxty)#ifOCAML_VERSION>=(5,5,0)|Otyp_moduleout_pkg->Otyp_module(qualify_out_pkgout_pkg)#elifOCAML_VERSION>=(5,4,0)|Otyp_module{opack_path;opack_cstrs}->Otyp_module{opack_path;opack_cstrs =List.map(fun(s,ty)->(s,auxty))opack_cstrs}#elifOCAML_VERSION>=(4,13,0)|Otyp_module(str,fl)->Otyp_module(str,List.map(fun(s,ty)->(s,auxty))fl)#else|Otyp_module (str,strl,tylist)->Otyp_module(str,strl,List.mapauxtylist)#endif|Otyp_open->Otyp_open|Otyp_attribute(ty,attr)->Otyp_attribute(auxty,attr)#ifOCAML_VERSION>=(5,5,0)|Otyp_externals->Otyp_externals|Otyp_functor(str,id,out_pkg,ty)->Otyp_functor(str,qualifyid,qualify_out_pkgout_pkg,auxty)andqualify_out_pkg{opack_path;opack_constraints}={opack_path;opack_constraints =List.map(fun(s,ty)->(s,auxty))opack_constraints;}#endifinaux tyletqualify_ty_in_sig_item(parents:parents)=letqual=qualify_typarentsinletopenOutcometreeinfunction|Osig_type(out_type_decl,rc)->Osig_type({out_type_declwithotype_type=qualout_type_decl.otype_type;#ifOCAML_VERSION>=(5,5,0)otype_constraints=List.map(fun(ty1,ty2)->qualty1,qualty2)out_type_decl.otype_constraints;#elseotype_cstrs=List.map(fun(ty1,ty2)->qualty1,qualty2)out_type_decl.otype_cstrs;#endif},rc)|Osig_valueo->Osig_value{owith oval_type=qualo.oval_type}|Osig_typext(constr,es)->Osig_typext({constrwithoext_args=List.mapqualconstr.oext_args},es)|out_sig->out_sig(* don't get down in modules, classes and their types *)(* -- end -- *)letwith_path_loc?srcpathloc=matchsrcpathwith|None->loc|Somepath->letpath=(* Some magic to get the real source when using jbuilder or
ocamlbuild *)letlpath=string_splitFilename.dir_sep.[0]pathinletrecaux=function|"_build"::"default"::r->r|"_build"::"install"::_->[]|"_build"::r->r|p::r->p::auxr|[]->[]inString.concatFilename.dir_sep(auxlpath)inletwith_path_pospos=letopenLexinginifnot(Filename.is_relativepos.pos_fname)thenposelse{poswithpos_fname=Filename.concatpathpos.pos_fname}inletopenLocationin{locwithloc_start=with_path_posloc.loc_start;loc_end=with_path_posloc.loc_end}letloc_of_sig_item=function|Types.Sig_value(_,descr,_)->descr.Types.val_loc|Types.Sig_type(_,descr,_,_)->descr.Types.type_loc|Types.Sig_typext(_,descr,_,_)->descr.Types.ext_loc|Types.Sig_module(_,_,descr,_,_)->descr.Types.md_loc|Types.Sig_modtype(_,descr,_)->descr.Types.mtd_loc|Types.Sig_class(_,descr,_,_)->descr.Types.cty_loc|Types.Sig_class_type(_,descr,_,_)->descr.Types.clty_locletid_of_sig_item=function|Types.Sig_value(id,_,_)|Types.Sig_type (id,_,_,_)|Types.Sig_typext(id,_,_,_)|Types.Sig_module (id,_,_,_,_)|Types.Sig_modtype(id,_,_)|Types.Sig_class(id,_,_,_)|Types.Sig_class_type(id,_,_,_)->idletkind_of_sig_item=function|Types.Sig_value_->Value|Types.Sig_type_->Type|Types.Sig_typext(_,_,Types.Text_exception,_)->Exception|Types.Sig_typext_->OpenType|Types.Sig_module_->Module|Types.Sig_modtype_->ModuleType|Types.Sig_class_->Class|Types.Sig_class_type_->ClassTypeletattrs_of_sig_item=function|Types.Sig_value(_,descr,_)->descr.Types.val_attributes|Types.Sig_type(_,descr,_,_)->descr.Types.type_attributes|Types.Sig_typext(_,descr,_,_)->descr.Types.ext_attributes|Types.Sig_module(_,_,descr,_,_)->descr.Types.md_attributes|Types.Sig_modtype(_,descr,_)->descr.Types.mtd_attributes|Types.Sig_class(_,descr,_,_)->descr.Types.cty_attributes|Types.Sig_class_type(_,descr,_,_)->descr.Types.clty_attributesletdoc_of_attributesattrs=letdoc_loc_id="ocaml.doc"in(* not exported ! *)letopenParsetreeintrymatchList.find(fun{attr_name={Location.txt}}->txt=doc_loc_id)attrswith|{attr_payload=PStr[{pstr_desc=Pstr_eval({pexp_desc},_)}]}->(matchpexp_descwith#ifOCAML_VERSION>=(5,3,0)|Pexp_constant{pconst_desc=Pconst_string(s,_,_);_}->Somes#elifOCAML_VERSION>=(4,11,0)|Pexp_constant(Pconst_string(s,_,_))->Somes#else|Pexp_constant(Pconst_string(s,_))->Somes#endif|_->debug"Unexpected ocaml.doc docstring format";None)|_->NonewithNot_found->None#ifOCAML_VERSION>=(4,14,0)letmake_type_expr~desc~level~scope~id=Types.create_exprdesc~level~scope~id#elif OCAML_VERSION>=(4,13,0)letmake_type_expr~desc~level~scope~id=Types.Private_type_expr.createdesc~level~scope~id#elseletmake_type_expr~desc ~level~scope~id={Types.desc;level;scope;id}#endiflettrie_of_type_decl?commentsinfoty_decl=matchty_decl.Types.type_kindwith#ifOCAML_VERSION>=(5,2,0)|Types.Type_abstract_->[],comments#else|Types.Type_abstract->[],comments#endif|Types.Type_open->[],comments#ifOCAML_VERSION>=(5,5,0)|Types.Type_external_->[],comments#endif|Types.Type_record(fields,_repr)->List.map(fun{Types.ld_id;ld_type;ld_attributes}->#ifOCAML_VERSION>=(4,14,0)letty=Printtyp.tree_of_typexpPrinttyp.Typeld_typein#elseletty=Printtyp.tree_of_typexpfalseld_typein#endifletty=Outcometree.Osig_type(Outcometree.({otype_name="";otype_params=[];otype_type=ty;otype_private=Asttypes.Public;#ifOCAML_VERSION>=(4,10,0)otype_immediate=Type_immediacy.Unknown;#elseotype_immediate=false;#endifotype_unboxed=false;#ifOCAML_VERSION>=(5,5,0)otype_constraints=[];#elseotype_cstrs=[];#endif}),Outcometree.Orec_not)inletdoc=doc_of_attributesld_attributesinletid_name=Ident.nameld_idinstring_to_keyid_name,IndexTrie.create~value:{path=info.path;orig_path=info.path;kind=Fieldinfo;name=id_name;ty=Somety;loc_sig=info.loc_sig;loc_impl=info.loc_impl;doc=lazydoc;file=info.file;}())fields,comments#ifOCAML_VERSION>=(4,13,0)|Types.Type_variant(variants,_rep)->#else|Types.Type_variantvariants->#endifList.map(fun{Types.cd_id;cd_args;cd_attributes}->letty=letparams=matchcd_argswith|Cstr_tuple[]->Outcometree.Otyp_sum[]|Cstr_tuple (param::_asl)->#ifOCAML_VERSION>=(4,14,0)Printtyp.tree_of_typexpPrinttyp.Type#elsePrinttyp.tree_of_typexpfalse#endif(make_type_expr#ifOCAML_VERSION>=(5,4,0)~desc:(Types.Ttuple(List.map(funx->(None,x))l))#else~desc:(Types.Ttuplel)#endif#ifOCAML_VERSION>=(4,14,0)~level:(Types.get_levelparam)#else~level:param.Types.level#endif~scope:0#ifOCAML_VERSION >=(4,14,0)~id:(Types.get_idparam))#else~id:param.Types.id)#endif|Cstr_recordparams ->Outcometree.Otyp_record(List.map(funl->#ifOCAML_VERSION>=(5,3,0){Outcometree.olab_name=Ident.namel.Types.ld_id;olab_mut=l.ld_mutable;#ifOCAML_VERSION>=(5,4,0)olab_atomic =l.ld_atomic;#endifolab_type=Printtyp.tree_of_typexpPrinttyp.Typel.ld_type;}#else(Ident.namel.Types.ld_id,l.ld_mutable=Mutable,#ifOCAML_VERSION>=(4,14,0)Printtyp.tree_of_typexp Printtyp.Typel.ld_type)#elsePrinttyp.tree_of_typexpfalsel.ld_type)#endif#endif)params)inOutcometree.Osig_type (Outcometree.({otype_name="";otype_params=[];otype_type=params;otype_private=Asttypes.Public;#ifOCAML_VERSION>=(4,10,0)otype_immediate=Type_immediacy.Unknown;#elseotype_immediate =false;#endifotype_unboxed=false;#ifOCAML_VERSION>=(5,5,0)otype_constraints=[];#elseotype_cstrs=[];#endif}),Outcometree.Orec_not)inletdoc=doc_of_attributes cd_attributes inletid_name =Ident.namecd_idinstring_to_keyid_name,IndexTrie.create~value:{path =info.path;orig_path=info.path;kind=Variant info;name=id_name;ty=Somety;loc_sig=info.loc_sig;loc_impl=info.loc_impl;doc=lazydoc;file=info.file;}())variants,comments(** Implements looking up a module path in the parents list *)letlookup_parents(parents:parents)pathsig_path=letsig_key,path_key=matchsig_pathwith|hd::tl->modpath_to_key [hd],modpath_to_keytl|[]->assert falseinletreclookup=function|[]->ifdebug_enabledthendebug"WARN: Module or sig reference %s not found a %s\n"(modpath_to_stringsig_path)(modpath_to_stringpath);IndexTrie.empty|(parentpath,lazyt)::parents->lets=IndexTrie.subtsig_keyinifs=IndexTrie.emptythenlookupparents elselets=IndexTrie.subspath_keyinletrewrite_path=fix_path_prefix(List.lengthparentpath+List.lengthsig_path)pathinIndexTrie.map (fun_kv->rewrite_pathv)sinlookupparentsletrecpath_of_ocaml=function|Path.Pidentid->[Ident.nameid]|Path.Pdot(path,s)->path_of_ocamlpath@[s]|Path.Papply(p1,_p2)->path_of_ocamlp1#ifOCAML_VERSION>=(5,1,0)|Pextra_ty(p,_extra_ty)->path_of_ocamlp#endifletrectrie_of_sig_item?comments?srcpathimplloc_trie(parents:parents)(orig_file:orig_file)path sig_itemnext=letid =id_of_sig_itemsig_iteminletloc=with_path_loc?srcpath(loc_of_sig_itemsig_item)inletnextloc =matchnextwith|None->Location.none|Somen->with_path_loc?srcpath(loc_of_sig_itemn)inletdoc,comments=matchdoc_of_attributes(attrs_of_sig_itemsig_item),commentswith|Somes,_->lazy(Somes),comments|None,None->lazyNone,None|None,Somecomments ->letassoc=lazy(associate_comment (Lazy.forcecomments)locnextloc)inlazy (fst(Lazy.forceassoc)),Some(lazy(snd(Lazy.force assoc)))inletty=Some(ty_of_sig_itemsig_item)inletkind=kind_of_sig_itemsig_iteminletloc_sig=lazylocinletloc_impl=lazy(matchimplloc_triewith|lazyNone->loc|lazy(Somet)->tryletpath=List.tlpath@[Ident.nameid]inletkey=modpath_to_key~enddot:falsepathinletc=List.find (has_kind kind)(IndexTrie.find_alltkey)inLazy.forcec.loc_implwithNot_found ->Location.none)inlet info={path;orig_path=path;kind;name=Ident.nameid;ty;loc_sig;loc_impl;doc;file=orig_file}inletsiblings,comments=(* read fields / variants ... *)matchsig_itemwith|Types.Sig_type(_id,descr,_is_rec,_)->trie_of_type_decl?commentsinfodescr|_->[],commentsin(* ignore functor arguments *)letrecsig_item_contents=function|Types.Sig_module(id,presence,#ifOCAML_VERSION >=(4,10,0)({Types.md_type=Types.Mty_functor(_,s)}asfunct),#else({Types.md_type=Types.Mty_functor(_,_,s)}asfunct),#endifis_rec,visibility)->letfunct={functwithTypes.md_type=s}insig_item_contents(Types.Sig_module(id,presence,funct,is_rec,visibility))|Types.Sig_modtype#ifOCAML_VERSION>=(4,10,0)(id,({Types.mtd_type=Some(Types.Mty_functor(_,s))}asfunct),visibility)#else(id,({Types.mtd_type=Some(Types.Mty_functor(_,_,s))}asfunct),visibility)#endif->letfunct ={functwithTypes.mtd_type=Somes}insig_item_contents (Types.Sig_modtype(id,funct,visibility))|si->siin(* read module / class contents *)letchildren,comments =matchsig_item_contentssig_itemwith|Types.Sig_module(id,_,{Types.md_type=Types.Mty_signaturesign},_,_)|Types.Sig_modtype(id,{Types.mtd_type=Some(Types.Mty_signaturesign)},_)->letpath=path@[Ident.nameid]inletchildren_comments=lazy (foldl_next(fun(t,comments)signnext->letchlds,comments=trie_of_sig_item?comments?srcpathimplloc_trie((path,lazyt)::parents)orig_filepathsignnextinList.fold_leftIndexTrie.appendtchlds,comments)(IndexTrie.empty,comments)sign)inletchildren=lazy(fst(Lazy.forcechildren_comments))inletcomments=matchcomments,children_commentswith|None,_->None|Some_,lazy(_,comments)->commentsinchildren,comments|Types.Sig_module(_,_,{Types.md_type=Types.Mty_identsig_ident|Types.Mty_aliassig_ident},_,_)|Types.Sig_modtype(_,{Types.mtd_type=Some(Types.Mty_identsig_ident|Types.Mty_aliassig_ident)},_)->letsig_path=path_of_ocamlsig_identinletchildren=lazy((* Only keep the children, don't override the module reference*)letlocal_path=path@[Ident.nameid]inletcanonical()=matchdocwith|lazy(Somed)->letrecaux =function|"@canonical"::path::_->Some(IndexMisc.string_split'.'path)|_::r->auxr|[]->Noneinaux(IndexMisc.string_split' 'd)|_->Noneinletm=lazy(let m=lookup_parents parentslocal_pathsig_pathinmatchcanonical()with|Somepath ->letstrip_path =fix_orig_path_prefix(List.lengthsig_path)pathinIndexTrie.map(fun_key->strip_path)m|None->m)inIndexTrie.graft_lazyIndexTrie.empty[]m)inchildren,comments|Types.Sig_class(id,{Types.cty_type=cty},_,_)|Types.Sig_class_type(id,{Types.clty_type=cty},_,_)->letrecget_clsig=function|Types.Cty_constr(_,_,cty)|Types.Cty_arrow(_,_,cty)->get_clsigcty|Types.Cty_signatureclsig->clsiginletclsig=get_clsigctyinletpath=path@[Ident.nameid]inlet(fields,_)=Ctype.flatten_fields(Ctype.object_fieldsclsig.Types.csig_self)inlazy(List.fold_left(funt(lbl,_,ty_expr)->iflbl="*dummy method*"thentelse#ifOCAML_VERSION>=(4,14,0)let()=Printtyp.prepare_for_printing[ty_expr]inletty=Printtyp.tree_of_typexpPrinttyp.Typety_exprin#elselet()=Printtyp.reset_and_mark_loopsty_exprinlet ty=Printtyp.tree_of_typexpfalsety_exprin#endifletty=Outcometree.Osig_type (Outcometree.({otype_name ="";otype_params=[];otype_type =ty;otype_private=Asttypes.Public;#ifOCAML_VERSION >=(4,10,0)otype_immediate=Type_immediacy.Unknown;#elseotype_immediate=false;#endifotype_unboxed=false;#ifOCAML_VERSION>=(5,5,0)otype_constraints=[];#elseotype_cstrs =[];#endif}),Outcometree.Orec_not)inIndexTrie.addt(string_to_keylbl){path=path;orig_path=path;kind=Methodinfo;name=lbl;ty=Somety;loc_sig=loc_sig;loc_impl=loc_impl;doc=lazyNone;file=info.file})IndexTrie.emptyfields),comments|_->lazyIndexTrie.empty,commentsinletname=Ident.nameidinifString.lengthname>0&&name.[0]='#'then[],commentselse(string_to_keyname,IndexTrie.create~value:info~children:(lazy[dot,Lazy.force children])())::siblings,comments(* These four functions go throughthe typedtree to extract includes *)letreclookup_trie_of_module_exprparentstpath=function|Typedtree.Tmod_ident(incpath,{Location.txt=_lid})->letincpath=path_of_ocamlincpathindebug"Including %s impl at %s\n"(modpath_to_stringincpath)(modpath_to_stringpath);letparents=(path,lazyt)::parentsinletsub=lookup_parentsparentspathincpathinoverriding_mergetsub|Typedtree.Tmod_constraint(e,_,_,_)(* | Typedtree.Tmod_apply (e,_,_) *)->lookup_trie_of_module_exprparentstpathe.mod_desc#ifOCAML_VERSION>=(4,10,0)|Typedtree.Tmod_apply({mod_desc=Typedtree.Tmod_functor(Typedtree.Named(Someid,_,_),f)},#else|Typedtree.Tmod_apply({mod_desc=Typedtree.Tmod_functor(id,_,_,f)},#endif{mod_desc=Typedtree.Tmod_ident(arg,_)|Typedtree.Tmod_constraint ({mod_desc =Typedtree.Tmod_ident(arg,_)},_,_,_)},_)->letid_name=Ident.nameidinlett=lookup_trie_of_module_exprparentstpathf.Typedtree.mod_descindebug"Grafting %s at %s\n"id_name(modpath_to_string(path_of_ocamlarg));letfunctor_arg=lazy(lookup_parents parents(path_of_ocamlarg)path)inIndexTrie.graft_lazyt(modpath_to_key[id_name])functor_arg|_->tletrecextract_includes_from_submodule_sigparentstpathname=function|Typedtree.Tmty_signaturesign->letpath=path@[name]inletsub_includes=lazy(get_includes_sig((path,lazyt)::parents)(IndexTrie.subt(modpath_to_key[name]))pathsign)inIndexTrie.graft_lazyt(modpath_to_key[name])sub_includes#ifOCAML_VERSION>=(4,10,0)|Typedtree.Tmty_functor(_,e)#else|Typedtree.Tmty_functor(_,_,_,e)#endif|Typedtree.Tmty_with(e,_)->extract_includes_from_submodule_sig parentstpathnamee.Typedtree.mty_desc|_->tandextract_includes_from_submodule_sig_optparentstpathidmty=#ifOCAML_VERSION>=(4,10,0)matchidwith None->t|Someid->#endifextract_includes_from_submodule_sigparentstpath(Ident.nameid)mtyandget_includes_implparentstpathttree_struct=letrecextract_submodule_impltname =function|Typedtree.Tmod_structurestr->letpath=path@[name]inletsub_includes=lazy(get_includes_impl((path,lazyt)::parents)(IndexTrie.subt(modpath_to_key[name]))pathstr)inIndexTrie.graft_lazyt(modpath_to_key[name])sub_includes(* | Typedtree.Tmod_functor (arg_id,_,arg_t,e) *)#ifOCAML_VERSION>=(4,10,0)|Typedtree.Tmod_apply({mod_desc=Typedtree.Tmod_functor(Typedtree.Named(Someid,_,_),f)},#else|Typedtree.Tmod_apply({mod_desc=Typedtree.Tmod_functor(id,_,_,f)},#endif{mod_desc=Typedtree.Tmod_ident(arg,_)|Typedtree.Tmod_constraint({mod_desc=Typedtree.Tmod_ident(arg,_)},_,_,_)},_)->letid_name=Ident.nameidindebug"Grafting %s at%s\n"id_name(modpath_to_string(path_of_ocamlarg));letfunctor_arg =lazy(lookup_parents((path,lazyt)::parents)(path_of_ocamlarg)(path@[name]))inextract_submodule_impl(IndexTrie.graft_lazyt(modpath_to_key[id_name])functor_arg)namef.Typedtree.mod_desc#ifOCAML_VERSION>=(4,10,0)|Typedtree.Tmod_functor(_,e)#else|Typedtree.Tmod_functor(_,_,_,e)#endif|Typedtree.Tmod_constraint(e,_,_,_)->extract_submodule_impltnamee.Typedtree.mod_desc|_->tinletextract_submodule_impl_opttidmty=#ifOCAML_VERSION >=(4,10,0)matchidwithNone->t|Someid->#endifextract_submodule_implt(Ident.nameid)mtyinList.fold_left (funtstruc_item->matchstruc_item.Typedtree.str_descwith|Typedtree.Tstr_include{Typedtree.incl_mod={Typedtree.mod_desc=e}}->lookup_trie_of_module_exprparentstpathe|Typedtree.Tstr_openTypedtree.{open_expr={mod_desc=Tmod_ident(p,_loc)}}(* TODO: handle the other new open cases *)->letsub=lookup_parents ((path,lazyt)::parents)path(path_of_ocamlp)inoverriding_mergetsub|Typedtree.Tstr_module{Typedtree.mb_id;mb_expr={Typedtree.mod_desc}}->extract_submodule_impl_opttmb_idmod_desc|Typedtree.Tstr_recmodulel->List.fold_left(funt{Typedtree.mb_id;mb_expr={Typedtree.mod_desc}}->extract_submodule_impl_opttmb_idmod_desc)tl|Typedtree.Tstr_modtype{Typedtree.mtd_id=id;mtd_type=Some{Typedtree.mty_desc=e}}->extract_includes_from_submodule_sigparentstpath(Ident.nameid)e|_->t)tttree_struct.Typedtree.str_itemsandget_includes_sig parentstpathttree_sig=letrecextract_includes t=function|Typedtree.Tmty_ident(incpath,_)->letincpath=path_of_ocamlincpathindebug"Including %ssig at %s\n" (modpath_to_stringincpath)(modpath_to_stringpath);letparents=(path,lazyt)::parentsinletsub=lookup_parentsparentspathincpath inoverriding_mergetsub|Typedtree.Tmty_with(e,_)->extract_includeste.Typedtree.mty_desc|Typedtree.Tmty_typeofe->lookup_trie_of_module_exprparentstpathe.Typedtree.mod_desc|_->tinList.fold_left(funtsig_item->matchsig_item.Typedtree.sig_descwith|Typedtree.Tsig_include{Typedtree.incl_mod={Typedtree.mty_desc=e}}->extract_includeste|Typedtree.Tsig_module{Typedtree.md_id;md_type={Typedtree.mty_desc}}->extract_includes_from_submodule_sig_optparentstpathmd_idmty_desc|Typedtree.Tsig_modtype{Typedtree.mtd_id=id;mtd_type=Some{Typedtree.mty_desc}}->extract_includes_from_submodule_sig parentstpath(Ident.nameid)mty_desc|Typedtree.Tsig_recmodulel->List.fold_left(funt{Typedtree.md_id;md_type={Typedtree.mty_desc}}->extract_includes_from_submodule_sig_optparentstpathmd_idmty_desc)tl|_->t)tttree_sig.Typedtree.sig_itemsletadd_locs~locst=IndexTrie.map(funpathinfo->letloc_info=lazy(List.find(has_kindinfo.kind)(IndexTrie.find_alllocspath))inletlookupfldnone=letloc=Lazy.force(fldinfo)inifloc=nonethentryLazy.force(fld(Lazy.forceloc_info))withNot_found->noneelselocin{info withloc_sig =lazy(lookup(funi->i.loc_sig)Location.none);loc_impl=lazy(lookup (funi->i.loc_impl)Location.none);doc=lazy(lookup(funi->i.doc)None);})tletcmt_includesparentstpathcmt_contents=matchcmt_contents.Cmt_format.cmt_annotswith|Cmt_format.Implementationimpl->get_includes_implparentstpathimpl|Cmt_format.Interfacesign->get_includes_sigparentstpathsign|_->IndexTrie.empty(* Can work in a subtree (t doesn't have to be the root) *)letqualify_type_identsparentst=letqualify_keyid=letrel_path =letrecrm_pfxparentspath=matchparents,pathwith|[_root],path->path|_::parents,_::path->rm_pfxparentspath|_->assertfalseinrm_pfx parentsid.pathinletqualify_tyty=letparents=letrecauxaccpath=matchacc,pathwith|((pfx,parent)::_),modl::r->lett=lazy (IndexTrie.sub(Lazy.forceparent)(string_to_key(modl)@[dot]))inaux((pfx@[modl],t)::acc)r|_->accinauxparentsrel_pathinqualify_ty_in_sig_itemparentstyin{idwithty=matchid.tywithSomety->Some(qualify_tyty)|None-> None}inIndexTrie.mapqualifytletcmt_signcmt_contents=matchcmt_contents.Cmt_format.cmt_annots with|Cmt_format.Implementation{Typedtree.str_type=sign;_}|Cmt_format.Interface{Typedtree.sig_type=sign;_}|Cmt_format.Packed(sign,_)->Somesign|_->Noneletprotect_readreaderf=try readerfwith|Cmt_format.Error_|Cmi_format.Error_->raise(Bad_format f)(* Look for a cmt file for the purpose of loading implementation locations.
(assuming other information is already loaded eg. from the cmti). *)letlookup_loc_implorig_file=matchorig_filewith|Cmt_->None|Cmif|Cmtif->let cmt=Filename.chop_extensionf^".cmt"inifSys.file_existscmtthenSomecmtelseletdir =Filename.dirnamecmtin(* dune 2 puts .cmt under native/ while cmi and cmti are under byte/ *)ifFilename.basenamedir="byte"thenlet(/)=Filename.concatinletcmt=Filename.dirnamedir/"native"/Filename.basenamecmtinifSys.file_existscmtthenSomecmtelseNoneelseNoneletload_loc_implparentsfilenamecmt_contents=debug" -Registering %s (for implementation locations)..."filename;letchrono=timer ()inmatch cmt_signcmt_contentswith|Somesign->letsrcpath=cmt_contents.Cmt_format.cmt_builddirinlett=foldl_next(funtsig_itemnext->letchld,_comments=trie_of_sig_item ~srcpath(lazyNone)parents(Cmtfilename)[]sig_itemnextinList.fold_leftIndexTrie.appendtchld)IndexTrie.emptysignindebug" %.3fs\n%!"(chrono());letincludes=cmt_includesparentst[]cmt_contents inlett=add_locs~locs:includestinSomet|_->debug" %.3fs\n%!"(chrono());Noneletload_cmi ~qualify roottmodulorig_file=IndexTrie.map_subtreet(string_to_keymodul)(funt->letfile=orig_file_nameorig_fileinletinfo=lazy(letchrono=timer()inletinfo=protect_readCmi_format.read_cmifileindebug " %.3fs\n"(chrono());info)inletimpl_cmt=lazy (matchlookup_loc_implorig_filewith|Somecmt->debug"Loading %s (for implementation locations)..."cmt;letchrono=timer()inletcmt_contents =protect_readCmt_format.read_cmtcmtindebug" %.3fs\n"(chrono());Some (cmt,cmt_contents)|None->None)inletchildren=lazy(letinfo=Lazy.forceinfoindebug" -Registering %s..." file;letchrono =timer ()inletrecimplloc_trie=lazy(matchLazy.forceimpl_cmtwith|Some(file,info)->load_loc_impl [[modul],lazy_t;[],root]fileinfo|None->None)andlazy_t=lazy(foldl_next(funtsig_itemnext->letparents =[[modul],lazyt;[],root]inletchld,_comments=trie_of_sig_itemimplloc_trieparentsorig_file[modul]sig_itemnextinList.fold_left IndexTrie.appendtchld)IndexTrie.emptyinfo.Cmi_format.cmi_sign)inlett=Lazy.forcelazy_t indebug" %.3fs ; done\n%!"(chrono());t)inlett=IndexTrie.addt[]{path=[];orig_path=[];kind=Module;name =modul;ty=None;loc_sig =Lazy.from_valLocation.none;loc_impl =Lazy.from_valLocation.none;doc=lazyNone;file=orig_file;}inletchildren=ifqualifythenlazy(qualify_type_idents [[modul],children;[],root](Lazy.forcechildren))elsechildreninIndexTrie.graft_lazyt[dot]children)letload_cmt~qualifyroottmodulorig_file=IndexTrie.map_subtreet(string_to_keymodul)(funt->letcmt_file=orig_file_nameorig_fileinletinfo=lazy(debug"Loading %s..."cmt_file;letchrono=timer()inletinfo=protect_readCmt_format.read_cmtcmt_fileindebug" %.3fs\n"(chrono());info)inletimpl_cmt=lazy(matchlookup_loc_implorig_filewith|Somecmt->debug"Loading %s (for implementation locations)..."cmt;letchrono=timer()inletcmt_contents=protect_readCmt_format.read_cmtcmtindebug" %.3fs\n"(chrono());Some(cmt,cmt_contents)|None->None)inletchildren=lazy(letinfo=Lazy.forceinfoindebug" -Registering %s..."cmt_file;letchrono=timer()inletcomments=Some(Lazy.from_valinfo.Cmt_format.cmt_comments)inletrecimplloc_trie=lazy(matchLazy.forceimpl_cmtwith|Some(file,info)->load_loc_impl [[modul],lazy_t;[],root]fileinfo|None->None)andlazy_t=lazy(matchcmt_signinfowith|Somesign->letsrcpath=info.Cmt_format.cmt_builddir inlett,_trailing_comments=foldl_next(fun (t,comments)sig_itemnext->letparents =[[modul],lazyt;[],root]inletchld,comments =trie_of_sig_item ?comments~srcpathimplloc_trie parentsorig_file[modul]sig_itemnextinList.fold_left IndexTrie.appendtchld,comments)(IndexTrie.empty,comments)signint|None ->IndexTrie.empty)inlett=Lazy.forcelazy_tindebug" %.3fs\n%!"(chrono());t)inletchildren=lazy(letincludes=cmt_includes[[modul],children;[],root]t[](Lazy.forceinfo)inadd_locs~locs:includes(Lazy.forcechildren))inletloc_sig,loc_impl=letof_info i=matchi.Cmt_format.cmt_sourcefilewith|Somef->Location.in_filef|None->Location.noneinmatchorig_filewith|Cmi_|Cmti_->lazy(of_info (Lazy.forceinfo)),lazy (match Lazy.forceimpl_cmtwith|Some (_,i)->of_info i|None->Location.none)|Cmt_->letl=lazy(of_info(Lazy.force info))inl,linlett=IndexTrie.addt[]{path=[];orig_path=[];kind=Module;name =modul;ty=None;loc_sig;loc_impl;doc=lazy None;file=orig_file;}inletchildren=ifqualifythenlazy(qualify_type_idents [[modul],children;[],root](Lazy.forcechildren))elsechildreninIndexTrie.graft_lazyt[dot]children)letdebug_file_counter=ref0letdebug_dir_counter=ref0letload_file~qualifyroottmodulf=incrdebug_file_counter;matchfwith|Cmi_->load_cmi ~qualifyroottmodulf|Cmt_|Cmti_->load_cmt~qualifyroot tmodulfletload_files~qualifytdirfiles=letsplit_filenamefile=tryleti=String.rindexfile'.'inletlen=String.length fileinletmodul=String.capitalize_ascii(String.subfile0i)inletext=String.lowercase_ascii(String.subfile(i+1)(len-i-1))inmodul,extwith Not_found ->file,""inletsort_modulesacc(dir,file)=let regbase=IndexTrie.addacc(string_to_keybase)inmatchsplit_filenamefilewith|base,"cmi"->regbase(Cmi(Filename.concatdirfile))|base,"cmt"->regbase(Cmt(Filename.concat dirfile))|base,"cmti"->regbase(Cmti(Filename.concatdirfile))|_->accinletmodules=List.fold_leftsort_modules IndexTrie.emptydirfilesinletrecroot=lazy(IndexTrie.fold0(funtmodulfiles->matchfileswith|[]->t|f1::fs->(* Load byorder of priority:
- first cmti, more info than cmi, ocamldocs, and doesn't expose
private values
- then cmt, it means there is no mli, everything is exposed
- then cmi, has the interface if not much more *)letchoose_filef1f2=matchf1,f2with|(Cmti _asf),_|_,(Cmti_asf)|(Cmt _asf),_|_,(Cmt_asf)|(Cmi_asf),_->finletfile=List.fold_leftchoose_file f1fsinletmodul=key_to_stringmodulinload_file~qualifyroottmodulfile)modulest)inLazy.forcerootletload_dirs~qualifytdirs=letdirfiles=List.fold_left(funaccdir->incrdebug_dir_counter;letfiles=List.rev_map(funf->dir,f)(Array.to_list(Sys.readdirdir))inList.rev_appendfilesacc)[](List.revdirs)inload_files~qualifytdirfilesletload~qualifypaths=lett=IndexTrie.create()inlett=List.fold_left(funtinfo->IndexTrie.addt(string_to_keyinfo.name)info)tIndexPredefined.allinletchrono=timer()inlett=load_dirs~qualifytpathsindebug"Modules directory loaded in %.3fs (%d files in %d directories)...\n"(chrono())!debug_file_counter!debug_dir_counter;open_module~cleanup_path:truet["Stdlib"]letfully_open_module?(cleanup_path=false)~qualifytpath=letbase_path=matchpathwith|m::_->string_to_keym|[]->[]in(* Merge trying to keep the documentation if the new trie has none *)letmergeintfsimpls=letkeep_intfinfo=tryletintf=List.find(has_kindinfo.kind)intfsinletdoc=lazy(matchinfo.docwith|lazyNone->Lazy.forceintf.doc|lazysome->some)inletloc_sig=intf.loc_sigin{infowithdoc;loc_sig}withNot_found->infoinList.mapkeep_intfimplsinlettpath=modpath_to_keypathinletmod_trie=IndexTrie.subttpathinletmod_trie=trymatch(IndexTrie.findtbase_path).filewith|Cmtif|Cmif->letf=Filename.chop_extensionf^".cmt"inifnot(Sys.file_existsf)thenmod_trieelseletdir,base=Filename.dirnamef,Filename.basenamefinlett=load_files~qualifyIndexTrie.empty[dir,base]inlett=IndexTrie.subttpathinIndexTrie.merge~values:mergemod_triet|Cmt_->mod_triewithNot_found->mod_triein(* cleanup and merge at root (cf. open_module) *)letmod_trie=ifcleanup_paththenletpathlen=List.lengthpathinIndexTrie.map(fun_key->fix_path_prefixpathlen[])mod_trieelsemod_trieinoverriding_mergetmod_trieletadd_file~qualifytfile=letdir,file=Filename.dirnamefile,Filename.basenamefileinload_files~qualifyt[dir,file]