/
b0_ocaml.ml
1969 lines (1782 loc) · 71.6 KB
/
b0_ocaml.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
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*---------------------------------------------------------------------------
Copyright (c) 2019 The b0 programmers. All rights reserved.
SPDX-License-Identifier: ISC
---------------------------------------------------------------------------*)
open B0_std
open Fut.Syntax
let add_if c v l = if c then v :: l else l
let () = B0_def.Scope.open_lib "ocaml"
module Tool = struct
(* Compilers *)
let comp_env_vars =
[ "CAMLLIB"; "CAMLSIGPIPE"; "CAML_DEBUG_FILE"; "CAML_DEBUG_SOCKET";
"CAML_LD_LIBRARY_PATH"; "BUILD_PATH_PREFIX_MAP"; "OCAMLDEBUG"; "OCAMLLIB";
"OCAMLPROF_DUMP"; "OCAMLRUNPARAM"; "OCAML_COLOR"; "OCAML_FLEXLINK";
"OCAML_INSTR_FILE"; "OCAML_INSTR_START"; "OCAML_INSTR_STOP";
"OCAML_SPACETIME_INTERVAL"; "OCAML_SPACETIME_SNAPSHOT_DIR"; "PATH";
"TERM"; "__AFL_SHM_ID";
(* XXX For cc for now we add them in bulk but we could make
them depend on the conffiguration. *)
"LD_LIBRARY_PATH"; "LIBRARY_PATH"; "C_INCLUDE_PATH";
(* XXX These are Windows specific and needed by cl.exe *)
"SystemRoot"; "INCLUDE"; "LIB"; ]
let ocamlc = B0_memo.Tool.by_name ~vars:comp_env_vars "ocamlc"
let ocamlopt = B0_memo.Tool.by_name ~vars:comp_env_vars "ocamlopt"
let ocamldep = B0_memo.Tool.by_name ~vars:comp_env_vars "ocamldep"
let ocamlmklib =
B0_memo.Tool.by_name ~vars:("OCAML_FLEXLINK" :: comp_env_vars) "ocamlmklib"
let ocamlobjinfo = B0_memo.Tool.by_name ~vars:comp_env_vars "ocamlobjinfo"
(* Toplevels *)
let top_env_vars =
[ "CAML_LD_LIBRARY_PATH"; "CAMLRUNPARAM";
"OCAMLTOP_INCLUDE_PATH";
"HOME"; "OCAMLLIB"; "OCAMLRUN_PARAM"; "OCAMLTOP_UTF_8"; "PATH"; "TERM"; ]
let ocaml = B0_memo.Tool.by_name ~vars:top_env_vars "ocaml"
let ocamlnat = B0_memo.Tool.by_name ~vars:top_env_vars "ocamlnat"
end
module Code = struct
type t = [ `Byte | `Native ]
type built = [ `Byte | `Native | `All ]
let pp ppf = function
| `Byte -> Fmt.string ppf "byte"
| `Native -> Fmt.string ppf "native"
let pp_built ppf = function #t as v -> pp ppf v | `All -> Fmt.string ppf "all"
let needs =
let doc = "Needed built code" in
let pp_value = pp_built in
B0_meta.Key.make "ocaml-code-needed" ~doc ~pp_value
let supported =
let doc = "Supported built code" in
let pp_value = pp_built in
B0_meta.Key.make "ocaml-supported-code" ~default:`All ~doc ~pp_value
let needed store memo =
let find_need u acc =
let need = B0_unit.find_meta needs u in
match acc, need with
| need, None | None, need -> need
| Some `Byte, Some `Byte -> acc (* jsoo use case *)
| Some `All, _ -> acc | _, Some `All -> acc
| Some `Byte, Some `Native -> Some `All
| Some `Native, Some `Native -> acc
| Some `Native, Some `Byte -> Some `All
in
let* build = B0_store.get store B0_build.self in
Fut.return (B0_unit.Set.fold find_need (B0_build.may_build build) None)
let wanted = B0_store.key (fun _ _ -> Fut.return `Auto)
let built =
let of_wanted_code s m = function
| #built as v -> Fut.return v
| `Auto ->
let* need = needed s m in
match need with
| Some need -> Fut.return need
| None ->
let* ocamlopt = B0_memo.tool_opt m Tool.ocamlopt in
Fut.return @@ if Option.is_some ocamlopt then `Native else `Byte
in
let det store memo =
let* wanted = B0_store.get store wanted in
of_wanted_code store memo wanted
in
B0_store.key det
end
module Conf = struct
type t =
{ fields : string String.Map.t;
version : int * int * int * string option;
where : Fpath.t;
asm_ext : string;
dll_ext : string;
exe_ext : string;
lib_ext : string;
obj_ext : string;
has_dynlink : bool; }
let find k c = String.Map.find_opt k c.fields
let version c = c.version
let where c = c.where
let asm_ext c = c.asm_ext
let exe_ext c = c.exe_ext
let dll_ext c = c.dll_ext
let lib_ext c = c.lib_ext
let obj_ext c = c.obj_ext
let has_dynlink c = c.has_dynlink
let to_string_map c = c.fields
let of_string_map fields = try
let err = Fmt.failwith in
let err_key k = err "key %a not found." Fmt.(code string) k in
let find k fs = match String.Map.find_opt k fs with
| None -> err_key k | Some v -> v
in
let version =
let v = find "version" fields in
match String.to_version v with
| None -> err "could not parse version string %S" v
| Some v -> v
in
let where = Fpath.of_string (find "standard_library" fields) in
let where = where |> Result.error_to_failure in
let asm_ext = find "ext_asm" fields in
let dll_ext = find "ext_dll" fields in
let exe_ext = find "ext_exe" fields in
let lib_ext = find "ext_lib" fields in
let obj_ext = find "ext_obj" fields in
let has_dynlink =
let k = "supports_shared_libraries" in
let s = find k fields in
match bool_of_string_opt s with
| None -> err "key %a cound not parse bool from %S" Fmt.(code string) k s
| Some b -> b
in
Ok { fields; version; where; asm_ext; dll_ext; exe_ext; lib_ext; obj_ext;
has_dynlink; }
with
| Failure e -> Error e
(* IO *)
let of_string ?file s =
let parse_line _ acc l = match String.cut_left ~sep:":" l with
| None -> acc (* XXX report an error *)
| Some (k, v) -> String.Map.add (String.trim k) (String.trim v) acc
in
try
let s = String.trim s and strip_newlines = true in
let fields =
String.fold_ascii_lines ~strip_newlines parse_line String.Map.empty s
in
Ok (of_string_map fields |> Result.error_to_failure)
with Failure e -> Fpath.error ?file " OCaml config: %s" e
let write m ~comp ~o =
let comp = B0_memo.tool m comp in
B0_memo.spawn m ~writes:[o] ~stdout:(`File o) @@
comp (Cmd.arg "-config")
let read m file =
let* s = B0_memo.read m file in
Fut.return (of_string ~file s |> B0_memo.fail_if_error m)
let key : t B0_store.key =
let conf_comp s m =
let of_built_code = function
| `Native | `All -> Tool.ocamlopt | `Byte -> Tool.ocamlc
in
Fut.map of_built_code (B0_store.get s Code.built)
in
let det s m =
let* comp = conf_comp s m in
let file = Fpath.(B0_store.dir s / B0_memo.mark m) in
write m ~comp ~o:file;
read m file
in
B0_store.key ~mark:"ocaml.conf" det
let version' build = Fut.map version (B0_build.get build key)
end
(* Modules *)
module Modname = struct
type t = string
let of_filename f = String.Ascii.capitalize (Fpath.basename ~no_ext:true f)
let v n = String.Ascii.capitalize n
let equal = String.equal
let compare = String.compare
let pp = Fmt.tty' [`Bold]
module Set = String.Set
module Map = String.Map
(* Filename mangling *)
let of_mangled_filename s =
let rem_ocaml_ext s = match String.cut_right ~sep:"." s with
| None -> s | Some (s, ("ml" | ".mli")) -> s | Some _ -> s
in
let mangle s =
let char_len = function
| '-' | '.' | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '\'' -> 1
| _ -> 2
in
let set_char b i c = match c with
| '.' | '-' -> Bytes.set b i '_'; i + 1
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '\'' as c ->
Bytes.set b i c; i + 1
| c ->
let c = Char.code c in
Bytes.set b (i ) (Char.Ascii.upper_hex_digit (c lsr 4));
Bytes.set b (i + 1) (Char.Ascii.upper_hex_digit (c ));
i + 2
in
String.byte_replacer char_len set_char s
in
let s = mangle (rem_ocaml_ext s) in
let s = match String.head s with
| Some c when Char.Ascii.is_letter c -> s
| None | Some _ -> "M" ^ s
in
String.Ascii.capitalize s
end
module Modref = struct
type t = Modname.t * Digest.t
let make n d = (String.Ascii.capitalize n, d)
let name = fst
let digest = snd
let equal (_, d0) (_, d1) = Digest.equal d0 d1
let compare (n0, d0) (n1, d1) = match Modname.compare n0 n1 with
| 0 -> Digest.compare d0 d1
| c -> c
let pp ppf (n, d) = Fmt.pf ppf "@[%s %a@]" (Digest.to_hex d) Modname.pp n
module T = struct type nonrec t = t let compare = compare end
module Set = struct
include Set.Make (T)
let dump ppf rs =
Fmt.pf ppf "@[<1>{%a}@]" (Fmt.iter ~sep:Fmt.comma iter pp) rs
let pp ?sep pp_elt = Fmt.iter ?sep iter pp_elt
end
module Map = struct
include Map.Make (T)
let dom m = fold (fun k _ acc -> Set.add k acc) m Set.empty
let of_list bs = List.fold_left (fun m (k,v) -> add k v m) empty bs
let add_to_list k v m = match find k m with
| exception Not_found -> add k [v] m
| l -> add k (v :: l) m
let add_to_set
(type set) (type elt)
(module S : Stdlib.Set.S with type elt = elt and type t = set)
k v m = match find k m with
| exception Not_found -> add k (S.singleton v) m
| set -> add k (S.add v set) m
let dump pp_v ppf m =
let pp_binding ppf (k, v) =
Fmt.pf ppf "@[<1>(@[%a@],@ @[%a@])@]" pp k pp_v v
in
Fmt.pf ppf "@[<1>{%a}@]"
(Fmt.iter_bindings ~sep:Fmt.sp iter pp_binding) m
let pp ?sep pp_binding = Fmt.iter_bindings ?sep iter pp_binding
end
end
module Modsrc = struct
module Deps = struct
let of_string ?(file = Fpath.dash) ?src_root s =
(* Parse ocamldep's [-slash -modules], a bit annoying to parse.
ocamldep shows its Makefile legacy. *)
let parse_path n p = (* ocamldep escapes spaces as "\ ", a bit annoying *)
let char_len_at s i = match s.[i] with
| '\\' when i + 1 < String.length s && s.[i+1] = ' ' -> 2
| _ -> 1
in
let set_char b k s i = match char_len_at s i with
| 2 -> Bytes.set b k ' '; 2
| 1 -> Bytes.set b k s.[i]; 1
| _ -> assert false
in
match String.byte_unescaper char_len_at set_char p with
| Error j -> Fmt.failwith_line n "%d: illegal escape" j
| Ok p ->
match Fpath.of_string p with
| Error e -> Fmt.failwith_line n " %s" e
| Ok p -> p
in
let parse_line ~src_root n acc line =
if line = "" then acc else
match String.cut_right (* right, windows drives *) ~sep:":" line with
| None -> Fmt.failwith_line n " cannot parse line: %S" line
| Some (file, mods) ->
let file = parse_path n file in
let file = match src_root with
| None -> file
| Some src_root -> Fpath.(src_root // file)
in
let add_mod acc m = Modname.Set.add m acc in
let mods = String.cuts_left ~drop_empty:true ~sep:" " mods in
let start = Modname.Set.singleton "Stdlib" in
let mods = List.fold_left add_mod start mods in
Fpath.Map.add file mods acc
in
try
let strip_newlines = true and parse = parse_line ~src_root in
Ok (String.fold_ascii_lines ~strip_newlines parse Fpath.Map.empty s)
with
| Failure e -> Fpath.error ~file "%s" e
let write ?src_root m ~srcs ~o =
let ocamldep = B0_memo.tool m Tool.ocamldep in
let srcs', cwd = match src_root with
| None -> srcs, None
| Some root ->
(* XXX unfortunately this doesn't report parse error
at the right place. So we don't do anything for now
the output thus depends on the path location and can't
be cached across machines.
let rem_prefix src = Fpath.rem_prefix root src |> Option.get in
List.map rem_prefix srcs, Some root
*)
srcs, None
in
B0_memo.spawn m ?cwd ~reads:srcs ~writes:[o] ~stdout:(`File o) @@
ocamldep Cmd.(arg "-slash" % "-modules" %% paths srcs')
let read ?src_root m file =
let* s = B0_memo.read m file in
Fut.return (of_string ?src_root ~file s |> B0_memo.fail_if_error m)
end
type t =
{ modname : Modname.t;
opaque : bool;
mli : Fpath.t option;
mli_deps : Modname.Set.t;
ml : Fpath.t option;
ml_deps : Modname.Set.t;
build_dir : Fpath.t;
build_base : Fpath.t }
let make ~modname ~opaque ~mli ~mli_deps ~ml ~ml_deps ~build_dir =
let build_base = Fpath.(build_dir / String.Ascii.uncapitalize modname) in
{ modname; opaque; mli; mli_deps; ml; ml_deps; build_dir; build_base }
let modname m = m.modname
let opaque m = m.opaque
let mli m = m.mli
let mli_deps m = m.mli_deps
let ml m = m.ml
let ml_deps m = m.ml_deps
let build_dir m = m.build_dir
let built_file m ~ext = Fpath.(m.build_base + ext)
let cmi_file m = built_file m ~ext:".cmi"
let cmo_file m = match ml m with
| None -> None | Some _ -> Some (built_file m ~ext:".cmo")
let cmx_file m = match ml m with
| None -> None | Some _ -> Some (built_file m ~ext:".cmx")
let pp =
let path_option = Fmt.option ~none:Fmt.none Fpath.pp_unquoted in
let deps = Modname.Set.pp ~sep:Fmt.sp Fmt.string in
Fmt.record Fmt.[
field "modname" modname Modname.pp;
field "opaque" opaque bool;
field "mli" mli path_option;
field "mli-deps" mli_deps deps;
field "ml" ml path_option;
field "ml-deps" ml_deps deps;
field "build-dir" build_dir Fpath.pp_unquoted ]
let impl_file ~code m =
let file = match code with `Byte -> cmo_file | `Native -> cmx_file in
file m
let as_intf_dep_files ?(init = []) m = cmi_file m :: init
let as_impl_dep_files ?(init = []) ~code m = match code with
| `Byte -> cmi_file m :: init
| `Native ->
match ml m with
| None -> cmi_file m :: init
| Some _ when m.opaque -> cmi_file m :: init
| Some _ -> cmi_file m :: Option.get (cmx_file m) :: init
let modname_map m ~kind files =
let add acc f =
let mname = Modname.of_filename f in
match Modname.Map.find_opt mname acc with
| None -> Modname.Map.add mname f acc
| Some f' ->
B0_memo.notify m `Warn
"@[<v>%a:@,File ignored. %a's module %s defined by file:@,%a:@]"
Fpath.pp f Modname.pp mname kind Fpath.pp f';
acc
in
List.fold_left add Modname.Map.empty files
let map_of_srcs m ~build_dir ~srcs ~src_deps =
let get_src_deps = function
| None -> Modname.Set.empty
| Some file ->
match Fpath.Map.find file src_deps with
| exception Not_found -> Modname.Set.empty
| deps -> deps
in
let mlis, mls = List.partition (Fpath.has_ext ".mli") srcs in
let mlis = modname_map m ~kind:"interface" mlis in
let mls = modname_map m ~kind:"implementation" mls in
let mod' modname mli ml =
let mli_deps = get_src_deps mli in
let ml_deps = get_src_deps ml in
let opaque = false in
Some (make ~modname ~opaque ~mli ~mli_deps ~ml ~ml_deps ~build_dir)
in
Modname.Map.merge mod' mlis mls
let sort ?stable ~deps name_map =
(* FIXME do something better, on cycles this lead to link failure
we should detect it. *)
let rec loop seen acc = function
| [] -> seen, acc
| src :: srcs ->
if Modname.Set.mem src.modname seen then loop seen acc srcs else
let seen = Modname.Set.add src.modname seen in
let add_src_dep n acc = match Modname.Set.mem n seen with
| true -> acc
| false ->
match Modname.Map.find_opt n name_map with
| None -> acc
| Some src -> src :: acc
in
let deps = Modname.Set.fold add_src_dep (deps src) [] in
let seen, acc = loop seen acc deps in
loop seen (src :: acc) srcs
in
let add_src _ src acc = src :: acc in
let stable = Option.value ~default:[] stable in
let todo = stable @ Modname.Map.fold add_src name_map [] in
let _, acc = loop Modname.Set.empty [] todo in
List.rev acc
let find ns map =
let rec loop res remain deps = match Modname.Set.choose deps with
| exception Not_found -> res, remain
| dep ->
let deps = Modname.Set.remove dep deps in
match Modname.Map.find dep map with
| m -> loop (m :: res) remain deps
| exception Not_found ->
loop res (Modname.Set.add dep remain) deps
in
loop [] Modname.Set.empty ns
let map_of_files ?(only_mlis = false) m ~build_dir ~src_root ~srcs =
let exts = ".mli" :: if only_mlis then [] else [".ml"] in
let exts = B0_file_exts.make exts in
let srcs = B0_file_exts.find_files exts srcs in
let o = Fpath.(build_dir / "ocaml-srcs.deps") in
Deps.write m ~src_root ~srcs ~o;
let* src_deps = Deps.read m ~src_root o in
Fut.return (map_of_srcs m ~build_dir ~srcs ~src_deps)
end
(* Libraries *)
module Libname = struct
open Result.Syntax
(* Note. As it stands library name dots are represented by
[Fpath.dir_sep_char]. Not sure it makes sense it was done at
some point while seeking a simpler library model so that we could
directly lookup in directories without having to
convert. Review. *)
type t = { name : Fpath.t }
let fpath_to_name ?(sep = '.') s =
let b = Bytes.of_string (Fpath.to_string s) in
for i = 0 to Bytes.length b - 1 do
if Bytes.get b i = Fpath.dir_sep_char then Bytes.set b i sep;
done;
Bytes.unsafe_to_string b
let name_to_fpath s =
let err s exp = Fmt.error "%S: not a library name, %s" s exp in
let err_start s = err s "expected a starting lowercase ASCII letter" in
let b = Bytes.of_string s in
let max = String.length s - 1 in
let rec loop i ~id_start = match i > max with
| true ->
if id_start then err_start s else
Ok (Fpath.v (Bytes.unsafe_to_string b))
| false when id_start ->
begin match Bytes.get b i with
| 'a' .. 'z' -> loop (i + 1) ~id_start:false
| _ -> err_start s
end
| false ->
begin match Bytes.get b i with
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '-' ->
loop (i + 1) ~id_start:false
| '.' -> Bytes.set b i Fpath.dir_sep_char; loop (i + 1) ~id_start:true
| c -> err s (Fmt.str "illegal character %C" c)
end
in
loop 0 ~id_start:true
let basename n =
let n = Fpath.to_string n.name in
match String.cut_right ~sep:Fpath.dir_sep n with
| None -> n | Some (_, n) -> n
let root n =
let n = Fpath.to_string n.name in
match String.cut_left ~sep:Fpath.dir_sep n with
| None -> n | Some (n, _) -> n
let segments n = Fpath.to_segments n.name
let to_archive_name n = fpath_to_name ~sep:'_' n.name
let undot ~rep n = fpath_to_name ~sep:rep n.name
let of_string s =
let* name = name_to_fpath s in
Ok { name }
let to_string n = fpath_to_name n.name
let to_fpath { name } = name
let v s = match of_string s with Ok n -> n | Error e -> invalid_arg e
let equal n0 n1 = Fpath.equal n0.name n1.name
let compare n0 n1 = Fpath.compare n0.name n1.name
let pp = Fmt.using to_string Fmt.code'
module T = struct type nonrec t = t let compare = compare end
module Set = Set.Make (T)
module Map = Map.Make (T)
end
let libname = Libname.v
(* Metadata *)
let tag = B0_meta.Key.make_tag "ocaml" ~doc:"OCaml related entity"
let c_requires =
let doc = "Required C libraries" in
let pp_value = Cmd.pp in
B0_meta.Key.make "c-requires" ~default:Cmd.empty ~doc ~pp_value
let requires =
let doc = "Required OCaml libraries" in
let pp_value = Fmt.(box @@ list ~sep:sp Libname.pp) in
B0_meta.Key.make "ocaml-requires" ~default:[] ~doc ~pp_value
let library =
let doc = "Defined OCaml library name" in
let pp_value = Fmt.using Libname.to_string Fmt.string in
B0_meta.Key.make "ocaml-library" ~doc ~pp_value
let deprecated_library =
let doc = "Deprecated library" in
let pp_value ppf = function
| `For lib -> Fmt.pf ppf "For library: %s" (Libname.to_string lib)
| `Msg msg -> Fmt.string ppf msg
in
B0_meta.Key.make "ocaml-deprecated-library" ~doc ~pp_value
let modsrcs = (* FIXME don't do that. *)
let pp_value = Fmt.any "<dynamic>" in
B0_meta.Key.make "mod-srcs" ~doc:"Module sources" ~pp_value
module Lib = struct
type t =
{ libname : Libname.t;
requires : Libname.t list;
dir : Fpath.t;
cmis : Fpath.t list;
cmxs : Fpath.t list;
cma : Fpath.t option;
cmxa : Fpath.t option;
c_archive : Fpath.t option;
c_stubs : Fpath.t list;
js_stubs : Fpath.t list; }
let make
~libname ~requires ~dir ~cmis ~cmxs ~cma ~cmxa ~c_archive ~c_stubs
~js_stubs
=
{ libname; requires; dir; cmis; cmxs; cma; cmxa; c_archive; c_stubs;
js_stubs }
let of_dir m ~clib_ext ~libname ~requires ~dir ~archive ~js_stubs =
Fut.return @@
Result.map_error (fun e -> Fmt.str "library %a: %s" Libname.pp libname e) @@
Result.bind (Os.Dir.exists dir) @@ function
| false ->
B0_memo.notify m `Warn "library %a: no directory %a"
Libname.pp libname Fpath.pp dir;
Ok (make ~libname ~requires ~dir ~cmis:[] ~cmxs:[] ~cma:None ~cmxa:None
~c_archive:None ~c_stubs:[] ~js_stubs:[])
| true ->
Result.bind (Os.Dir.fold_files ~recurse:false Os.Dir.path_list dir [])
@@ fun fs ->
let js_stubs = List.map (fun f -> Fpath.(dir // f)) js_stubs in
let () = List.iter (B0_memo.file_ready m) js_stubs in
let rec loop cmis cmxs cma cmxa c_archive c_stubs = function
| [] ->
make ~libname ~requires ~dir ~cmis ~cmxs ~cma ~cmxa ~c_archive
~c_stubs ~js_stubs
| f :: fs ->
let is_lib_archive f = match archive with
| None -> false
| Some a -> String.equal (Fpath.basename ~no_ext:true f) a
in
match Fpath.get_ext f with
| ".cmi" ->
B0_memo.file_ready m f;
loop (f :: cmis) cmxs cma cmxa c_archive c_stubs fs
| ".cmx" ->
B0_memo.file_ready m f;
loop cmis (f :: cmxs) cma cmxa c_archive c_stubs fs
| ".cma" ->
let cma = match is_lib_archive f with
| true -> B0_memo.file_ready m f; Some f
| false -> cma
in
loop cmis cmxs cma cmxa c_archive c_stubs fs
| ".cmxa" ->
let cmxa = match is_lib_archive f with
| true -> B0_memo.file_ready m f; Some f
| false -> cmxa
in
loop cmis cmxs cma cmxa c_archive c_stubs fs
| ext when String.equal ext clib_ext ->
B0_memo.file_ready m f;
let c_archive, c_stubs = match is_lib_archive f with
| true -> Some f, c_stubs
| false -> c_archive, (f :: c_stubs)
in
loop cmis cmxs cma cmxa c_archive c_stubs fs
| _ ->
loop cmis cmxs cma cmxa c_archive c_stubs fs
in
Ok (loop [] [] None None None [] fs)
let of_unit b ocaml_conf u =
(* TODO presence of archives should depend on built_code. *)
B0_build.require b u;
let m = B0_build.memo b in
let build_dir = B0_build.build_dir b u in
let libname = B0_unit.get_meta library u |> B0_memo.fail_if_error m in
let requires =
B0_unit.get_meta requires u |> B0_memo.fail_if_error m
in
let archive = Libname.to_archive_name libname in
let base = Fpath.(build_dir / archive) in
let cma = Some Fpath.(base + ".cma") in
let cmxa = Some Fpath.(base + ".cmxa") in
let c_archive = Some Fpath.(base + (Conf.lib_ext ocaml_conf)) in
let c_stubs = [] (* FIXME *) in
let* srcs = B0_unit.get_meta modsrcs u |> B0_memo.fail_if_error m in
let cmis, cmxs =
let rec loop cmis cmxs = function
| [] -> cmis, cmxs
| s :: ss ->
let cmis = Modsrc.cmi_file s :: cmis in
let cmxs = match Modsrc.cmx_file s with
| None -> cmxs | Some cmx -> cmx :: cmxs
in
loop cmis cmxs ss
in
loop [] [] (Modname.Map.fold (fun _ v acc -> v :: acc) srcs [])
in
let js_stubs = [] (* FIXME *) in
Fut.return @@
Some (make ~libname ~requires ~dir:build_dir ~cmis ~cmxs ~cma ~cmxa
~c_archive ~c_stubs ~js_stubs)
let libname l = l.libname
let requires l = l.requires
let dir l = l.dir
let cmis l = l.cmis
let cmxs l = l.cmxs
let cma l = l.cma
let cmxa l = l.cmxa
let c_archive l = l.c_archive
let c_stubs l = l.c_stubs
let js_stubs l = l.js_stubs
end
(* Library resolvers *)
module Libresolver = struct
(* FIXME rework erroring, for now we are not using the mecanisms
and they likely need to be tweaked. *)
(* Resolution scopes *)
module Scope = struct
type find = Conf.t -> B0_memo.t -> Libname.t -> Lib.t option Fut.t
type suggest = Conf.t -> B0_memo.t -> Libname.t -> string option Fut.t
type t = { name : string; find : find; suggest : suggest; }
let name s = s.name
let find s = s.find
let suggest s = s.suggest
let make ~name ~find ~suggest = { name; find; suggest }
module Ocamlpath = struct
(* Stubbed at the moment *)
let find ~cache_dir conf m n = Fut.return None
let suggest conf m n = Fut.return None
let scope ~cache_dir =
let find = find ~cache_dir in
{ name = "OCAMLPATH"; find; suggest }
end
module Ocamlfind = struct
let tool = B0_memo.Tool.by_name "ocamlfind"
let parse_info m ?(file = Fpath.dash) ~libname:_ s =
let parse_requires requires =
let to_libname s =
Result.error_to_failure @@
Result.map_error (Fmt.str "required library: %s") @@
Libname.of_string s
in
if requires = "" then [] else
(* ocamlfind does not normalize *)
let skip_ws = String.lose_left Char.Ascii.is_white in
let get_tok = String.span_left (Fun.negate Char.Ascii.is_white) in
let rec rev_toks acc s =
let s = (skip_ws s) in
match get_tok s with
| "", rest -> if rest = "" then acc else rest :: acc (* will err *)
| tok, rest -> rev_toks (tok :: acc) rest
in
List.rev_map to_libname (rev_toks [] requires)
in
let parse_archive a =
if a = "" then None else
match String.cut_right ~sep:"." a with
| None -> Some a | Some (a, _ext) -> Some a
in
let parse_js_stubs js_stubs =
let stubs = String.cuts_left ~drop_empty:true ~sep:"," js_stubs in
let to_path s =
Result.error_to_failure @@
Result.map_error (Fmt.str "js stubs: %s") @@
Fpath.of_string s
in
List.map to_path stubs
in
try
match String.split_on_char ':' (String.trim s) with
| [meta; dir; archive; requires; js_stubs] ->
let requires = parse_requires requires in
let archive = parse_archive archive in
let dir =
Result.error_to_failure @@
Result.map_error (Fmt.str "library directory: %s") @@
Fpath.of_string dir
in
let js_stubs = parse_js_stubs js_stubs in
Ok (meta, requires, dir, archive, js_stubs)
| _ -> Fmt.failwith "could not parse %S" s
with
| Failure e -> Fmt.error "@[<v>%a: %s@]" Fpath.pp file e
(* FIXME need to solve the META file read.
FIXME post exec is still super messy, check if we can make it
to use Memo.t *)
let write_info ~cache_dir conf m n =
(* FIXME better [n] not found error *)
let ocamlfind = B0_memo.tool m tool in
let fname, lib, predicates = match Libname.to_string n with
| "ocaml.threads" | "threads" | "threads.posix" ->
if Conf.version conf < (5, 0, 0, None)
then "threads", "threads.posix", "byte,native,mt,mt_posix"
else "threads", "threads", "byte,native"
| n -> n, n, "byte,native"
in
let post_exec op = match B0_zero.Op.status op with
| B0_zero.Op.Done ->
begin match
Option.get (B0_zero.Op.Spawn.exit (B0_zero.Op.Spawn.get op))
with
| `Exited 2 ->
(* FIXME checktypo *)
let err = Fmt.str "OCaml library %a not found" Libname.pp n in
B0_zero.Op.set_status op (B0_zero.Op.(Failed (Exec (Some err))))
| _ -> ()
end
| _ -> ()
in
let success_exits = [0; 2 (* not found *) ] in
let info =
(* We use %A otherwise whith %a we get a blank line if there's
no archive. Technically though we only support single library
archives *)
"%m:%d:%A:%(requires):%(jsoo_runtime)"
in
let fname = Fmt.str "ocamlfind.%s" fname in
let o = Fpath.(cache_dir / fname) in
let stdout = `File o in
B0_memo.spawn m
~success_exits ~reads:[] ~writes:[o] ~stdout ~post_exec @@
ocamlfind Cmd.(arg "query" % lib % "-predicates" % predicates %
"-format" % info);
o
let read_info m clib_ext libname file =
let* s = B0_memo.read m file in
match parse_info ~file m ~libname s with
| Error _ as e -> B0_memo.fail_if_error m e
| Ok (_meta, requires, dir, archive, js_stubs) ->
let* lib =
Lib.of_dir m ~clib_ext ~libname ~requires ~dir ~archive ~js_stubs
in
Fut.return (Some (B0_memo.fail_if_error m lib))
let find ~cache_dir conf m n =
(* This never returns None we should factor error reporting
in *)
let clib_ext = Conf.lib_ext conf in
let o = write_info ~cache_dir conf m n in
read_info m clib_ext n o
let suggest conf m n = Fut.return None
let scope ~cache_dir =
let find = find ~cache_dir in
{ name = "ocamlfind"; find; suggest }
end
module Build = struct
let libs_in_build
b ~conf : (B0_unit.t * (Lib.t option Fut.t Lazy.t)) Libname.Map.t
=
let add u acc = match B0_unit.find_meta library u with
| None -> acc
| Some lib_name ->
match Libname.Map.find_opt lib_name acc with
| None ->
let lib = lazy (Lib.of_unit b conf u) in
Libname.Map.add lib_name (u, lib) acc
| Some (lib_u, _) ->
B0_memo.notify (B0_build.memo b)
`Warn "@[OCaml library %a already defined in unit %a.@,\
Ignoring definition in unit %a@]"
Libname.pp lib_name B0_unit.pp_name lib_u B0_unit.pp_name u;
acc
in
B0_unit.Set.fold add (B0_build.may_build b) Libname.Map.empty
let scope b conf =
let name = "build" in
let libs_in_build = libs_in_build b ~conf in
let find ocaml_conf m n =
match Libname.Map.find_opt n libs_in_build with
| None -> Fut.return None
| Some (_, lazy lib) -> lib
in
let suggest ocaml_conf m n = Fut.return None in
make ~name ~find ~suggest
end
let cache_dir_name = "ocaml-libresolver"
let ocamlpath = Ocamlpath.scope
let ocamlfind = Ocamlfind.scope
let build = Build.scope
end
type t =
{ memo : B0_memo.t;
conf : Conf.t;
scopes : Scope.t list;
mutable lookups : Lib.t option Fut.t Libname.Map.t; }
let make memo conf scopes =
let memo = B0_memo.with_mark memo "ocaml-resolver" in
{ memo; conf; scopes; lookups = Libname.Map.empty }
let default store m =
let* b = B0_store.get store B0_build.self in
let* ocaml_conf = B0_build.get b Conf.key in
let build_scope = Scope.build b ocaml_conf in
let cache_dir = Fpath.(B0_build.shared_build_dir b / Scope.cache_dir_name)in
(* let ocamlpath = Lib.Resolver.ocamlpath ~cache_dir in *)
let ocamlfind = Scope.ocamlfind ~cache_dir in
let scopes = [build_scope; (* ocamlpath; *) ocamlfind] in
Fut.return (make m ocaml_conf scopes)
let key = B0_store.key ~mark:"ocaml.libresolver" default
(* Properties *)
let memo r = r.memo
let lookups r = r.lookups
let ocaml_conf r = r.conf
let scopes r = r.scopes
let find_in_scopes r set n =
let rec loop r set n = function
| [] -> set None
| s :: ss ->
Fut.await (Scope.find s r.conf r.memo n) @@ function
| None -> loop r set n ss
| Some _ as lib -> set lib
in
loop r set n r.scopes
let find r n = match Libname.Map.find_opt n r.lookups with
| Some v -> v
| None ->
let fut, set = Fut.make () in
r.lookups <- Libname.Map.add n fut r.lookups;
find_in_scopes r set n;
fut
let get r n = Fut.bind (find r n) @@ function
| None -> B0_memo.fail r.memo "No OCaml library %a found" Libname.pp n
| Some lib -> Fut.return lib
let get_list r ns = Fut.of_list (List.map (get r) ns)
let get_list_and_deps r ns =
let rec loop seen acc = function
| [] -> Fut.return (seen, acc)
| l :: ls ->
if Libname.Set.mem l seen then loop seen acc ls else
let seen = Libname.Set.add l seen in
let* lib = get r l in
let not_seen n = not (Libname.Set.mem n seen) in
let deps = List.filter not_seen (Lib.requires lib) in
let* seen, acc = loop seen acc deps in
loop seen (lib :: acc) ls
in
let* _, libs = loop Libname.Set.empty [] ns in
Fut.return (List.rev libs)
end
module Compile = struct
(* XXX We should properly investigate how to use BUILD_PATH_PREFIX_MAP.
However for some reasons that were never not really answered by @gasche in
https://github.com/ocaml/ocaml/pull/1515, the map does not affect
absolute paths which severly limits its applicability.
XXX At some point we would had -o OBJ src [-I inc...] this worked
at least in 4.07 but not in 4.03, where apparently the order mattered.
XXX thread conf/version at that level ? E.g. if `-inc` becomes a
reality. We'd like to slip `-inc` in incs_of_file. *)
type code = [ `Byte | `Native ]
let incs_of_files files =
Cmd.paths ~slip:"-I" @@ Fpath.distinct @@ List.map Fpath.parent files
let c_to_o ?post_exec ?k m ~comp ~opts ~reads ~c ~o =
let cwd = Fpath.parent o
(* We can't use `-c` and `-o` on C files see
https://github.com/ocaml/ocaml/issues/7677 so we cwd to the
output directory to perform the spawn. *)
in
let incs = incs_of_files reads in
B0_memo.spawn m ?post_exec ?k ~reads:(c :: reads) ~writes:[o] ~cwd @@
(B0_memo.tool m comp)
Cmd.(arg "-c" %% opts %% unstamp (incs %% path c))
let mli_to_cmi ?post_exec ?k ~and_cmti m ~comp ~opts ~reads ~mli ~o =