123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906(* {{{ COPYING *(
This file is part of Merlin, an helper for ocaml editors
Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net>
Thomas Refis <refis.thomas(_)gmail.com>
Simon Castellan <simon.castellan(_)iuwt.fr>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The Software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall
the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising
from, out ofor in connection with the software or the use or other dealings
in the Software.
)* }}} *)typejson=[`Assocof(string*json)list|`Boolofbool|`Floatoffloat|`Intofint|`Listofjsonlist|`Null|`Stringofstring]moduleJson=structtypet=jsonletstringx=`Stringxletintx=`Intxletboolx=`Boolxletoptionf=function|None->`Null|Somex->fxletlistfx=`List(List.mapfx)letpretty_to_string:(t->string)ref=ref@@fun_->Printf.sprintf"Logger error: `Std.Json.pretty_to_string` is not set. You should \
initialize that reference with the pretifier of your choice to enable \
json logging. A common one is `Yojson.Basic.pretty_to_string`."endmoduleHashtbl=structincludeHashtblletfind_sometblkey=trySome(findtblkey)withNot_found->Noneletelementstbl=Hashtbl.fold(fun_keyeltacc->elt::acc)tbl[]letforalltablef=matchHashtbl.iter(funkv->ifnot(fkv)thenraiseExit)tablewith|()->true|exceptionExit->falseendmoduleList=structincludeListLabelsletinit~fn=letrecauxi=ifi=nthen[]elsefi::aux(succi)inaux0letindex~fl=letrecauxi=function|[]->raiseNot_found|x::_whenfx->i|_::xs->aux(succi)xsinaux0lletfind_some~fl=trySome(find~fl)withNot_found->Noneletrecrev_scan_leftacc~fl~init=matchlwith|[]->acc|x::xs->letinit=finitxinrev_scan_left(init::acc)~fxs~initletscan_left~fl~init=List.rev(rev_scan_left[]~fl~init)letrev_filter~flst=letrecauxacc=function|[]->acc|x::xs->aux(iffxthenx::accelseacc)xsinaux[]lstletrecfilter_map~f=function|[]->[]|x::xs->(matchfxwith|None->filter_map~fxs|Somex->x::filter_map~fxs)letrecfind_map~f=function|[]->raiseNot_found|x::xs->(matchfxwith|None->find_map~fxs|Somex'->x')letrecmap_end~fl1l2=matchl1with|[]->l2|hd::tl->fhd::map_end~ftll2letconcat_map~fl=flatten(map~fl)letreplicateelemn=letrecauxaccelemn=ifn<=0thenaccelseaux(elem::acc)elem(n-1)inaux[]elemnletrecremove?(phys=false)x=letcheck=ifphysthen(==)else(=)infunction|[]->[]|hd::tlwhencheckxhd->tl|hd::tl->hd::remove~physxtlletrecremove_allx=function|[]->[]|hd::tlwhenx=hd->remove_allxtl|hd::tl->hd::remove_allxtlletrecsame~fl1l2=match(l1,l2)with|[],[]->true|hd1::tl1,hd2::tl2whenfhd1hd2->same~ftl1tl2|_,_->false(* [length_lessthan n l] returns
* Some (List.length l) if List.length l <= n
* None otherwise *)letlength_lessthannl=letrecauxi=function|_::xswheni<n->aux(succi)xs|[]->Somei|_->Noneinaux0lletfilter_dup'~equivlst=lettbl=Hashtbl.create17inletfab=letb'=equivbinifHashtbl.memtblb'thenaelse(Hashtbl.addtblb'();b::a)inrev(fold_left~f~init:[]lst)letfilter_duplst=filter_dup'~equiv:(funx->x)lstletrecmerge_cons~f=function|a::(b::tlastl')->beginmatchfabwith|Somea'->merge_cons~f(a'::tl)|None->a::merge_cons~ftl'end|tl->tlletrectake_while~f=function|x::xswhenfx->x::take_while~fxs|_->[]letrecdrop_while~f=function|x::xswhenfx->drop_while~fxs|xs->xsletrectake_naccn=function|x::xswhenn>0->take_n(x::acc)(n-1)xs|_->List.revacclettake_nnl=take_n[]nlletrecdrop_nn=function|_::xswhenn>0->drop_n(n-1)xs|xs->xsletrecsplit_naccn=function|x::xswhenn>0->split_n(x::acc)(n-1)xs|xs->(List.revacc,xs)letsplit_nnl=split_n[]nlletrecsplit3xsyszs=function|(x,y,z)::tl->split3(x::xs)(y::ys)(z::zs)tl|[]->(List.revxs,List.revys,List.revzs)letsplit3l=split3[][][]lletrecunfold~fa=matchfawith|None->[]|Somea->a::unfold~faletrecrev_unfoldacc~fa=matchfawith|None->acc|Somea->rev_unfold(a::acc)~faletrecfold_n_map~f~init=function|[]->(init,[])|x::xs->letacc,x'=finitxinletacc,xs'=fold_n_map~f~init:accxsin(acc,x'::xs')letreciteri2i~fl1l2=match(l1,l2)with|[],[]->()|a1::l1,a2::l2->fia1a2;iteri2(i+1)~fl1l2|_,_->raise(Invalid_argument"iteri2")letiteri2~fl1l2=iteri20~fl1l2moduleLazy=structtype'at=Nil|Consof'a*'atlazy_tletrecmap~f=function|Nil->Nil|Cons(hd,tl)->Cons(fhd,lazy(map~f(Lazy.forcetl)))letrecto_strict=function|Nil->[]|Cons(hd,(lazytl))->hd::to_stricttlletrecunfoldfa=matchfawith|None->Nil|Somea->Cons(a,lazy(unfoldfa))letrecfilter_map~f=function|Nil->Nil|Cons(a,tl)->(matchfawith|None->filter_map~f(Lazy.forcetl)|Somea'->Cons(a',lazy(filter_map~f(Lazy.forcetl))))endlethd_opt=function|[]->None|x::_->Somexletreclast=function|[]->None|[x]->Somex|_::l->lastlletrecgroup_bypredgroupacc=function|[]->List.revacc|x::xs->(matchgroupwith|x'::_whenpredxx'->group_bypred(x::group)accxs|_->group_bypred[x](group::acc)xs)letgroup_bypredxs=matchgroup_bypred[][]xswith|[]::xs|xs->xs(* Merge sorted lists *)letrecmerge~cmpl1l2=match(l1,l2)with|l,[]|[],l->l|x1::_,x2::x2swhencmpx1x2>0->x2::merge~cmpl1x2s|x1::x1s,_->x1::merge~cmpx1sl2letrecdedup_adjacent~cmp=function|x1::(x2::_asxs)whencmpx1x2=0->dedup_adjacent~cmpxs|x::xs->x::dedup_adjacent~cmpxs|[]->[](* [sort_uniq] does not need to maintain a set of seen entries because duplicates will
be adjacent. *)letsort_uniq~cmpl=dedup_adjacent~cmp(sort~cmpl)letprintf()l="[ "^String.concat"; "(List.map(f())l)^" ]"letmax_eltlist~cmp=fold_leftlist~init:None~f:(funaccelt->matchaccwith|None->Someelt|Somemax->ifcmpmaxelt<0thenSomeeltelseacc)letmin_eltlist~cmp=fold_leftlist~init:None~f:(funaccelt->matchaccwith|None->Someelt|Somemin->ifcmpminelt>0thenSomeeltelseacc)endmoduleOption=structletbindopt~f=matchoptwith|None->None|Somex->fxletmap~f=function|None->None|Somex->Some(fx)letget=function|None->raiseNot_found|Somex->xletvalue~default=function|None->default|Somex->xletvalue_map~f~default=function|None->default|Somex->fxletiter~f=function|None->()|Somex->fxletconsoxs=matchowith|None->xs|Somex->x::xsmoduleInfix=structletreturnx=Somexlet(>>=)xf=bindx~flet(>>|)xf=mapx~flet(let*)optf=bindopt~flet(let+)optf=mapopt~fendincludeInfixletto_list=function|None->[]|Somex->[x]letis_some=function|None->false|_->trueletplusab=matchawith|Some_->a|None->bletprintf()=function|None->"None"|Somes->"Some ("^f()s^")"endmoduleResult=structincludeResultletmap~fr=Result.mapfrletbind~fr=Result.bindrfendmoduleString=structincludeStringLabelsletfor_allft=letlen=String.lengthtinletrecloopi=i=len||(ft.[i]&&loop(i+1))inloop0letreverses1=letlen=lengths1inlets2=Bytes.makelen'a'infori=0tolen-1doBytes.sets2is1.[len-i-1]done;Bytes.to_strings2letcommon_prefix_lens1s2=letrecauxi=ifi>=lengths1||i>=lengths2||s1.[i]<>s2.[i]thenielseaux(succi)inaux0(* [is_prefixed ~by s] returns [true] iff [by] is a prefix of [s] *)letis_prefixed~by=letl=String.lengthbyinfuns->letl'=String.lengthsinl'>=l&&tryfori=0topredldoifs.[i]<>by.[i]thenraiseNot_founddone;truewithNot_found->false(* Drop characters from beginning of string *)letdropns=subs~pos:n~len:(lengths-n)moduleSet=structincludeMoreLabels.Set.Make(structtypet=stringletcompare=compareend)letof_listl=List.fold_left~f:(funselt->addelts)l~init:emptyletto_lists=fold~f:(funxxs->x::xs)s~init:[]endmoduleMap=structincludeMoreLabels.Map.Make(structtypet=stringletcompare=compareend)letof_listl=List.fold_left~f:(funm(k,v)->add~key:k~data:vm)l~init:emptyletto_listm=fold~f:(fun~key~dataxs->(key,data)::xs)m~init:[]letkeysm=fold~f:(fun~key~data:_xs->key::xs)m~init:[]letvaluesm=fold~f:(fun~key:_~dataxs->data::xs)m~init:[]letadd_multiplekeydatat=letcurrent=tryfindkeytwithNot_found->[]inletdata=data::currentinadd~key~datatendletmemcs=tryignore(String.indexsc:int);truewithNot_found->falseletfirst_double_underscore_ends=letlen=String.lengthsinletrecauxi=ifi>len-2thenraiseNot_foundelseifs.[i]='_'&&s.[i+1]='_'theni+1elseaux(i+1)inaux0letno_double_underscores=tryignore(first_double_underscore_ends);falsewithNot_found->truelettrim=function|""->""|str->letl=String.lengthstrinletis_space=function|' '|'\n'|'\t'|'\r'->true|_->falseinletr0=ref0andrl=reflinwhile!r0<l&&is_spacestr.[!r0]doincrr0done;letr0=!r0inwhile!rl>r0&&is_spacestr.[!rl-1]dodecrrldone;letrl=!rlinifr0=0&&rl=lthenstrelsesubstr~pos:r0~len:(rl-r0)letprint()s=Printf.sprintf"%S"sletcapitalize=capitalize_asciiletuncapitalize=uncapitalize_asciiletlowercase=lowercase_asciiletuppercase=uppercase_asciiletsplit_on_char_cs=matchString.indexscwith|exceptionNot_found->[s]|p->letrecloopi=matchString.index_fromsicwith|exceptionNot_found->[String.subsi(String.lengths-i)]|j->lets0=String.subsi(j-i)ins0::loop(j+1)inlets0=String.subs0pins0::loop(p+1)letchop_prefix~prefixtext=lettlen=String.lengthtextinletplen=String.lengthprefixiniftlen>=plenthentryfori=0toplen-1doifprefix.[i]<>text.[i]thenraiseNot_founddone;Some(String.subtextplen(tlen-plen))withNot_found->NoneelseNoneletnext_occurrence~patterntextfrom=letplen=String.lengthpatterninletlast=String.lengthtext-pleninleti=reffromandj=ref0inwhile!i<=last&&!j<plendoiftext.[!i+!j]<>pattern.[!j]then(incri;j:=0)elseincrjdone;if!j<plenthenraiseNot_foundelse!iletreplace_all~pattern~with_text=ifpattern=""thentextelsematchnext_occurrence~patterntext0with|exceptionNot_found->text|j0->letbuffer=Buffer.create(String.lengthtext)inletrecauxij=Buffer.add_substringbuffertexti(j-i);Buffer.add_stringbufferwith_;leti'=j+String.lengthpatterninmatchnext_occurrence~patterntexti'with|exceptionNot_found->Buffer.add_substringbuffertexti'(String.lengthtext-i')|j'->auxi'j'inaux0j0;Buffer.contentsbufferletrfindi=letrecloops~fi=ifi<0thenNoneelseiff(String.unsafe_getsi)thenSomeielseloops~f(i-1)infun?froms~f->letfrom=letlen=String.lengthsinmatchfromwith|None->len-1|Somei->ifi>len-1thenfailwith"rfindi: invalid from"elseiinloops~ffromletreccheck_prefixs~prefixleni=i=len||(s.[i]=prefix.[i]&&check_prefixs~prefixlen(i+1))letlsplit2s~on=matchString.index_optsonwith|None->None|Somei->Some(subs~pos:0~len:i,subs~pos:(i+1)~len:(lengths-i-1))letis_prefixs~prefix=letlen=lengthsinletprefix_len=lengthprefixinlen>=prefix_len&&check_prefixs~prefixprefix_len0endletsprintf=Printf.sprintfmoduleFormat=structincludeFormatletdefault_width=ref0letto_string?(width=!default_width)()=letb=Buffer.create32inletppf=formatter_of_bufferbinletcontents()=pp_print_flushppf();Buffer.contentsbinpp_set_marginppfwidth;(ppf,contents)endmoduleLexing=structtypeposition=Lexing.position={pos_fname:string;pos_lnum:int;pos_bol:int;pos_cnum:int}include(Lexing:moduletypeofstructincludeLexingendwithtypeposition:=position)letmovebufp=buf.lex_abs_pos<-p.pos_cnum-buf.lex_curr_pos;buf.lex_curr_p<-pletfrom_strings?empty?positionsourcerefill=letpos=ref0inletlen=ref(String.lengthsource)inletsource=refsourceinletlex_funbufsize=letcount=min(!len-!pos)sizeinletcount=ifcount<=0thenbeginsource:=refill();len:=String.length!source;pos:=0;min!lensizeendelsecountinifcount<=0then0elsebeginString.blit~src:!source~src_pos:!pos~dst:buf~dst_pos:0~len:count;pos:=!pos+count;(matchemptywith|None->()|Somer->r:=!pos>=!len);countendinletbuf=from_functionlex_funinOption.iter~f:(movebuf)position;buf(* Manipulating position *)letmake_pos?(pos_fname="")(pos_lnum,pos_cnum)={pos_fname;pos_lnum;pos_cnum;pos_bol=0}letcolumnpos=pos.pos_cnum-pos.pos_bolletset_columnposcol={poswithpos_cnum=pos.pos_bol+col}letsplit_pospos=(pos.pos_lnum,columnpos)letcompare_posp1p2=matchcomparep1.pos_lnump2.pos_lnumwith|0->compare(columnp1)(columnp2)|n->nletprint_position()p=letl1,c1=split_pospinsprintf"%d:%d"l1c1(* Current position in lexer, even if the buffer is in the middle of a refill
operation *)letimmediate_posbuf={buf.lex_curr_pwithpos_cnum=buf.lex_abs_pos+buf.lex_curr_pos}letjson_of_positionpos=letline,col=split_posposin`Assoc[("line",`Intline);("col",`Intcol)]letmin_posp1p2=ifcompare_posp1p2<=0thenp1elsep2letmax_posp1p2=ifcompare_posp1p2>=0thenp1elsep2endmoduleChar=struct(* FIXME: Remove once we drop support for 4.02 and replace the calls to
[uppercase] and [lowercase] by their [_ascii] version. *)[@@@ocaml.warning"-3"]includeCharletis_lowercasec=lowercase_asciic=cletis_uppercasec=uppercase_asciic=cletis_strictly_lowercasec=not(is_uppercasec)letis_strictly_uppercasec=not(is_lowercasec)endmoduleGlob:sigtypepattern=Wildwild|Exactofstring|RegexpofStr.regexpvalcompile_pattern:string->patternvalmatch_pattern:pattern->string->boolend=structtypepattern=Wildwild|Exactofstring|RegexpofStr.regexpletcompile_pattern=function|"**"->Wildwild|pattern->letregexp=Buffer.create15inletchunk=Buffer.create15inletflush()=ifBuffer.lengthchunk>0then(Buffer.add_stringregexp(Str.quote(Buffer.contentschunk));Buffer.clearchunk)inletl=String.lengthpatterninleti=ref0inwhile!i<ldobeginmatchpattern.[!i]with|'\\'->incri;if!i<lthenBuffer.add_charchunkpattern.[!i]|'*'->flush();Buffer.add_stringregexp".*"|'?'->flush();Buffer.add_charregexp'.'|x->Buffer.add_charchunkxend;incridone;ifBuffer.lengthregexp=0thenExact(Buffer.contentschunk)else(flush();Buffer.add_charregexp'$';Regexp(Str.regexp(Buffer.contentsregexp)))letmatch_patternrestr=matchrewith|Wildwild->true|Regexpre->Str.string_matchrestr0|Exacts->s=strendletfprintf=Format.fprintfletlazy_eqab=match(Lazy.is_vala,Lazy.is_valb)with|true,true->Lazy.force_vala==Lazy.force_valb|false,false->a==b|_->falseletlet_refrvf=letv'=!rinr:=v;matchf()with|result->r:=v';result|exceptionexn->r:=v';raiseexnletfailwithffmt=Printf.ksprintffailwithfmtmoduleShell=structletsplit_commandstr=letcomps=ref[]inletdirty=reffalseinletbuf=Buffer.create16inletflush()=if!dirtythen(comps:=Buffer.contentsbuf::!comps;dirty:=false;Buffer.clearbuf)inleti=ref0andlen=String.lengthstrinletunescape=function|'n'->'\n'|'r'->'\r'|'t'->'\t'|x->xinwhile!i<lendoletc=str.[!i]inincri;matchcwith|' '|'\t'|'\n'|'\r'->flush()|'\\'->dirty:=true;if!i<lenthen(Buffer.add_charbuf(unescapestr.[!i]);incri)|'\''->dirty:=true;while!i<len&&str.[!i]<>'\''doBuffer.add_charbufstr.[!i];incridone;incri|'"'->dirty:=true;while!i<len&&str.[!i]<>'"'do(matchstr.[!i]with|'\\'->incri;if!i<lenthenBuffer.add_charbuf(unescapestr.[!i])|x->Buffer.add_charbufx);incridone;incri|x->dirty:=true;Buffer.add_charbufxdone;flush();List.rev!compsendmoduleSystem=structexternalwindows_merlin_system_command:string->cwd:string->?outfile:string->int="ml_merlin_system_command"letrun_in_directory:(prog:string->prog_is_quoted:bool->args:stringlist->cwd:string->?stdin:string->?stdout:string->?stderr:string->unit->[`Finishedofint|`Cancelled])ref=ref@@fun~prog~prog_is_quoted:_~args~cwd?stdin:_?stdout?stderr:_()->(* Currently we assume that [prog] is always quoted and might contain
arguments such as [-as-ppx]. This is due to the way Merlin gets its
configuration. Thus we cannot rely on [Filename.quote_command]. *)letargs=String.concat~sep:" "@@List.map~f:Filename.quoteargsin(* Runned program should never output on stdout since it is the
channel used by Merlin to communicate with the editor *)letargs=ifSys.win32thenargselseletstdout=matchstdoutwith|Somefile->Filename.quotefile|None->"&2"inPrintf.sprintf"%s 1>%s"argsstdoutinletcmd=Format.sprintf"%s %s"progargsinletexit_code=ifSys.win32then(* Note: the following function will never output to stdout.
When [stdout = None], stdout is sent to stderr. *)windows_merlin_system_commandcmd~cwd?outfile:stdoutelseSys.command(Printf.sprintf"cd %s && %s"(Filename.quotecwd)cmd)in`Finishedexit_codeend(* [modules_in_path ~ext path] lists ocaml modules corresponding to
* filenames with extension [ext] in given [path]es.
* For instance, if there is file "a.ml","a.mli","b.ml" in ".":
* - modules_in_path ~ext:".ml" ["."] returns ["A";"B"],
* - modules_in_path ~ext:".mli" ["."] returns ["A"] *)letmodules_in_path~extpath=letseen=Hashtbl.create7inList.fold_left~init:[]path~f:beginfunresultsdir->tryArray.fold_leftbeginfunresultsfile->ifFilename.check_suffixfileextthenletname=Filename.chop_extensionfileinifHashtbl.memseennamethenresultselse(Hashtbl.addseenname();String.capitalizename::results)elseresultsendresults(Sys.readdirdir)withSys_error_->resultsendletfile_contentsfilename=letic=open_infilenameintryletstr=Bytes.create1024inletbuf=Buffer.create1024inletrecloop()=matchinputicstr01024with|0->()|n->Buffer.add_subbytesbufstr0n;loop()inloop();close_in_noerric;Buffer.contentsbufwithexn->close_in_noerric;raiseexnexternalreraise:exn->'a="%reraise"(** Some value that must be interpreted with respect to a specific work
directory. (e.g. for resolving relative paths or executing sub-commands *)type'awith_workdir={workdir:string;workval:'a}letdump_with_workdirfx:json=`Assoc[("workdir",`Stringx.workdir);("workval",fx.workval)]