Repository navigation
Expand file tree
/
Copy pathrescript_compiler_driver.ml
More file actions
666 lines (631 loc) · 26.5 KB
/
Copy pathrescript_compiler_driver.ml
File metadata and controls
666 lines (631 loc) · 26.5 KB
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the Q Public License version 1.0. *)
(* *)
(***********************************************************************)
let absname_key = Request_local.new_key (fun () -> ref false)
let absname () = Domain.DLS.get absname_key
exception Request_exit of int
module Error_message_utils_support = struct
external to_comment : Res_comment.t -> Error_message_utils.Parser.comment
= "%identity"
external from_comment : Error_message_utils.Parser.comment -> Res_comment.t
= "%identity"
(* The parser hooks are installed once, before worker domains start. *)
let install_parser () =
(Error_message_utils.Parser.parse_source :=
fun source ->
let res =
Res_driver.parse_implementation_from_source
~display_filename:"<none>" ~source
in
(* Hints rewrite source text extracted at a location. Text that does
not parse cleanly (e.g. a location that leaves out the parentheses
around an operand) must not be turned into a suggestion. *)
if res.invalid then ([], [])
else (res.parsetree, res.comments |> List.map to_comment));
Error_message_utils.Parser.reprint_source :=
fun parsetree comments ->
Res_printer.print_implementation parsetree
~comments:(comments |> List.map from_comment)
~width:80
let setup () =
Error_message_utils.configured_jsx_module ()
:= Some
(match !((Js_config.current ()).jsx_module) with
| React -> "React"
| Generic {module_name} -> module_name)
end
let set_abs_input_name sourcefile =
let sourcefile =
if !(absname ()) && Filename.is_relative sourcefile then
Ext_path.absolute_cwd_path sourcefile
else sourcefile
in
Location.set_input_name sourcefile;
sourcefile
let setup_outcome_printer () = Lazy.force Res_outcome_printer.setup
let setup_runtime_path path = Runtime_package.set_path path
let process_file sourcefile ?kind ppf =
(* The input name must identify the source when writing the binary AST. *)
setup_outcome_printer ();
Error_message_utils_support.setup ();
let kind =
match kind with
| None ->
Ext_file_extensions.classify_input
(Ext_filename.get_extension_maybe sourcefile)
| Some kind -> kind
in
let res =
match kind with
| Res ->
let sourcefile = set_abs_input_name sourcefile in
Js_implementation.implementation
~parser:
(Res_driver.parse_implementation
~ignore_parse_errors:!((Clflags.current ()).ignore_parse_errors))
ppf sourcefile
| Resi ->
let sourcefile = set_abs_input_name sourcefile in
Js_implementation.interface
~parser:
(Res_driver.parse_interface
~ignore_parse_errors:!((Clflags.current ()).ignore_parse_errors))
ppf sourcefile
| Intf_ast -> Js_implementation.interface_mliast ppf sourcefile
(* The printer setup is done in the runtime depends on
the content of ast
*)
| Impl_ast -> Js_implementation.implementation_mlast ppf sourcefile
| Mlmap ->
Location.set_input_name sourcefile;
Js_implementation.implementation_map ppf sourcefile
| Cmi ->
let cmi_sign = (Cmi_format.read_cmi sourcefile).cmi_sign in
let output = Compiler_request_output.stdout_formatter () in
Printtyp.signature output cmi_sign;
Format.pp_print_newline output ()
| Unknown -> Bsc_args.bad_arg ("don't know what to do with " ^ sourcefile)
in
res
let reprint_source_file sourcefile =
let kind =
Ext_file_extensions.classify_input
(Ext_filename.get_extension_maybe sourcefile)
in
let sourcefile = set_abs_input_name sourcefile in
let res =
match kind with
| Res ->
let parse_result =
Res_driver.parsing_engine.parse_implementation ~filename:sourcefile
in
if parse_result.invalid then (
Res_diagnostics.print_report parse_result.diagnostics
parse_result.source;
raise_notrace (Request_exit 1));
Res_compmisc.init_path ();
parse_result.parsetree
|> Cmd_ppx_apply.apply_rewriters ~tool_name:Js_config.tool_name Ml
|> Ppx_entry.rewrite_implementation
|> Res_printer.print_implementation ~width:100
~comments:parse_result.comments
|> Compiler_request_output.print_stdout
| Resi ->
let parse_result =
Res_driver.parsing_engine.parse_interface ~filename:sourcefile
in
if parse_result.invalid then (
Res_diagnostics.print_report parse_result.diagnostics
parse_result.source;
raise_notrace (Request_exit 1));
Res_compmisc.init_path ();
parse_result.parsetree
|> Cmd_ppx_apply.apply_rewriters ~tool_name:Js_config.tool_name Mli
|> Ppx_entry.rewrite_signature
|> Res_printer.print_interface ~width:100 ~comments:parse_result.comments
|> Compiler_request_output.print_stdout
| _ ->
Compiler_request_output.print_stdout
("Invalid input for reprinting ReScript source. Must be a ReScript \
file: " ^ sourcefile);
raise_notrace (Request_exit 2)
in
res
let usage = "Usage: bsc <options> <files>\nOptions are:"
let ppf () = Compiler_request_output.stderr_formatter ()
(* Error messages to standard error formatter *)
let anonymous ~(rev_args : string list) =
match rev_args with
| [filename] -> process_file filename (ppf ())
| [] -> ()
| _ ->
if !((Js_config.current ()).syntax_only) then
Ext_list.rev_iter rev_args (fun filename ->
Clflags.reset_dump_state ();
Warnings.reset ();
process_file filename (ppf ()))
else Bsc_args.bad_arg "can not handle multiple files"
(* Immediate actions of the command line write files: a request started
early waits for the build system first. *)
let format_file input =
Compiler_request_state.before_effect ();
let ext =
Ext_file_extensions.classify_input (Ext_filename.get_extension_maybe input)
in
(match ext with
| Res | Resi -> ()
| _ -> Bsc_args.bad_arg ("don't know what to do with " ^ input));
let formatted =
Res_multi_printer.print
~ignore_parse_errors:!((Clflags.current ()).ignore_parse_errors)
input
in
match !((Clflags.current ()).output_name) with
| None -> Compiler_request_output.write_stdout_binary formatted
| Some fname -> Ext_io.write_file fname formatted
let set_color_option option =
match Clflags.parse_color_setting option with
| None -> ()
| Some setting -> (Clflags.current ()).color := Some setting
(* The temporary file is made absolute: a relative temporary directory names a
directory under the process's working directory, while a request resolves
relative paths against its own. *)
let eval (s : string) ~suffix =
Compiler_request_state.before_effect ();
let tmpfile = Filename.temp_file "eval" suffix in
let tmpfile =
if Filename.is_relative tmpfile then Filename.concat (Sys.getcwd ()) tmpfile
else tmpfile
in
Fun.protect
~finally:(fun () ->
if not !((Clflags.current ()).verbose) then
try Sys.remove tmpfile with _ -> ())
(fun () ->
Ext_io.write_file tmpfile s;
anonymous ~rev_args:[tmpfile])
(* let (//) = Filename.concat *)
let bs_version_string = "ReScript " ^ Bs_version.version
let print_version_string () =
Compiler_request_output.print_stdout bs_version_string;
raise_notrace (Request_exit 0)
let[@inline] set s : Bsc_args.spec = Unit (Unit_set s)
let[@inline] clear s : Bsc_args.spec = Unit (Unit_clear s)
let[@inline] string_call s : Bsc_args.spec = String (String_call s)
let[@inline] string_optional_set s : Bsc_args.spec =
String (String_optional_set s)
let[@inline] unit_call s : Bsc_args.spec = Unit (Unit_call s)
let[@inline] string_list_add s : Bsc_args.spec = String (String_list_add s)
let parse_source_map value =
(Js_config.current ()).source_map :=
match String.lowercase_ascii value with
| "linked" -> Linked
| "inline" -> Inline
| "hidden" -> Hidden
| "false" | "none" -> No_source_map
| value ->
Bsc_args.bad_arg
("Unsupported sourceMap value: " ^ value
^ ". Expected linked, inline, hidden, false, or none")
let parse_bool_ref target value =
target :=
match String.lowercase_ascii value with
| "true" -> true
| "false" -> false
| value -> Bsc_args.bad_arg ("Expected true or false, got: " ^ value)
(* mostly common used to list in the beginning to make search fast
*)
let command_line_flags () : (string * Bsc_args.spec * string) array =
[|
( "-I",
string_list_add (Clflags.current ()).include_dirs,
"*internal* <dir> Add <dir> to the list of include directories" );
( "-w",
string_call (Warnings.parse_options false),
"<list> Enable or disable warnings according to <list>:\n\
+<spec> enable warnings in <spec>\n\
-<spec> disable warnings in <spec>\n\
@<spec> enable warnings in <spec> and treat them as errors\n\
<spec> can be:\n\
<num> a single warning number\n\
<num1>..<num2> a range of consecutive warning numbers\n\
default setting is " ^ Bsc_warnings.defaults_w );
( "-o",
string_optional_set (Clflags.current ()).output_name,
"*internal* <file> set output file name to <file>" );
( "-bs-read-cmi",
unit_call (fun _ -> (Clflags.current ()).assume_no_mli := Mli_exists),
"*internal* Assume mli always exist " );
( "-ppx",
string_list_add (Clflags.current ()).all_ppx,
"*internal* <command> Pipe abstract syntax trees through preprocessor \
<command>" );
( "-open",
string_list_add (Clflags.current ()).open_modules,
"*internal* <module> Opens the module <module> before typing" );
( "-bs-jsx",
string_call (fun i ->
if i <> "4" then Bsc_args.bad_arg ("Unsupported jsx version: " ^ i);
(Js_config.current ()).jsx_version :=
Js_config.jsx_version_of_int @@ int_of_string i),
"*internal* Set jsx version" );
( "-bs-jsx-module",
string_call (fun i ->
let is_generic =
match i |> String.lowercase_ascii with
| "react" -> false
| _ -> true
in
(Js_config.current ()).jsx_module := Js_config.jsx_module_of_string i;
if is_generic then (Js_config.current ()).jsx_version := Some Jsx_v4),
"*internal* Set jsx module" );
( "-bs-jsx-mode",
string_call ignore,
"*internal* Set jsx mode, this is no longer used and is a no-op." );
( "-bs-jsx-preserve",
set (Clflags.current ()).jsx_preserve,
"*internal* Preserve jsx" );
( "-bs-source-map",
string_call parse_source_map,
"*internal* Configure source map output" );
( "-bs-source-map-sources-content",
string_call
(parse_bool_ref (Js_config.current ()).source_map_sources_content),
"*internal* Include original source text in source maps" );
( "-bs-source-map-root",
string_call (fun value -> (Js_config.current ()).source_map_root := value),
"*internal* Set sourceRoot in source maps" );
( "-bs-package-output",
string_call Js_packages_state.update_npm_package_path,
"*internal* Set npm-output-path: [opt_module]:path, for example: \
'lib/cjs', 'amdjs:lib/amdjs', 'es6:lib/es6' " );
( "-bs-project-root",
string_call (fun s ->
(* Writers open paths under the root without resolving them against
the request's working directory, so make it absolute here. *)
let root = Ext_path.absolute_cwd_path s in
Ext_path.set_project_root root;
Gentype_config.project_root () := root),
"*internal* Set the project root directory" );
( "-bs-ast",
unit_call (fun _ ->
(Js_config.current ()).binary_ast := true;
(Js_config.current ()).syntax_only := true),
"*internal* Generate binary .mli_ast and ml_ast and stop" );
( "-bs-test-ast-conversion",
set (Js_config.current ()).test_ast_conversion,
"*internal* Roundtrip the parsed AST through Parsetree0 before continuing"
);
( "-bs-syntax-only",
set (Js_config.current ()).syntax_only,
"*internal* Only check syntax" );
("-bs-g", set (Js_config.current ()).debug, "Debug mode");
( "-bs-package-name",
string_call Js_packages_state.set_package_name,
"*internal* Set package name, useful when you want to produce npm \
packages" );
( "-bs-ns",
string_call Js_packages_state.set_package_map,
"*internal* Set package map, not only set package name but also use it \
as a namespace" );
( "-as-pp",
unit_call (fun _ ->
(Js_config.current ()).as_pp := true;
(Js_config.current ()).syntax_only := true),
"*internal*As pp to interact with native tools" );
( "-no-alias-deps",
set (Clflags.current ()).transparent_modules,
"*internal*Do not record dependencies for module aliases" );
( "-bs-gentype",
set (Clflags.current ()).bs_gentype,
"*internal* Pass gentype command" );
( "-bs-gentype-module",
string_call (fun s ->
Gentype_config.module_flag () := Gentype_config.module_of_string s),
"*internal* Set gentype module system: commonjs|esmodule" );
( "-bs-gentype-module-resolution",
string_call (fun s ->
Gentype_config.module_resolution_flag ()
:= Gentype_config.module_resolution_of_string s),
"*internal* Set gentype module resolution strategy: node|node16|bundler"
);
( "-bs-gentype-export-interfaces",
set (Gentype_config.export_interfaces_flag ()),
"*internal* Emit gentype interface files" );
( "-bs-gentype-generated-extension",
string_call (fun s ->
Gentype_config.generated_file_extension_flag () := Some s),
"*internal* Set gentype generated-file extension (e.g. .gen.tsx)" );
( "-bs-gentype-suffix",
string_call (fun s -> Gentype_config.suffix_flag () := Some s),
"*internal* Set gentype import-path suffix (e.g. .bs.js, .mjs)" );
( "-bs-gentype-shim",
string_call Gentype_config.add_shim,
"*internal* Register a gentype shim mapping: From=To (repeatable)" );
( "-bs-gentype-debug",
string_call Debug.set_item,
"*internal* Enable a gentype debug category (repeatable): \
all|basic|codeItems|config|converter|dependencies|moduleResolution|notImplemented|translation|typeEnv|typeResolution"
);
( "-bs-gentype-dep",
string_call Gentype_config.add_bs_dependency,
"*internal* Register a gentype bsb dependency (repeatable)" );
( "-bs-gentype-source-dir",
string_call Gentype_config.add_source_dir,
"*internal* Register a gentype source directory relative to the project \
root (repeatable)" );
( "-bs-gentype-dep-path",
string_call Gentype_config.add_dep_path,
"*internal* Register a gentype dependency install path: \
<name>=<absolute-path> (repeatable)" );
( "-bs-gentype-bsb-project-root",
string_call (fun s -> Gentype_config.bsb_project_root () := s),
"*internal* Set gentype bsb project root (workspace root containing \
.sourcedirs.json)" );
(******************************************************************************)
( "-nostdlib",
set (Js_config.current ()).no_stdlib,
"*internal* Don't use stdlib" );
( "-color",
string_call set_color_option,
"*internal* Enable or disable colors in compiler messages\n\
The following settings are supported:\n\
auto use heuristics to enable colors only if supported\n\
always enable colors\n\
never disable colors\n\
The default setting is 'always'\n\
The current heuristic for 'auto'\n\
checks that the TERM environment variable exists and is\n\
not empty or \"dumb\", and that isatty(stderr) holds." );
( "-e",
string_call (fun s -> eval s ~suffix:Literals.suffix_res),
"(experimental) set the string to be evaluated in ReScript syntax" );
( "-bs-cmi-only",
set (Js_config.current ()).cmi_only,
"*internal* Stop after generating cmi file" );
( "-bs-cmi",
set (Js_config.current ()).force_cmi,
"*internal* Not using cached cmi, always generate cmi" );
( "-bs-cmj",
set (Js_config.current ()).force_cmj,
"*internal* Not using cached cmj, always generate cmj" );
( "-bs-no-version-header",
set (Js_config.current ()).no_version_header,
"*internal*Don't print version header" );
( "-bs-no-builtin-ppx",
set (Js_config.current ()).no_builtin_ppx,
"*internal* Disable built-in ppx" );
( "-bs-cross-module-opt",
set (Js_config.current ()).cross_module_inline,
"*internal* Enable cross module inlining(experimental), default(false)" );
( "-bs-no-cross-module-opt",
clear (Js_config.current ()).cross_module_inline,
"*internal* Disable cross module inlining(experimental)" );
( "-debug-ir",
set (Js_config.current ()).debug_ir,
"*internal* Dump compiler IR and enable Lambda invariant checks" );
( "-check-lam",
set (Js_config.current ()).check_lam,
"*internal* Check Lambda invariants after optimization passes" );
( "-bs-no-check-div-by-zero",
clear (Js_config.current ()).check_div_by_zero,
"*internal* unsafe mode, don't check div by zero and mod by zero" );
( "-bs-noassertfalse",
set (Clflags.current ()).no_assert_false,
"*internal* no code for assert false" );
( "-noassert",
set (Clflags.current ()).noassert,
"*internal* Do not compile assertion checks" );
( "-bs-loc",
set (Clflags.current ()).dump_location,
"*internal* dont display location with -dtypedtree, -dparsetree" );
( "-dtypedtree",
set (Clflags.current ()).dump_typedtree,
"*internal* debug typedtree" );
( "-dparsetree",
set (Clflags.current ()).dump_parsetree,
"*internal* debug parsetree" );
( "-drawlambda",
set (Clflags.current ()).dump_rawlambda,
"*internal* debug raw lambda" );
( "-draw-coercions",
set (Clflags.current ()).dump_coercions,
"*internal* debug module coercions with raw internal types" );
("-dsource", set (Clflags.current ()).dump_source, "*internal* print source");
( "-reprint-source",
string_call reprint_source_file,
"*internal* transform the target ReScript file using PPXes provided, and \
print the transformed ReScript code to stdout" );
("-format", string_call format_file, "*internal* Format as Res syntax");
( "-only-parse",
set (Clflags.current ()).only_parse,
"*internal* stop after parsing" );
( "-editor-mode",
unit_call (fun () ->
(Clflags.current ()).ignore_parse_errors := true;
(Js_config.current ()).cmi_only := true),
"*internal* Enable editor mode." );
( "-ignore-parse-errors",
set (Clflags.current ()).ignore_parse_errors,
"*internal* continue after parse errors" );
( "-verbose",
set (Clflags.current ()).verbose,
"*internal* Print calls to external commands" );
( "-keep-locs",
set (Clflags.current ()).keep_locs,
"*internal* Keep locations in .cmi files" );
( "-no-keep-locs",
clear (Clflags.current ()).keep_locs,
"*internal* Do not keep locations in .cmi files" );
("-nopervasives", set (Clflags.current ()).nopervasives, "*internal*");
( "-v",
unit_call print_version_string,
"Print compiler version and location of standard library and exit" );
("-version", unit_call print_version_string, "Print version and exit");
( "-absname",
set (absname ()),
"*internal* Show absolute filenames in error messages" );
( "-enable-experimental",
string_call Experimental_features.enable_from_string,
"Enable experimental features: repeatable, e.g. -enable-experimental \
LetUnwrap" );
(* Not used, the build system did the expansion *)
( "-bs-no-bin-annot",
clear (Clflags.current ()).binary_annotations,
"*internal* Disable binary annotations (by default on)" );
( "-short-paths",
clear (Clflags.current ()).real_paths,
"*internal* Shorten paths in types" );
("-unsafe", Unit_dummy, "*internal* No longer used and is a no-op.");
( "-runtime-path",
string_call setup_runtime_path,
"*internal* Set the path of the runtime package (@rescript/runtime)" );
( "-warn-help",
unit_call (fun () ->
Warnings.help_warnings ();
raise_notrace (Request_exit 0)),
"Show description of warning numbers" );
( "-warn-error",
string_call (Warnings.parse_options true),
"<list> Enable or disable error status for warnings according\n\
to <list>. See option -w for the syntax of <list>.\n\
Default setting is " ^ Bsc_warnings.defaults_warn_error );
( "-make-runtime",
unit_call Js_packages_state.make_runtime,
"*internal* make runtime library" );
|]
(** parse flags in config *)
let file_level_flags_handler (e : Parsetree.expression option) =
match e with
| None -> ()
| Some {pexp_desc = Pexp_array args; pexp_loc} -> (
let args =
Array.of_list
(Ext_list.map args (fun e ->
match Ast_payload.semantic_string_of_expression e with
| Some name -> name
| _ ->
Location.raise_errorf ~loc:e.pexp_loc "string literal expected"))
in
try
Bsc_args.parse_exn ~start:0 ~argv:args (command_line_flags ())
(fun ~rev_args:_ -> ())
~usage
with _ ->
Location.prerr_warning pexp_loc (Preprocessor "invalid flags for bsc"))
| Some e -> Location.raise_errorf ~loc:e.pexp_loc "string array expected"
(* These shared hooks are installed when the driver module loads, before any
request can start on another domain. Concurrent Lazy.force calls would race
on a first request. *)
let () =
Bs_conditional_initial.setup_env ();
setup_outcome_printer ();
Error_message_utils_support.install_parser ();
let flags = "flags" in
Ast_config.add_structure flags file_level_flags_handler;
Ast_config.add_signature flags file_level_flags_handler;
Ident.capture_request_baseline ()
type result = {exit_code: int; stdout: string; stderr: string}
let build_identity = Rescript_compiler_build_identity.value
(* Request_local gives every request the state of a new compiler process.
On top of that, a request needs bsc's own defaults, and allocates the shared
predefined type graphs in a fixed order: lazy first use on different worker
domains would otherwise shift serialized type IDs. *)
let start_request () =
Clflags.reset ();
Predef.reset_for_request ();
Env.reset_initial_for_request ()
(* Interfaces that this domain keeps for later requests must not keep this
request's memoized abbreviations, so they are reset while the request's
memo list is still current. A failed request may also have stopped with
some of their types marked, so the domain drops them. *)
let leave_cached_interfaces_clean action =
match action () with
| result ->
Btype.cleanup_abbrev ();
if result.exit_code <> 0 then Bs_cmi_load.discard_cached_cmis ();
result
| exception exn ->
Btype.cleanup_abbrev ();
Bs_cmi_load.discard_cached_cmis ();
raise exn
let with_fresh_request_states ?hooks ~cwd action =
Predef.with_fresh (fun () ->
Env.with_fresh_initial (fun () ->
Ident.with_fresh (fun () ->
Request_local.with_fresh (fun () ->
Compiler_request_state.with_fresh ~cwd ?hooks (fun () ->
leave_cached_interfaces_clean action)))))
let run_argv ?run_external ?hooks ~capture ~cwd argv =
with_fresh_request_states ?hooks ~cwd (fun () ->
start_request ();
Cmt_format.set_args argv;
let execute () =
try
Bsc_args.parse_exn ~argv (command_line_flags ()) anonymous ~usage;
0
with
| Request_exit code -> code
| Bsc_args.Help message ->
Compiler_request_output.write_stdout message;
0
| Res_driver.Already_reported -> 1
| Bsc_args.Bad msg ->
Format.fprintf (ppf ()) "%s@." msg;
2
| x ->
Location.report_exception (ppf ()) x;
2
in
let run_with_external_owner action =
match run_external with
| None -> action ()
| Some run_external ->
Ccomp.with_command_runner
(fun command ->
let status, stdout, stderr = run_external command in
Compiler_request_output.write_stdout stdout;
(* Written past the formatter, which would count the PPX's
output as the current column and indent later errors. *)
Format.pp_print_flush (ppf ()) ();
Compiler_request_output.write_stderr stderr;
status)
action
in
if capture then
let exit_code, stdout, stderr =
Compiler_request_output.with_capture (fun () ->
Misc.Color.set_color_tag_handling
(Compiler_request_output.stdout_formatter ());
Misc.Color.set_color_tag_handling
(Compiler_request_output.stderr_formatter ());
run_with_external_owner execute)
in
{exit_code; stdout; stderr}
else
(* A bsc process streams to its own stdout and stderr. *)
let exit_code =
Fun.protect
(fun () -> run_with_external_owner execute)
~finally:(fun () ->
Format.pp_print_flush Format.std_formatter ();
Format.pp_print_flush Format.err_formatter ();
flush stdout;
flush stderr)
in
{exit_code; stdout = ""; stderr = ""})
let run_request_with_hooks ~hooks ~run_external ~cwd ~argv ~input =
let logical_argv = Array.of_list ("bsc" :: (argv @ [input])) in
run_argv ?run_external ~hooks ~capture:true ~cwd logical_argv
let run_request ~run_external ~cwd ~argv ~input =
run_request_with_hooks ~hooks:Compiler_request_state.no_hooks ~run_external
~cwd ~argv ~input
let run argv = (run_argv ~capture:false ~cwd:(Sys.getcwd ()) argv).exit_code