Debian Codegraph @

vernac/library.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12 open CErrors
13 open Util
14
15 open Names
16 open Libobject
17
18 (************************************************************************)
19 (*s Low-level interning/externing of libraries to files *)
20
21 let raw_extern_library f =
22 ObjFile.open_out ~file:f
23
24 let raw_intern_library ?loc f =
25 System.with_magic_number_check ?loc
26 (fun file -> ObjFile.open_in ~file) f
27
28 (************************************************************************)
29 (** Serialized objects loaded on-the-fly *)
30
31 exception Faulty of string
32
33 module Delayed :
34 sig
35
36 type 'a delayed
37 val in_delayed : string -> ObjFile.in_handle -> segment:'a ObjFile.id -> 'a delayed * Digest.t
38 val fetch_delayed : 'a delayed -> 'a
39
40 end =
41 struct
42
43 type 'a delayed = {
44 del_file : string;
45 del_off : int64;
46 del_digest : Digest.t;
47 }
48
49 let in_delayed f ch ~segment =
50 let seg = ObjFile.get_segment ch ~segment in
51 let digest = seg.ObjFile.hash in
52 { del_file = f; del_digest = digest; del_off = seg.ObjFile.pos; }, digest
53
54 (** Fetching a table of opaque terms at position [pos] in file [f],
55 expecting to find first a copy of [digest]. *)
56
57 let fetch_delayed del =
58 let { del_digest = digest; del_file = f; del_off = pos; } = del in
59 let ch = open_in_bin f in
60 let obj, digest' =
61 try
62 let () = LargeFile.seek_in ch pos in
63 let obj = System.marshal_in f ch in
64 let digest' = Digest.input ch in
65 obj, digest'
66 with e -> close_in ch; raise e
67 in
68 close_in ch;
69 if not (String.equal digest digest') then raise (Faulty f);
70 obj
71
72 end
73
74 open Delayed
75
76
77 (************************************************************************)
78 (*s Modules on disk contain the following informations (after the magic
79 number, and before the digest). *)
80
81 type compilation_unit_name = DirPath.t
82
83 type library_disk = {
84 md_compiled : Safe_typing.compiled_library;
85 md_syntax_objects : Declaremods.library_objects;
86 md_objects : Declaremods.library_objects;
87 }
88
89 type summary_disk = {
90 md_name : compilation_unit_name;
91 md_deps : (compilation_unit_name * Safe_typing.vodigest) array;
92 md_ocaml : string;
93 md_info : Library_info.t;
94 }
95
96 (*s Modules loaded in memory contain the following informations. They are
97 kept in the global table [libraries_table]. *)
98
99 type library_t = {
100 library_name : compilation_unit_name;
101 library_data : library_disk;
102 library_deps : (compilation_unit_name * Safe_typing.vodigest) array;
103 library_digests : Safe_typing.vodigest;
104 library_info : Library_info.t;
105 library_vm : Vmlibrary.on_disk;
106 }
107
108 (* This is a map from names to loaded libraries *)
109 let libraries_table : library_t DirPath.Map.t ref =
110 Summary.ref DirPath.Map.empty ~stage:Summary.Stage.Synterp ~name:"LIBRARY"
111
112 (* This is the map of loaded libraries filename *)
113 (* (not synchronized so as not to be caught in the states on disk) *)
114 let libraries_filename_table = ref DirPath.Map.empty
115
116 (* These are the _ordered_ sets of loaded, imported and exported libraries *)
117 let libraries_loaded_list = Summary.ref [] ~stage:Summary.Stage.Synterp ~name:"LIBRARY-LOAD"
118
119 let loaded_native_libraries = Summary.ref DirPath.Set.empty ~stage:Summary.Stage.Interp ~name:"NATIVE-LIBRARY-LOAD"
120
121 (* Opaque proof tables *)
122
123 (* various requests to the tables *)
124
125 let find_library dir =
126 DirPath.Map.find_opt dir !libraries_table
127
128 let try_find_library dir =
129 match find_library dir with
130 | Some lib -> lib
131 | None ->
132 user_err
133 (str "Unknown library " ++ DirPath.print dir ++ str ".")
134
135 let library_compiled dir =
136 let lib = Option.get @@ find_library dir in
137 lib.library_data.md_compiled
138
139 let register_library_filename dir f =
140 (* Not synchronized: overwrite the previous binding if one existed *)
141 (* from a previous play of the session *)
142 libraries_filename_table :=
143 DirPath.Map.add dir f !libraries_filename_table
144
145 let library_full_filename dir =
146 try DirPath.Map.find dir !libraries_filename_table
147 with Not_found -> "<unavailable filename>"
148
149 let library_is_loaded dir =
150 try let _ = find_library dir in true
151 with Not_found -> false
152
153 (* If a library is loaded several time, then the first occurrence must
154 be performed first, thus the libraries_loaded_list ... *)
155
156 let register_loaded_library ~root m =
157 let libname = m.library_name in
158 let rec aux = function
159 | [] -> [root, libname]
160 | (_, m') ::_ as l when DirPath.equal m' libname -> l
161 | m'::l' -> m' :: aux l' in
162 libraries_loaded_list := aux !libraries_loaded_list;
163 libraries_table := DirPath.Map.add libname m !libraries_table
164
165 let register_native_library libname =
166 if (Global.typing_flags ()).enable_native_compiler
167 && not (DirPath.Set.mem libname !loaded_native_libraries) then begin
168 let dirname = Filename.dirname (library_full_filename libname) in
169 loaded_native_libraries := DirPath.Set.add libname !loaded_native_libraries;
170 Nativelib.enable_library dirname libname
171 end
172
173 let loaded_libraries () = List.map snd !libraries_loaded_list
174
175 (** Delayed / available tables of opaque terms *)
176
177 type table_status =
178 | ToFetch of Opaques.opaque_disk delayed
179 | Fetched of Opaques.opaque_disk
180
181 let opaque_tables =
182 ref (DirPath.Map.empty : table_status DirPath.Map.t)
183
184 let add_opaque_table dp st =
185 opaque_tables := DirPath.Map.add dp st !opaque_tables
186
187 let access_table what tables dp i =
188 let t = match DirPath.Map.find dp !tables with
189 | Fetched t -> t
190 | ToFetch f ->
191 let dir_path = Names.DirPath.to_string dp in
192 Flags.if_verbose Feedback.msg_info (str"Fetching " ++ str what++str" from disk for " ++ str dir_path);
193 let t =
194 try fetch_delayed f
195 with Faulty f ->
196 user_err
197 (str "The file " ++ str f ++ str " (bound to " ++ str dir_path ++
198 str ") is corrupted,\ncannot load some " ++
199 str what ++ str " in it.\n")
200 in
201 tables := DirPath.Map.add dp (Fetched t) !tables;
202 t
203 in
204 Opaques.get_opaque_disk i t
205
206 let access_opaque_table o =
207 let (sub, ci, dp, i) = Opaqueproof.repr o in
208 let ans =
209 if DirPath.equal dp (Global.current_dirpath ()) then
210 Opaques.get_current_opaque i
211 else
212 let what = "opaque proofs" in
213 access_table what opaque_tables dp i
214 in
215 match ans with
216 | None -> None
217 | Some (c, ctx) ->
218 let (c, ctx) = Discharge.cook_opaque_proofterm ci (c, ctx) in
219 let c = Mod_subst.subst_mps_list sub c in
220 Some (c, ctx)
221
222 let indirect_accessor = {
223 Global.access_proof = access_opaque_table;
224 }
225
226 (************************************************************************)
227 (* Internalise libraries *)
228
229 type seg_sum = summary_disk
230 type seg_lib = library_disk
231 type seg_proofs = Opaques.opaque_disk
232 type seg_vm = Vmlibrary.compiled_library
233
234 let mk_library sd md digests vm =
235 {
236 library_name = sd.md_name;
237 library_data = md;
238 library_deps = sd.md_deps;
239 library_digests = digests;
240 library_info = sd.md_info;
241 library_vm = vm;
242 }
243
244 let mk_intern_library sum lib digest_lib proofs vm =
245 add_opaque_table sum.md_name (ToFetch proofs);
246 let open Safe_typing in
247 mk_library sum lib (Dvo_or_vi digest_lib) vm
248
249 let summary_seg : seg_sum ObjFile.id = ObjFile.make_id "summary"
250 let library_seg : seg_lib ObjFile.id = ObjFile.make_id "library"
251 let opaques_seg : seg_proofs ObjFile.id = ObjFile.make_id "opaques"
252 let vm_seg : seg_vm ObjFile.id = Vmlibrary.vm_segment
253
254 module Intern = struct
255 module Provenance = struct
256 type t = string * string
257 (** A pair of [kind, object], for example ["file",
258 "/usr/local/foo.vo"], used for error messages. *)
259 end
260
261 type t = DirPath.t -> (library_t, Exninfo.iexn) Result.t * Provenance.t
262 end
263
264 let intern_from_file file =
265 let ch = raw_intern_library file in
266 let lsd, digest_lsd = ObjFile.marshal_in_segment ch ~segment:summary_seg in
267 let lmd, digest_lmd = ObjFile.marshal_in_segment ch ~segment:library_seg in
268 let del_opaque, _ = in_delayed file ch ~segment:opaques_seg in
269 let vmlib = Vmlibrary.load lsd.md_name ~file ch in
270 ObjFile.close_in ch;
271 System.check_caml_version ~caml:lsd.md_ocaml ~file;
272 register_library_filename lsd.md_name file;
273 Library_info.warn_library_info ~transitive:true lsd.md_name lsd.md_info;
274 mk_intern_library lsd lmd digest_lmd del_opaque vmlib
275
276 let intern_from_file file =
277 let provenance = ("file", file) in
278 (* This is a barrier to catch IO / Marshal exceptions in a more
279 structured way, as to provide better error messages. *)
280 (match CErrors.to_result ~f:intern_from_file file with
281 | Ok res -> Ok res
282 | Error iexn -> Error iexn), provenance
283
284 let check_library_expected_name ~provenance dir library_name =
285 if not (DirPath.equal dir library_name) then
286 let kind, obj = provenance in
287 user_err
288 (str "The " ++ str kind ++ str " " ++ str obj ++ str " contains library" ++ spc () ++
289 DirPath.print library_name ++ spc () ++ str "and not library" ++
290 spc() ++ DirPath.print dir ++ str ".")
291
292 exception InternError of { exn : exn; provenance : Intern.Provenance.t; dir : DirPath.t }
293
294 let () = CErrors.register_handler (function
295 | InternError { exn; provenance; dir } ->
296 let err = CErrors.print exn in
297 Some (Pp.(str "Error when parsing .vo (from " ++ str (fst provenance) ++ str " " ++
298 str (snd provenance) ++ str ") for library " ++ Names.DirPath.print dir ++ str ": " ++ err))
299 | _ -> None)
300
301 let error_in_intern provenance dir (exn, info) =
302 Exninfo.iraise (InternError { exn; provenance; dir }, info)
303
304 (* Returns the digest of a library, checks both caches to see what is loaded *)
305 let rec intern_library ~root ~intern (needed, contents as acc) dir =
306 (* Look if in the current logical environment *)
307 match find_library dir with
308 | Some loaded_lib -> loaded_lib, acc
309 | None ->
310 (* Look if already listed in the accumulator *)
311 match DirPath.Map.find_opt dir contents with
312 | Some interned_lib ->
313 interned_lib, acc
314 | None ->
315 (* We intern the library, and then intern the deps *)
316 match intern dir with
317 | Ok m, provenance ->
318 check_library_expected_name ~provenance dir m.library_name;
319 m, intern_library_deps ~root ~intern acc dir m
320 | Error iexn, provenance ->
321 error_in_intern provenance dir iexn
322
323 and intern_library_deps ~root ~intern libs dir m =
324 let needed, contents =
325 Array.fold_left (intern_mandatory_library ~intern dir)
326 libs m.library_deps in
327 ((root, dir) :: needed, DirPath.Map.add dir m contents )
328
329 and intern_mandatory_library ~intern caller libs (dir,d) =
330 let m, libs = intern_library ~root:false ~intern libs dir in
331 let digest = m.library_digests in
332 let () = if not (Safe_typing.digest_match ~actual:digest ~required:d) then
333 let from = library_full_filename caller in
334 user_err
335 (str "Compiled library " ++ DirPath.print caller ++
336 str " (in file " ++ str from ++
337 str ") makes inconsistent assumptions over library " ++
338 DirPath.print dir)
339 in
340 libs
341
342 let rec_intern_library ~intern libs (loc, dir) =
343 let m, libs = intern_library ~root:true ~intern libs dir in
344 Library_info.warn_library_info m.library_name m.library_info;
345 libs
346
347 let native_name_from_filename f =
348 let ch = raw_intern_library f in
349 let lmd, digest_lmd = ObjFile.marshal_in_segment ch ~segment:summary_seg in
350 Nativecode.mod_uid_of_dirpath lmd.md_name
351
352 (**********************************************************************)
353 (*s [require_library] loads and possibly opens a library. This is a
354 synchronized operation. It is performed as follows:
355
356 preparation phase: (functions require_library* ) the library and its
357 dependencies are read from to disk (using intern_* )
358 [they are read from disk to ensure that at section/module
359 discharging time, the physical library referred to outside the
360 section/module is the one that was used at type-checking time in
361 the section/module]
362
363 execution phase: (through add_leaf and cache_require)
364 the library is loaded in the environment and Nametab, the objects are
365 registered etc, using functions from Declaremods (via load_library,
366 which recursively loads its dependencies)
367 *)
368
369 let register_library m =
370 let l = m.library_data in
371 Declaremods.Interp.register_library
372 m.library_name
373 l.md_compiled
374 l.md_objects
375 m.library_digests
376 m.library_vm
377 ;
378 register_native_library m.library_name
379
380 let register_library_syntax (root, m) =
381 let l = m.library_data in
382 Declaremods.Synterp.register_library
383 m.library_name
384 l.md_syntax_objects;
385 register_loaded_library ~root m
386
387 (* Follow the semantics of Anticipate object:
388 - called at module or module type closing when a Require occurs in
389 the module or module type
390 - not called from a library (i.e. a module identified with a file) *)
391 let load_require _ needed =
392 List.iter register_library needed
393
394 (* [needed] is the ordered list of libraries not already loaded *)
395 let cache_require o =
396 load_require 1 o
397
398 let discharge_require o = Some o
399
400 (* open_function is never called from here because an Anticipate object *)
401
402 type require_obj = library_t list
403
404 let in_require : require_obj -> obj =
405 declare_object
406 {(default_object "REQUIRE") with
407 cache_function = cache_require;
408 load_function = load_require;
409 open_function = (fun _ _ -> assert false);
410 discharge_function = discharge_require;
411 classify_function = (fun o -> Anticipate) }
412
413 let load_require_syntax _ needed =
414 List.iter register_library_syntax needed
415
416 let cache_require_syntax o =
417 load_require_syntax 1 o
418
419 let discharge_require_syntax o = Some o
420
421 (* open_function is never called from here because an Anticipate object *)
422
423 type require_obj_syntax = (bool * library_t) list
424
425 let in_require_syntax : require_obj_syntax -> obj =
426 declare_object
427 {(default_object "REQUIRE-SYNTAX") with
428 object_stage = Summary.Stage.Synterp;
429 cache_function = cache_require_syntax;
430 load_function = load_require_syntax;
431 open_function = (fun _ _ -> assert false);
432 discharge_function = discharge_require_syntax;
433 classify_function = (fun o -> Anticipate) }
434
435 (* Require libraries, import them if [export <> None], mark them for export
436 if [export = Some true] *)
437
438 let warn_require_in_module =
439 CWarnings.create ~name:"require-in-module" ~category:CWarnings.CoreCategories.fragile
440 (fun () -> strbrk "Use of “Require” inside a module is fragile." ++ spc() ++
441 strbrk "It is not recommended to use this functionality in finished proof scripts.")
442
443 let require_library_from_dirpath needed =
444 if Lib.is_module_or_modtype () then warn_require_in_module ();
445 Lib.add_leaf (in_require needed)
446
447 let require_library_syntax_from_dirpath ~intern modrefl =
448 let needed, contents = List.fold_left (rec_intern_library ~intern) ([], DirPath.Map.empty) modrefl in
449 let needed = List.rev_map (fun (root, dir) -> root, DirPath.Map.find dir contents) needed in
450 Lib.add_leaf (in_require_syntax needed);
451 List.map snd needed
452
453 (************************************************************************)
454 (*s [save_library dir] ends library [dir] and save it to the disk. *)
455
456 let current_deps () =
457 (* Only keep the roots of the dependency DAG *)
458 let map (root, m) =
459 if root then
460 let m = try_find_library m in
461 Some (m.library_name, m.library_digests)
462 else None
463 in
464 List.map_filter map !libraries_loaded_list
465
466 let error_recursively_dependent_library dir =
467 user_err
468 (strbrk "Unable to use logical name " ++ DirPath.print dir ++
469 strbrk " to save current library because" ++
470 strbrk " it already depends on a library of this name.")
471
472 type 'doc todo_proofs =
473 | ProofsTodoNone (* for .vo *)
474 | ProofsTodoSomeEmpty of Future.UUIDSet.t (* for .vos *)
475
476 (* We now use two different digests in a .vo file. The first one
477 only covers half of the file, without the opaque table. It is
478 used for identifying this version of this library : this digest
479 is the one leading to "inconsistent assumptions" messages.
480 The other digest comes at the very end, and covers everything
481 before it. This one is used for integrity check of the whole
482 file when loading the opaque table. *)
483
484 (* Security weakness: file might have been changed on disk between
485 writing the content and computing the checksum... *)
486
487 (* EJGA: would be nice maybe to have a version that performs extra
488 cleanup in the case the computation raises? *)
489 let save_library_base f sum lib proofs vmlib =
490 try
491 let open Memprof_coq.Resource_bind in
492 let& ch = Memprof_coq.Masking.with_resource ~acquire:raw_extern_library ~release:ObjFile.close_out f in
493 ObjFile.marshal_out_segment ch ~segment:summary_seg sum;
494 ObjFile.marshal_out_segment ch ~segment:library_seg lib;
495 ObjFile.marshal_out_segment ch ~segment:opaques_seg proofs;
496 ObjFile.marshal_out_segment ch ~segment:vm_seg vmlib
497 with exn ->
498 let iexn = Exninfo.capture exn in
499 Sys.remove f;
500 Exninfo.iraise iexn
501
502 (* This is the basic vo save structure *)
503 let save_library_struct ~output_native_objects dir =
504 let md_compiled, md_objects, md_syntax_objects, vmlib, ast, info =
505 Declaremods.end_library ~output_native_objects dir in
506 let sd =
507 { md_name = dir
508 ; md_deps = Array.of_list (current_deps ())
509 ; md_ocaml = Coq_config.caml_version
510 ; md_info = info
511 } in
512 let md =
513 { md_compiled
514 ; md_syntax_objects
515 ; md_objects
516 } in
517 if Array.exists (fun (d,_) -> DirPath.equal d dir) sd.md_deps then
518 error_recursively_dependent_library dir;
519 sd, md, vmlib, ast
520
521 let save_library dir : library_t =
522 let sd, md, vmlib, _ast = save_library_struct ~output_native_objects:false dir in
523 (* Digest for .vo files is on the md part, for now we also play it
524 safe when we work on-memory and compute the digest for the lib
525 part, even if that's slow. Better safe than sorry. *)
526 let digest = Marshal.to_string md [] |> Digest.string in
527 mk_library sd md (Dvo_or_vi digest) (Vmlibrary.inject vmlib)
528
529 let save_library_to todo_proofs ~output_native_objects dir f =
530 assert(
531 let expected_extension = match todo_proofs with
532 | ProofsTodoNone -> ".vo"
533 | ProofsTodoSomeEmpty _ -> ".vos"
534 in
535 Filename.check_suffix f expected_extension);
536 let except = match todo_proofs with
537 | ProofsTodoNone -> Future.UUIDSet.empty
538 | ProofsTodoSomeEmpty except -> except
539 in
540 (* Ensure that the call below is performed with all opaques joined *)
541 let () = Opaques.Summary.join ~except () in
542 let opaque_table, f2t_map = Opaques.dump ~except () in
543 let () = assert (not (Future.UUIDSet.is_empty except) ||
544 Safe_typing.is_joined_environment (Global.safe_env ()))
545 in
546 let sd, md, vmlib, ast = save_library_struct ~output_native_objects dir in
547 (* Writing vo payload *)
548 save_library_base f sd md opaque_table vmlib;
549 (* Writing native code files *)
550 if output_native_objects then
551 let fn = Filename.dirname f ^"/"^ Nativecode.mod_uid_of_dirpath dir in
552 Nativelib.compile_library ast fn
553
554 let get_used_load_paths () =
555 String.Set.elements
556 (List.fold_left (fun acc (root, m) -> String.Set.add
557 (Filename.dirname (library_full_filename m)) acc)
558 String.Set.empty !libraries_loaded_list)
559
560 let _ = Nativelib.get_load_paths := get_used_load_paths