123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451(* {{{ 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 of or in connection with the software or the use or other dealings
in the Software.
)* }}} *)openStdlet{Logger.log}=Logger.for_section"Mconfig_dot"typedirective=Merlin_dot_protocol.directivetypeconfig={build_path:stringlist;source_path:stringlist;hidden_build_path:stringlist;hidden_source_path:stringlist;cmi_path:stringlist;cmt_path:stringlist;index_files:stringlist;flags:stringlistwith_workdirlist;extensions:stringlist;suffixes:(string*string)list;stdlib:stringoption;source_root:stringoption;unit_name:stringoption;wrapping_prefix:stringoption;reader:stringlist;exclude_query_dir:bool;use_ppx_cache:bool}letempty_config={build_path=[];hidden_build_path=[];hidden_source_path=[];source_path=[];cmi_path=[];cmt_path=[];index_files=[];extensions=[];suffixes=[];flags=[];stdlib=None;source_root=None;unit_name=None;wrapping_prefix=None;reader=[];exclude_query_dir=false;use_ppx_cache=false}letwhite_regexp=Str.regexp"[ \t]+"(* Parses suffixes pairs that were supplied as whitespace separated pairs
designating implementation/interface suffixes. These would be supplied in
the .merlin file as:
SUFFIX .sfx .sfxi *)letparse_suffixstr=lettrimmed=String.trimstrinletsplit_on_white=Str.splitwhite_regexptrimmedinifList.lengthsplit_on_white!=2then[]elseletfirst,second=(List.nthsplit_on_white0,List.nthsplit_on_white1)inifString.getfirst0!='.'||String.getsecond0!='.'then[]else[(first,second)](* This module contains invariants around processes that need to be preserved *)moduleConfigurator:sigtypet=Dot_merlin|Dunevalof_string_opt:string->toptionvalto_string:t->stringexceptionProcess_exitedmoduleProcess:sigtypenonrect={kind:t;initial_cwd:string;stdin:out_channel;stdout:in_channel;stderr:in_channel}end(* [Some] if the process is live, [None] if the process died immediately after
spawning. The check is a bit fragile, but is principally there to check if
`dot-merlin-reader` isn't installed or isn't on the PATH; it only needs to
be best-effort besides that. This function can raise [Process_exited] and
[Unix_error]. *)valget_process_exn:dir:string->t->Process.tend=structtypet=Dot_merlin|Duneletof_string_opt=function|".merlin"->SomeDot_merlin|"dune-project"|"dune-workspace"->SomeDune|_->Noneletto_string=function|Dot_merlin->"dot-merlin-reader"|Dune->"dune"exceptionProcess_exitedmoduleProcess=structtypenonrect={kind:t;initial_cwd:string;stdin:out_channel;stdout:in_channel;stderr:in_channel}moduleWith_pid=structtypenonrect={pid:int;process:t}endletstart~dircfg=letprog,args=matchcfgwith|Dot_merlin->letprog="dot-merlin-reader"in(prog,[|prog|])|Dune->letprog="dune"in(prog,[|prog;"ocaml-merlin";"--no-print-directory"|])inletcwd=Sys.getcwd()inletstdin_r,stdin_w=Unix.pipe()inletstdout_r,stdout_w=Unix.pipe()inletstderr_r,stderr_w=Unix.pipe()inUnix.chdirdir;Unix.set_close_on_execstdin_w;(* Set the windows equivalent of close on exec for and stdin stderr
Most processes spawned by merlin are supposed to inherit stderr to
output their debug information. This is fine because these processes
are short-lived.
However the dune helper we are about to spawn is long-lived, which can
cause issues with inherited descriptors because it will outlive
merlin's client process.
This is not an issue under Unix because file descriptors are replaced
(stdin/out/err are new), but under Windows, handle can accumulate.
This makes emacs block, synchronously waiting for the inherited (but
unused) stdout/stderr to be closed.
Os_ipc.merlin_dont_inherit_stdio is a no-op under Unix.
*)Os_ipc.merlin_dont_inherit_stdiotrue;log~title:"get_config""Starting %s configuration provider from dir %s."(to_stringcfg)dir;letpid=letopenUnixintrycreate_processprogargsstdin_rstdout_wstderr_wwithUnix_error_aserr->Os_ipc.merlin_dont_inherit_stdiofalse;chdircwd;List.iter~f:close[stdin_r;stdin_w;stdout_r;stdout_w;stderr_r;stderr_w];raiseerrinOs_ipc.merlin_dont_inherit_stdiofalse;Unix.chdircwd;Unix.closestdin_r;Unix.closestdout_w;Unix.closestderr_w;letstdin=Unix.out_channel_of_descrstdin_winletstdout=Unix.in_channel_of_descrstdout_rinletstderr=Unix.in_channel_of_descrstderr_rinletinitial_cwd=Misc.canonicalize_filenamedirinWith_pid.{pid;process={kind=cfg;initial_cwd;stdin;stdout;stderr}}end(* Invariant: Every PID in this hashtable can be waited on. This means it's
either running or hasn't been waited on yet. To ensure this invariant is
preserved, we don't expose the PIDs outside of the [Configurator]
module. *)letrunning_processes:(string*t,Process.With_pid.t)Hashtbl.t=Hashtbl.create0letget_process_with_pid~dirconfigurator=tryletp=Hashtbl.findrunning_processes(dir,configurator)inleti,_=Unix.waitpid[WNOHANG]p.pidinifi=0thenpelseletp=Process.start~dirconfiguratorinHashtbl.replacerunning_processes(dir,configurator)p;pwithNot_found->letp=Process.start~dirconfiguratorinHashtbl.addrunning_processes(dir,configurator)p;pletget_process_exn~dirconfigurator=letp=get_process_with_pid~dirconfiguratorinmatchUnix.waitpid[WNOHANG]p.pidwith|0,_->p.process|_->beginHashtbl.removerunning_processes(dir,configurator);raiseProcess_exitedendendletprepend_config~dir:cwdconfigurator(directives:directivelist)config=List.fold_left~init:(config,[])~f:(fun(config,errors)->function|`Bpath->({configwithbuild_path=path::config.build_path},errors)|`Spath->({configwithsource_path=path::config.source_path},errors)|`BHpath->({configwithhidden_build_path=path::config.hidden_build_path},errors)|`SHpath->({configwithhidden_source_path=path::config.hidden_source_path},errors)|`CMIpath->({configwithcmi_path=path::config.cmi_path},errors)|`CMTpath->({configwithcmt_path=path::config.cmt_path},errors)|`INDEXfile->({configwithindex_files=file::config.index_files},errors)|`EXTexts->({configwithextensions=exts@config.extensions},errors)|`SUFFIXsuffix->({configwithsuffixes=parse_suffixsuffix@config.suffixes},errors)|`FLGflags->letflags={workdir=cwd;workval=flags}in({configwithflags=flags::config.flags},errors)|`STDLIBpath->({configwithstdlib=Somepath},errors)|`SOURCE_ROOTpath->({configwithsource_root=Somepath},errors)|`UNIT_NAMEname->({configwithunit_name=Somename},errors)|`WRAPPING_PREFIXprefix->({configwithwrapping_prefix=Someprefix},errors)|`READERreader->({configwithreader},errors)|`EXCLUDE_QUERY_DIR->({configwithexclude_query_dir=true},errors)|`USE_PPX_CACHE->({configwithuse_ppx_cache=true},errors)|`ERROR_MSGstr->(config,str::errors)|`UNKNOWN_TAG_whenconfigurator=Configurator.Dune->(* For easier forward compatibility we ignore unknown configuration tags
when they are provided by dune *)(config,errors)|`UNKNOWN_TAGtag->leterror=Printf.sprintf"Unknown configuration tag \"%s\""tagin(config,error::errors))directivesletpostprocess_configconfig=letcleanlist=List.rev(List.filter_duplist)in{build_path=cleanconfig.build_path;source_path=cleanconfig.source_path;hidden_build_path=cleanconfig.hidden_build_path;hidden_source_path=cleanconfig.hidden_source_path;cmi_path=cleanconfig.cmi_path;cmt_path=cleanconfig.cmt_path;index_files=cleanconfig.index_files;extensions=cleanconfig.extensions;suffixes=cleanconfig.suffixes;flags=cleanconfig.flags;stdlib=config.stdlib;source_root=config.source_root;unit_name=config.unit_name;wrapping_prefix=config.wrapping_prefix;reader=config.reader;exclude_query_dir=config.exclude_query_dir;use_ppx_cache=config.use_ppx_cache}typecontext={workdir:string;configurator:Configurator.t;process_dir:string}exceptionEnd_of_inputletget_config{workdir;process_dir;configurator}path_abs=letlog_querypath=log~title:"get_config""Querying %s (inital cwd: %s) for file: %s.\nWorkdir: %s"(Configurator.to_stringconfigurator)process_dirpathworkdirinletquerypath(p:Configurator.Process.t)=letopenMerlin_dot_protocol.Blockinginlog_querypath;Commands.send_filep.stdinpath;flushp.stdin;readp.stdoutintryletp=Configurator.get_process_exn~dir:process_dirconfiguratorin(* Both [p.initial_cwd] and [path_abs] have gone through
[canonicalize_filename] *)letpath_rel=String.chop_prefix~prefix:p.initial_cwdpath_abs|>Option.map~f:(funpath->(* We need to remove the leading path separator after chopping.
There is one case where no separator is left: when [initial_cwd]
was the root of the filesystem *)ifString.lengthpath>0&&path.[0]=Filename.dir_sep.[0]thenString.drop1pathelsepath)inletpath=match(p.kind,path_rel)with|Dune,Somepath_rel->path_rel|_,_->path_absin(* Starting with Dune 2.8.3 relative paths are preferred. However to maintain
compatibility with 2.8 <= Dune <= 2.8.2 we always retry with an absolute
path if using a relative one failed *)letanswer=matchquerypathpwith|Ok[`ERROR_MSG_]whenp.kind=Dune->querypath_absp|answer->answerinmatchanswerwith|Okdirectives->letcfg,failures=prepend_config~dir:workdirconfiguratordirectivesempty_configin(postprocess_configcfg,failures)|Error(Merlin_dot_protocol.Unexpected_outputmsg)->(empty_config,[msg])|Error(Merlin_dot_protocol.Csexp_parse_error_)->raiseEnd_of_inputwith|Configurator.Process_exited->(* This can happen
- If `dot-merlin-reader` is not installed and the project use `.merlin`
files
- There was a bug in the external reader causing a crash *)letprogram_name=Lib_config.program_name()inleterror=Printf.sprintf"A problem occurred with %s external configuration reader. %s If the \
problem persists, please file an issue on %s's tracker."program_name(matchconfiguratorwith|Dot_merlin->"Check that `dot-merlin-reader` is installed."|Dune->"Check that `dune` is installed and up-to-date.")program_namein(empty_config,[error])|Unix.Unix_error(ENOENT,"create_process","dune")->leterror=Printf.sprintf"%s could not find `dune` in the PATH to get project configuration. If \
you do not rely on Dune, make sure `.merlin` files are present in the \
project's sources."(Lib_config.program_name())in(empty_config,[error])|Unix.Unix_error(ENOENT,"create_process","dot-merlin-reader")->leterror=Printf.sprintf"%s could not find `dot-merlin-reader` in the PATH. Please make sure \
that `dot-merlin-reader` is installed and in the PATH."(Lib_config.program_name())in(empty_config,[error])|End_of_input->(* This can happen
- if a project using old-dune has not been built and Merlin wrongly tries to
start `new-dune ocaml-merlin` in the absence of `.merlin` files
- the process stopped in the middle of its answer (which is very unlikely) *)letprogram_name=Lib_config.program_name()inleterror=Printf.sprintf"%s could not load its configuration from the external reader. %s"program_name(matchconfiguratorwith|Dot_merlin->"If the problem persists, please file an issue."|Dune->"Building your project with `dune` might solve this issue.")in(empty_config,[error])letfind_project_contextstart_dir=(* The workdir is the first directory we find which contains a [dune] file.
We need to keep track of this folder because [dune ocaml-merlin] might be
started from a folder that is a parent of the [workdir]. Thus we cannot
always use that starting folder as the workdir. *)letmap_workdirdir=function|Somedir->Somedir|None->letfnames=List.map~f:(Filename.concatdir)["dune";"dune-file"]inifList.exists~f:(funfname->Sys.file_existsfname&¬(Sys.is_directoryfname))fnamesthenSomedirelseNoneinletrecloopworkdirdir=trySome(List.find_map[".merlin";"dune-project";"dune-workspace"]~f:(funf->letfname=Filename.concatdirfinifSys.file_existsfname&¬(Sys.is_directoryfname)then(* When starting [dot-merlin-reader] from [dir]
the workdir is always [dir] *)letworkdir=iff=".merlin"thenNoneelseworkdirinletworkdir=Option.value~default:dirworkdirinSome({workdir;process_dir=dir;configurator=Option.get(Configurator.of_string_optf)},fname)elseNone))withNot_found->letparent=Filename.dirnamedirinifparent<>dirthen(* Was this directory the workdir ? *)letworkdir=map_workdirdirworkdirinloopworkdirparentelseNoneinloopNonestart_dir