Debian Codegraph @

topbin/rocqnative.ml

raw symbols SCIP
1 (* Rocq native compiler *)
2 open CErrors
3 open Util
4 open Names
5 open Pp
6
7 module Loadpath :
8 sig
9 val add_load_path : string * DirPath.t -> unit
10 val default_root_prefix : DirPath.t
11 val dirpath_of_string : string -> DirPath.t
12 val locate_absolute_library : DirPath.t -> string
13 end =
14 struct
15
16 let pr_dirpath dp = str (DirPath.to_string dp)
17 let default_root_prefix = DirPath.empty
18 let split_dirpath d =
19 let l = DirPath.repr d in (DirPath.make (List.tl l), List.hd l)
20
21 type logical_path = DirPath.t
22
23 let load_paths = ref ([],[] : CUnix.physical_path list * logical_path list)
24
25 let remove_load_path dir =
26 let physical, logical = !load_paths in
27 load_paths := List.filter2 (fun p d -> p <> dir) physical logical
28
29 let add_load_path (phys_path,rocq_path) =
30 if CDebug.(get_flag misc) then
31 Feedback.msg_notice (str "path: " ++ pr_dirpath rocq_path ++ str " ->" ++ spc() ++
32 str phys_path);
33 let phys_path = CUnix.canonical_path_name phys_path in
34 let physical, logical = !load_paths in
35 match List.filter2 (fun p d -> p = phys_path) physical logical with
36 | _,[dir] ->
37 if rocq_path <> dir
38 (* If this is not the default -I . to coqtop *)
39 && not
40 (phys_path = CUnix.canonical_path_name Filename.current_dir_name
41 && rocq_path = default_root_prefix)
42 then
43 begin
44 (* Assume the user is concerned by library naming *)
45 if dir <> default_root_prefix then
46 Feedback.msg_warning
47 (str phys_path ++ strbrk " was previously bound to " ++
48 pr_dirpath dir ++ strbrk "; it is remapped to " ++
49 pr_dirpath rocq_path);
50 remove_load_path phys_path;
51 load_paths := (phys_path::fst !load_paths, rocq_path::snd !load_paths)
52 end
53 | _,[] ->
54 load_paths := (phys_path :: fst !load_paths, rocq_path :: snd !load_paths)
55 | _ -> anomaly (Pp.str ("Two logical paths are associated to "^phys_path^"."))
56
57 let load_paths_of_dir_path dir =
58 let physical, logical = !load_paths in
59 fst (List.filter2 (fun p d -> d = dir) physical logical)
60
61 let locate_absolute_library dir =
62 (* Search in loadpath *)
63 let pref, base = split_dirpath dir in
64 let loadpath = load_paths_of_dir_path pref in
65 if loadpath = [] then CErrors.user_err (str "No loadpath for " ++ DirPath.print pref);
66 let name = Id.to_string base^".vo" in
67 try
68 let _, file = System.where_in_path ~warn:false loadpath name in
69 file
70 with Not_found ->
71 CErrors.user_err (str "File " ++ str name ++ str " not found in loadpath")
72
73 let dirpath_of_string s = match String.split_on_char '.' s with
74 | [""] -> default_root_prefix
75 | dir -> DirPath.make (List.rev_map Id.of_string dir)
76
77 end
78
79 module Library =
80 struct
81
82 type library_objects
83
84 type compilation_unit_name = DirPath.t
85
86 (* The [*_disk] types below must be kept in sync with the vo representation. *)
87
88 type library_disk = {
89 md_compiled : Safe_typing.compiled_library;
90 md_syntax_objects : library_objects;
91 md_objects : library_objects;
92 }
93
94 type library_info
95
96 type summary_disk = {
97 md_name : compilation_unit_name;
98 md_deps : (compilation_unit_name * Safe_typing.vodigest) array;
99 md_ocaml : string;
100 md_info : library_info;
101 }
102
103 type library_t = {
104 library_name : compilation_unit_name;
105 library_file : string;
106 library_data : Safe_typing.compiled_library;
107 library_deps : (compilation_unit_name * Safe_typing.vodigest) array;
108 library_digests : Safe_typing.vodigest;
109 library_vm : Vmlibrary.on_disk;
110 }
111
112 let libraries_table : string DirPath.Map.t ref = ref DirPath.Map.empty
113
114 let register_loaded_library senv libname file =
115 let () = assert (not @@ DirPath.Map.mem libname !libraries_table) in
116 let () = libraries_table := DirPath.Map.add libname file !libraries_table in
117 let prefix = Nativecode.mod_uid_of_dirpath libname ^ "." in
118 let () = Nativecode.register_native_file prefix in
119 senv
120
121 let mk_library sd f md digests vm =
122 {
123 library_name = sd.md_name;
124 library_file = f;
125 library_data = md;
126 library_deps = sd.md_deps;
127 library_digests = digests;
128 library_vm = vm;
129 }
130
131 let summary_seg : summary_disk ObjFile.id = ObjFile.make_id "summary"
132 let library_seg : library_disk ObjFile.id = ObjFile.make_id "library"
133
134 let intern_from_file f =
135 let ch = System.with_magic_number_check (fun file -> ObjFile.open_in ~file) f in
136 let lsd, digest_lsd = ObjFile.marshal_in_segment ch ~segment:summary_seg in
137 let lmd, digest_lmd = ObjFile.marshal_in_segment ch ~segment:library_seg in
138 let vmlib = Vmlibrary.load ~file:f lsd.md_name ch in
139 ObjFile.close_in ch;
140 System.check_caml_version ~caml:lsd.md_ocaml ~file:f;
141 let open Safe_typing in
142 mk_library lsd f lmd.md_compiled (Dvo_or_vi digest_lmd) vmlib
143
144 let rec intern_library (needed, contents) dir =
145 (* Look if already listed and consequently its dependencies too *)
146 match DirPath.Map.find dir contents with
147 | lib -> lib.library_digests, (needed, contents)
148 | exception Not_found ->
149 let f = Loadpath.locate_absolute_library dir in
150 let m = intern_from_file f in
151 if not (DirPath.equal dir m.library_name) then
152 user_err
153 (str "The file " ++ str f ++ str " contains library" ++ spc () ++
154 DirPath.print m.library_name ++ spc () ++ str "and not library" ++
155 spc() ++ DirPath.print dir ++ str ".");
156 let (needed, contents) = intern_library_deps (needed, contents) dir m f in
157 m.library_digests, (dir :: needed, DirPath.Map.add dir m contents)
158
159 and intern_library_deps libs dir m from =
160 Array.fold_left (intern_mandatory_library dir from) libs m.library_deps
161
162 and intern_mandatory_library caller from libs (dir,d) =
163 let digest, libs = intern_library libs dir in
164 if not (Safe_typing.digest_match ~actual:digest ~required:d) then
165 user_err (str "Compiled library " ++ DirPath.print caller ++
166 str " (in file " ++ str from ++ str ") makes inconsistent assumptions \
167 over library " ++ DirPath.print dir);
168 libs
169
170 let register_library senv m =
171 let mp = MPfile m.library_name in
172 let mp', senv = Safe_typing.import m.library_data m.library_vm m.library_digests senv in
173 let () =
174 if not (ModPath.equal mp mp') then
175 anomaly (Pp.str "Unexpected disk module name.")
176 in
177 register_loaded_library senv m.library_name m.library_file
178
179 let save_library_to env dir f lib =
180 let mp = MPfile dir in
181 let ast = Nativelibrary.dump_library mp env lib in
182 let fn = Filename.dirname f ^"/"^ Nativecode.mod_uid_of_dirpath dir in
183 Nativelib.compile_library ast fn
184
185 let get_used_load_paths () =
186 String.Set.elements
187 (DirPath.Map.fold (fun m f acc -> String.Set.add
188 (Filename.dirname f) acc)
189 !libraries_table String.Set.empty)
190
191 let _ = Nativelib.get_load_paths := get_used_load_paths
192 end
193
194 let add_path ~unix_path:dir ~rocq_root:rocq_dirpath =
195 let open System in
196 if exists_dir dir then
197 begin
198 Loadpath.add_load_path (dir,rocq_dirpath)
199 end
200 else
201 Feedback.msg_warning (str "Cannot open " ++ str dir)
202
203 let convert_string d =
204 try Id.of_string d
205 with CErrors.UserError _ ->
206 Flags.if_verbose Feedback.msg_warning
207 (str "Directory " ++ str d ++ str " cannot be used as a Rocq identifier (skipped)");
208 raise_notrace Exit
209
210 let rocq_root = Id.of_string "Corelib"
211
212 let add_rec_path ~unix_path ~rocq_root =
213 let open System in
214 if exists_dir unix_path then
215 let dirs = all_subdirs ~unix_path in
216 let prefix = DirPath.repr rocq_root in
217 let convert_dirs (lp, cp) =
218 try
219 let path = List.rev_map convert_string cp @ prefix in
220 Some (lp, Names.DirPath.make path)
221 with Exit -> None
222 in
223 let dirs = List.map_filter convert_dirs dirs in
224 List.iter Loadpath.add_load_path dirs;
225 Loadpath.add_load_path (unix_path, rocq_root)
226 else
227 Feedback.msg_warning (str "Cannot open " ++ str unix_path)
228
229 let init_load_path_std env ~default_ml () =
230 let corelib = Boot.Env.corelib env |> Boot.Path.to_string in
231 let user_contrib = Boot.Env.user_contrib env |> Boot.Path.to_string in
232 let xdg_dirs = Envars.xdg_dirs in
233 let rocqpath = Envars.coqpath in
234 let () = if default_ml then Nativelib.(include_dirs := default_include_dirs env) in
235 (* NOTE: These directories are searched from last to first *)
236 (* first standard library *)
237 add_rec_path ~unix_path:corelib ~rocq_root:(Names.DirPath.make[rocq_root]);
238 (* then user-contrib *)
239 if Sys.file_exists user_contrib then
240 add_rec_path ~unix_path:user_contrib ~rocq_root:Loadpath.default_root_prefix;
241 (* then directories in XDG_DATA_DIRS and XDG_DATA_HOME *)
242 List.iter (fun s -> add_rec_path ~unix_path:s ~rocq_root:Loadpath.default_root_prefix)
243 (xdg_dirs ~warn:(fun x -> Feedback.msg_warning (str x)));
244 (* then directories in ROCQPATH *)
245 List.iter (fun s -> add_rec_path ~unix_path:s ~rocq_root:Loadpath.default_root_prefix) (rocqpath())
246
247 let init_load_path ~boot ~coqlib ~vo_path ~ml_path =
248 let default_ml = CList.is_empty ml_path in
249 let coqenv = Boot.Env.maybe_init ~boot ~coqlib
250 ~warn_ignored_coqlib:CWarnings.warn_ignored_coqlib
251 in
252 let () = match coqenv with
253 | Boot -> ()
254 | Env env ->
255 init_load_path_std env ~default_ml:(CList.is_empty ml_path) ()
256 in
257 let () = if not default_ml then Nativelib.include_dirs := ml_path in
258 (* always add current directory *)
259 add_path ~unix_path:"." ~rocq_root:Loadpath.default_root_prefix;
260 (* additional loadpath, given with -R/-Q options *)
261 List.iter
262 (fun (unix_path, rocq_root) -> add_rec_path ~unix_path ~rocq_root)
263 (List.rev vo_path)
264
265 let fb_handler = function
266 | Feedback.{ contents; _ } ->
267 match contents with
268 | Feedback.Message(_lvl,_loc,_qf, msg)->
269 Format.printf "%s@\n%!" Pp.(string_of_ppcmds msg)
270 | _ -> ()
271
272 let init_rocq () =
273 let senv = Safe_typing.empty_environment in
274 let senv = Safe_typing.set_native_compiler true senv in
275 let () = Safe_typing.allow_delayed_constants := false in
276 let dummy = Names.DirPath.make [Names.Id.of_string_soft "@native"] in
277 let _, senv = Safe_typing.start_library dummy senv in
278 senv
279
280 let compile senv ~in_file =
281 let lib = Library.intern_from_file in_file in
282 let dir = lib.Library.library_name in
283 (* Require the dependencies **only once** *)
284 let deps, contents = Library.intern_library_deps ([], DirPath.Map.empty) dir lib in_file in
285 let fold senv dep = Library.register_library senv (DirPath.Map.find dep contents) in
286 let senv = List.fold_left fold senv (List.rev deps) in
287 (* Extract the native code and compile it *)
288 let modl = Mod_declarations.mod_type (Safe_typing.module_of_library lib.Library.library_data) in
289 let out_vo = Filename.(remove_extension in_file) ^ ".vo" in
290 (* Replay locally the module being extracted *)
291 let env = match modl with
292 | NoFunctor struc ->
293 let reso = Mod_declarations.mod_delta (Safe_typing.module_of_library lib.Library.library_data) in
294 Modops.add_structure (MPfile dir) struc reso (Safe_typing.env_of_safe_env senv)
295 | MoreFunctor _ -> assert false
296 in
297 Library.save_library_to env dir out_vo modl
298
299 module Usage :
300 sig
301 val usage : unit -> 'a
302 end =
303 struct
304
305 let print_usage_channel co command =
306 output_string co command;
307 output_string co "rocq native-precompile options are:\n";
308 output_string co
309 " -Q dir coqdir map physical dir to logical coqdir\
310 \n -R dir coqdir synonymous for -Q\
311 \n\
312 \n\
313 \n -boot boot mode\
314 \n -coqlib dir set coqnative's standard library location\
315 \n -native-output-dir <directory> set the output directory for native objects\
316 \n -nI dir OCaml include directories for the native compiler (default if not set) \
317 \n\
318 \n -h, --help print this list of options\
319 \n"
320
321 (* print the usage on standard error *)
322
323 let print_usage = print_usage_channel stderr
324
325 let print_usage_coqnative () =
326 print_usage "Usage: rocq native-precompile <options> file\n\n"
327
328 let usage () =
329 print_usage_coqnative ();
330 flush stderr;
331 exit 1
332
333 end
334
335 type opts = {
336 boot : bool;
337 coqlib : string option;
338 vo_path : (string * DirPath.t) list;
339 ml_path : string list;
340 }
341
342 let rec parse_args (args : string list) accu =
343 match args with
344 | [] -> CErrors.user_err (Pp.str "parse args error: missing argument")
345 | "-boot" :: rem ->
346 parse_args rem { accu with boot = true}
347 (* We ignore as we don't require Prelude explicitly *)
348 | "-noinit" :: rem ->
349 parse_args rem accu
350 | ("-Q" | "-R") :: d :: p :: rem ->
351 let p = if String.equal p "Coq" then "Corelib" else p in
352 (* -R Coq ... is only used by Dune in conjunction with the -boot
353 option. The above line should be removed once we require an
354 updated version of Dune. *)
355 let p = Loadpath.dirpath_of_string p in
356 let accu = { accu with vo_path = (d, p) :: accu.vo_path } in
357 parse_args rem accu
358 | "-I" :: _d :: rem ->
359 (* Ignore *)
360 parse_args rem accu
361 | "-nI" :: dir :: rem ->
362 let accu = { accu with ml_path = dir :: accu.ml_path } in
363 parse_args rem accu
364 |"-native-output-dir" :: dir :: rem ->
365 Nativelib.output_dir := dir;
366 parse_args rem accu
367 | "-coqlib" :: s :: rem -> parse_args rem { accu with coqlib = Some s }
368 | ("-?"|"-h"|"-H"|"-help"|"--help") :: _ -> Usage.usage ()
369 | [file] ->
370 accu, file
371 | args ->
372 let args_msg = String.concat " " args in
373 CErrors.user_err Pp.(str "parse args error, too many arguments: " ++ str args_msg)
374
375 let () =
376 let _ = Feedback.add_feeder fb_handler in
377 try
378 let opts = { boot = false; coqlib = None; vo_path = []; ml_path = [] } in
379 let opts, in_file = parse_args (List.tl @@ Array.to_list Sys.argv) opts in
380 let () = init_load_path ~boot:opts.boot
381 ~coqlib:opts.coqlib
382 ~vo_path:(List.rev opts.vo_path)
383 ~ml_path:(List.rev opts.ml_path)
384 in
385 let senv = init_rocq () in
386 compile senv ~in_file
387 with exn ->
388 Format.eprintf "Error: @[%a@]@\n%!" Pp.pp_with (CErrors.print exn);
389 let exit_code = CErrors.exit_code exn in
390 exit exit_code