Source file mconfig_dot.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
open Std
let { Logger.log } = Logger.for_section "Mconfig_dot"
type directive = Merlin_dot_protocol.directive
type config =
{ build_path : string list;
source_path : string list;
hidden_build_path : string list;
hidden_source_path : string list;
cmi_path : string list;
cmt_path : string list;
index_files : string list;
flags : string list with_workdir list;
extensions : string list;
suffixes : (string * string) list;
stdlib : string option;
source_root : string option;
unit_name : string option;
wrapping_prefix : string option;
reader : string list;
exclude_query_dir : bool;
use_ppx_cache : bool
}
let empty_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
}
let white_regexp = Str.regexp "[ \t]+"
let parse_suffix str =
let trimmed = String.trim str in
let split_on_white = Str.split white_regexp trimmed in
if List.length split_on_white != 2 then []
else
let first, second =
(List.nth split_on_white 0, List.nth split_on_white 1)
in
if String.get first 0 != '.' || String.get second 0 != '.' then []
else [ (first, second) ]
module Configurator : sig
type t = Dot_merlin | Dune
val of_string_opt : string -> t option
val to_string : t -> string
exception Process_exited
module Process : sig
type nonrec t =
{ kind : t;
initial_cwd : string;
stdin : out_channel;
stdout : in_channel;
stderr : in_channel
}
end
val get_process_exn : dir:string -> t -> Process.t
end = struct
type t = Dot_merlin | Dune
let of_string_opt = function
| ".merlin" -> Some Dot_merlin
| "dune-project" | "dune-workspace" -> Some Dune
| _ -> None
let to_string = function
| Dot_merlin -> "dot-merlin-reader"
| Dune -> "dune"
exception Process_exited
module Process = struct
type nonrec t =
{ kind : t;
initial_cwd : string;
stdin : out_channel;
stdout : in_channel;
stderr : in_channel
}
module With_pid = struct
type nonrec t = { pid : int; process : t }
end
let start ~dir cfg =
let prog, args =
match cfg with
| Dot_merlin ->
let prog = "dot-merlin-reader" in
(prog, [| prog |])
| Dune ->
let prog = "dune" in
(prog, [| prog; "ocaml-merlin"; "--no-print-directory" |])
in
let cwd = Sys.getcwd () in
let stdin_r, stdin_w = Unix.pipe () in
let stdout_r, stdout_w = Unix.pipe () in
let stderr_r, stderr_w = Unix.pipe () in
Unix.chdir dir;
Unix.set_close_on_exec stdin_w;
Os_ipc.merlin_dont_inherit_stdio true;
log ~title:"get_config" "Starting %s configuration provider from dir %s."
(to_string cfg) dir;
let pid =
let open Unix in
try create_process prog args stdin_r stdout_w stderr_w
with Unix_error _ as err ->
Os_ipc.merlin_dont_inherit_stdio false;
chdir cwd;
List.iter ~f:close
[ stdin_r; stdin_w; stdout_r; stdout_w; stderr_r; stderr_w ];
raise err
in
Os_ipc.merlin_dont_inherit_stdio false;
Unix.chdir cwd;
Unix.close stdin_r;
Unix.close stdout_w;
Unix.close stderr_w;
let stdin = Unix.out_channel_of_descr stdin_w in
let stdout = Unix.in_channel_of_descr stdout_r in
let stderr = Unix.in_channel_of_descr stderr_r in
let initial_cwd = Misc.canonicalize_filename dir in
With_pid.
{ pid; process = { kind = cfg; initial_cwd; stdin; stdout; stderr } }
end
let running_processes : (string * t, Process.With_pid.t) Hashtbl.t =
Hashtbl.create 0
let get_process_with_pid ~dir configurator =
try
let p = Hashtbl.find running_processes (dir, configurator) in
let i, _ = Unix.waitpid [ WNOHANG ] p.pid in
if i = 0 then p
else
let p = Process.start ~dir configurator in
Hashtbl.replace running_processes (dir, configurator) p;
p
with Not_found ->
let p = Process.start ~dir configurator in
Hashtbl.add running_processes (dir, configurator) p;
p
let get_process_exn ~dir configurator =
let p = get_process_with_pid ~dir configurator in
match Unix.waitpid [ WNOHANG ] p.pid with
| 0, _ -> p.process
| _ -> begin
Hashtbl.remove running_processes (dir, configurator);
raise Process_exited
end
end
let prepend_config ~dir:cwd configurator (directives : directive list) config =
List.fold_left ~init:(config, [])
~f:(fun (config, errors) -> function
| `B path ->
({ config with build_path = path :: config.build_path }, errors)
| `S path ->
({ config with source_path = path :: config.source_path }, errors)
| `BH path ->
( { config with hidden_build_path = path :: config.hidden_build_path },
errors )
| `SH path ->
( { config with hidden_source_path = path :: config.hidden_source_path },
errors )
| `CMI path -> ({ config with cmi_path = path :: config.cmi_path }, errors)
| `CMT path -> ({ config with cmt_path = path :: config.cmt_path }, errors)
| `INDEX file ->
({ config with index_files = file :: config.index_files }, errors)
| `EXT exts ->
({ config with extensions = exts @ config.extensions }, errors)
| `SUFFIX suffix ->
( { config with suffixes = parse_suffix suffix @ config.suffixes },
errors )
| `FLG flags ->
let flags = { workdir = cwd; workval = flags } in
({ config with flags = flags :: config.flags }, errors)
| `STDLIB path -> ({ config with stdlib = Some path }, errors)
| `SOURCE_ROOT path -> ({ config with source_root = Some path }, errors)
| `UNIT_NAME name -> ({ config with unit_name = Some name }, errors)
| `WRAPPING_PREFIX prefix ->
({ config with wrapping_prefix = Some prefix }, errors)
| `READER reader -> ({ config with reader }, errors)
| `EXCLUDE_QUERY_DIR -> ({ config with exclude_query_dir = true }, errors)
| `USE_PPX_CACHE -> ({ config with use_ppx_cache = true }, errors)
| `ERROR_MSG str -> (config, str :: errors)
| `UNKNOWN_TAG _ when configurator = Configurator.Dune ->
(config, errors)
| `UNKNOWN_TAG tag ->
let error = Printf.sprintf "Unknown configuration tag \"%s\"" tag in
(config, error :: errors))
directives
let postprocess_config config =
let clean list = List.rev (List.filter_dup list) in
{ build_path = clean config.build_path;
source_path = clean config.source_path;
hidden_build_path = clean config.hidden_build_path;
hidden_source_path = clean config.hidden_source_path;
cmi_path = clean config.cmi_path;
cmt_path = clean config.cmt_path;
index_files = clean config.index_files;
extensions = clean config.extensions;
suffixes = clean config.suffixes;
flags = clean config.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
}
type context =
{ workdir : string; configurator : Configurator.t; process_dir : string }
exception End_of_input
let get_config { workdir; process_dir; configurator } path_abs =
let log_query path =
log ~title:"get_config"
"Querying %s (inital cwd: %s) for file: %s.\nWorkdir: %s"
(Configurator.to_string configurator)
process_dir path workdir
in
let query path (p : Configurator.Process.t) =
let open Merlin_dot_protocol.Blocking in
log_query path;
Commands.send_file p.stdin path;
flush p.stdin;
read p.stdout
in
try
let p = Configurator.get_process_exn ~dir:process_dir configurator in
let path_rel =
String.chop_prefix ~prefix:p.initial_cwd path_abs
|> Option.map ~f:(fun path ->
if String.length path > 0 && path.[0] = Filename.dir_sep.[0] then
String.drop 1 path
else path)
in
let path =
match (p.kind, path_rel) with
| Dune, Some path_rel -> path_rel
| _, _ -> path_abs
in
let answer =
match query path p with
| Ok [ `ERROR_MSG _ ] when p.kind = Dune -> query path_abs p
| answer -> answer
in
match answer with
| Ok directives ->
let cfg, failures =
prepend_config ~dir:workdir configurator directives empty_config
in
(postprocess_config cfg, failures)
| Error (Merlin_dot_protocol.Unexpected_output msg) ->
(empty_config, [ msg ])
| Error (Merlin_dot_protocol.Csexp_parse_error _) -> raise End_of_input
with
| Configurator.Process_exited ->
let program_name = Lib_config.program_name () in
let error =
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
(match configurator with
| Dot_merlin -> "Check that `dot-merlin-reader` is installed."
| Dune -> "Check that `dune` is installed and up-to-date.")
program_name
in
(empty_config, [ error ])
| Unix.Unix_error (ENOENT, "create_process", "dune") ->
let error =
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") ->
let error =
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 ->
let program_name = Lib_config.program_name () in
let error =
Printf.sprintf
"%s could not load its configuration from the external reader. %s"
program_name
(match configurator with
| Dot_merlin -> "If the problem persists, please file an issue."
| Dune -> "Building your project with `dune` might solve this issue.")
in
(empty_config, [ error ])
let find_project_context start_dir =
let map_workdir dir = function
| Some dir -> Some dir
| None ->
let fnames = List.map ~f:(Filename.concat dir) [ "dune"; "dune-file" ] in
if
List.exists
~f:(fun fname ->
Sys.file_exists fname && not (Sys.is_directory fname))
fnames
then Some dir
else None
in
let rec loop workdir dir =
try
Some
(List.find_map [ ".merlin"; "dune-project"; "dune-workspace" ]
~f:(fun f ->
let fname = Filename.concat dir f in
if Sys.file_exists fname && not (Sys.is_directory fname) then
let workdir = if f = ".merlin" then None else workdir in
let workdir = Option.value ~default:dir workdir in
Some
( { workdir;
process_dir = dir;
configurator = Option.get (Configurator.of_string_opt f)
},
fname )
else None))
with Not_found ->
let parent = Filename.dirname dir in
if parent <> dir then
let workdir = map_workdir dir workdir in
loop workdir parent
else None
in
loop None start_dir