Debian Codegraph @

vernac/mltop.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 Util
12 open Pp
13
14 (* Code to interact with ML "toplevel", in particular, handling ML
15 plugin loading.
16
17 We use Fl_dynload to load plugins, which can correctly track
18 dependencies, and manage path for us.
19
20 A bit of infrastructure is still in place to support a "legacy"
21 mode where Rocq used to manage the OCaml include paths and directly
22 load .cmxs/.cma files itself.
23
24 We also place here the required code for interacting with the
25 Summary and Libobject, and provide an API so plugins can interact
26 with this loading/unloading for Rocq-specific purposes adding their
27 own init functions, given that OCaml cannot unlink a dynamic module.
28
29 *)
30
31
32 module Fl_internals = struct
33
34 (* Fl_split.in_words is not exported *)
35 let fl_split_in_words s =
36 (* splits s in words separated by commas and/or whitespace *)
37 let l = String.length s in
38 let rec split i j =
39 if j < l then
40 match s.[j] with
41 | (' '|'\t'|'\n'|'\r'|',') ->
42 if i<j then (String.sub s i (j-i)) :: (split (j+1) (j+1))
43 else split (j+1) (j+1)
44 | _ ->
45 split i (j+1)
46 else
47 if i<j then [ String.sub s i (j-i) ] else []
48 in
49 split 0 0
50
51 (* simulate what fl_dynload does *)
52 let fl_find_plugins lib =
53 let base = Findlib.package_directory lib in
54 let preds = Findlib.recorded_predicates () in
55 let archive = try Findlib.package_property preds lib "plugin"
56 with Not_found ->
57 try fst (Findlib.package_property_2 ("plugin"::preds) lib "archive")
58 with Not_found -> ""
59 in
60 fl_split_in_words archive |> List.map (Findlib.resolve_path ~base)
61
62 (* We register errors at for Dynlink and Findlib, it is possible to
63 do so Symtable too, as we used to do in the bytecode init code.
64 *)
65 let () = CErrors.register_handler (function
66 | Dynlink.Error msg ->
67 Some (hov 0 (str "Dynlink error: " ++ str (Dynlink.error_message msg)))
68 | Fl_package_base.No_such_package(p,msg) ->
69 let paths = Findlib.search_path () in
70 Some (hov 0 (str "Findlib error: " ++ str p ++
71 str " not found in:" ++ cut () ++ v 0 (prlist_with_sep cut str paths) ++ fnl() ++ str msg))
72 | _ ->
73 None
74 )
75
76 end
77
78 let dbg_dynlink = CDebug.create ~name:"dynlink" ()
79
80 module PluginSpec : sig
81
82 type t
83
84 (* Main constructor, takes the format used in Declare ML Module.
85 With [usercode:true], warn instead of error on legacy syntax. *)
86 val of_package : ?usercode:bool -> string -> t
87
88 val to_package : t -> string
89
90 val is_loaded : t -> bool
91
92 (* Load a plugin, low-level, that is to say, will directly call the
93 loading mechanism in OCaml/findlib *)
94 val load : t -> unit
95
96 (* Compute a digest, a findlib library name have more than one
97 plugin .cmxs, however this is not the case in Rocq. Maybe we
98 should strengthen this invariant. *)
99 val digest : t -> Digest.t list
100
101 (** bool = true for implicit dependencies *)
102 val add_deps : t list -> (bool * t) list
103
104 val pp : t -> string
105
106 module Set : CSet.ExtS with type elt = t
107 module Map : CMap.ExtS with type key = t and module Set := Set
108
109 end = struct
110
111 type t = { lib : string }
112
113 let compare { lib = l1 } { lib = l2 } = String.compare l1 l2
114
115 module Self = struct
116 type nonrec t = t
117 let compare = compare
118 end
119
120 module Set = CSet.Make(Self)
121 module Map = CMap.Make(Self)
122
123 module Errors = struct
124
125 let warn_legacy_loading =
126 CWarnings.create ~name:"legacy-loading-removed" ~category:Deprecation.Version.v9_0
127 Pp.(fun name ->
128 str "Legacy loading plugin method has been removed from Rocq, \
129 and the `:` syntax is deprecated, and its first \
130 argument ignored; please remove \"" ++
131 str name ++ str ":\" from your Declare ML")
132
133 let plugin_name_invalid_format m =
134 CErrors.user_err
135 Pp.(str Format.(asprintf "%s is not a valid plugin name." m) ++ spc () ++
136 str "It should be a public findlib name, e.g. package-name.foo." ++ spc () ++
137 str "Legacy names followed by a findlib public name, e.g. "++ spc () ++
138 str "legacy_plugin:package-name.plugin," ++ spc() ++
139 str "are not supported anymore.")
140
141 let warn_coq_core =
142 CWarnings.create ~name:"coq-core-plugin" ~category:Deprecation.Version.v9_0
143 Pp.(fun () -> str "\"coq-core\" has been renamed to \"rocq-runtime\".")
144
145 end
146
147 (* We would properly load the rocq-runtime cmxs because of the
148 virtual coq-core findlib package, but we would not initialize the plugin.
149 eg [Declare ML Module "coq-core.plugins.ltac". Ltac foo := idtac.] would fail
150 as the grammar for Ltac is not activated. *)
151 let compat_coq_core lib =
152 let old_prefix = "coq-core.plugins." in
153 if CString.is_prefix old_prefix lib
154 then begin
155 Errors.warn_coq_core ();
156 let old_len = String.length old_prefix in
157 "rocq-runtime.plugins." ^ (CString.sub lib old_len (String.length lib - old_len))
158 end
159 else lib
160
161 let of_package ?(usercode=false) m =
162 let lib = match String.split_on_char ':' m with
163 | [ lib ] -> lib
164 | [cmxs; lib] when usercode ->
165 Errors.warn_legacy_loading cmxs;
166 lib
167 | _ -> Errors.plugin_name_invalid_format m
168 in
169 let lib = if usercode then compat_coq_core lib else lib in
170 { lib }
171
172 let to_package { lib } = lib
173
174 let is_loaded { lib } = Findlib.is_recorded_package lib
175
176 let load = function
177 | { lib } ->
178 if Findlib.is_recorded_package lib then
179 dbg_dynlink Pp.(fun () -> str lib ++ str " already loaded")
180 else begin
181 (* no point in using Fl_dynload since we [add_deps] to get digests *)
182 let plugins = Fl_internals.fl_find_plugins lib in
183 dbg_dynlink Pp.(fun () ->
184 str lib ++ str ": linking" ++ spc() ++
185 prlist_with_sep spc str plugins);
186 List.iter Dynlink.loadfile plugins;
187 Findlib.record_package Record_load lib
188 end
189
190 let add_deps plugins =
191 let explicit = Set.of_list plugins in
192 let preds = Findlib.recorded_predicates() in
193 let allplugins = Findlib.package_deep_ancestors preds (List.map to_package plugins) in
194 let deps = List.filter_map (fun lib ->
195 (* comes from findlib so guaranteed valid *)
196 let plugin = { lib } in
197 let explicit = Set.mem plugin explicit in
198 (* only add not-yet-loaded implicit deps *)
199 if not explicit && Findlib.is_recorded_package lib then None
200 else Some (not explicit, plugin))
201 allplugins
202 in
203 dbg_dynlink Pp.(fun () ->
204 str "for " ++ prlist_with_sep spc (fun {lib} -> str lib) plugins ++
205 str ":" ++ fnl() ++
206 v 2 (str "all deps:" ++ spc() ++ prlist_with_sep spc str allplugins) ++ fnl() ++
207 v 2 (str "filtered deps:" ++ spc() ++ prlist_with_sep spc (fun (_,{lib}) -> str lib) deps));
208 deps
209
210 let digest s =
211 match s with
212 | { lib } ->
213 let plugins = Fl_internals.fl_find_plugins lib in
214 List.map Digest.file plugins
215
216 let pp = function
217 | { lib } -> lib
218
219 end
220
221 (* If there is a toplevel under Rocq *)
222 type toplevel =
223 { load_plugin : PluginSpec.t -> unit
224 (** Load a findlib library, given by public name *)
225 ; load_module : string -> unit
226 (** Load a cmxs / cmo module, used by the native compiler to load objects *)
227 ; add_dir : string -> unit
228 (** Adds a dir to the module search path *)
229 ; ml_loop : ?init_file:string -> unit -> unit
230 (** Run the OCaml toplevel with given initialisation file *)
231 }
232
233 (* Determines the behaviour of Rocq with respect to ML files (compiled
234 or not) *)
235 type kind_load =
236 | WithTop of toplevel
237 | WithoutTop
238
239 (* Must be always initialized *)
240 let load = ref WithoutTop
241
242 (* Sets and initializes a toplevel (if any) *)
243 let set_top toplevel = load :=
244 WithTop toplevel;
245 Nativelib.load_obj := toplevel.load_module
246
247 (* Removes the toplevel (if any) *)
248 let remove () =
249 load := WithoutTop;
250 Nativelib.load_obj := (fun x -> () : string -> unit)
251
252 (* Tests if an Ocaml toplevel runs under Rocq *)
253 let is_ocaml_top () =
254 match !load with
255 | WithTop _ -> true
256 |_ -> false
257
258 (* Tests if we can load ML files *)
259 let has_dynlink = Coq_config.has_natdynlink || not Sys.(backend_type = Native)
260
261 (* Runs the toplevel loop of Ocaml *)
262 let ocaml_toploop ?init_file () =
263 match !load with
264 | WithTop t -> t.ml_loop ?init_file ()
265 | _ -> ()
266
267 let ml_load p =
268 match !load with
269 | WithTop t -> t.load_plugin p
270 | WithoutTop ->
271 PluginSpec.load p
272
273 let load_module x = match !load with
274 | WithTop t -> t.load_module x
275 | WithoutTop -> ()
276
277 (* Adds a path to the ML paths *)
278 let add_ml_dir s =
279 match !load with
280 | WithTop t -> t.add_dir s
281 | WithoutTop when has_dynlink -> ()
282 | _ -> ()
283
284 (** Init time functions *)
285
286 let initialized_plugins = Summary.ref ~stage:Synterp ~name:"inited-plugins" PluginSpec.Set.empty
287
288 let plugin_init_functions : (unit -> unit) list PluginSpec.Map.t ref = ref PluginSpec.Map.empty
289
290 let add_init_function name f =
291 let name = PluginSpec.of_package name in
292 if PluginSpec.Set.mem name !initialized_plugins
293 then CErrors.anomaly Pp.(str "Not allowed to add init function for already initialized plugin " ++ str (PluginSpec.pp name));
294 plugin_init_functions := PluginSpec.Map.update name (function
295 | None -> Some [f]
296 | Some g -> Some (f::g))
297 !plugin_init_functions
298
299 (** Registering functions to be used at caching time, that is when the Declare
300 ML module command is issued. *)
301
302 type cache_obj = CacheObj : { synterp : unit -> 'a; interp : 'a -> unit } -> cache_obj
303
304 let interp_only_obj interp = CacheObj { synterp = (fun () -> ()); interp }
305
306 let cache_objs = ref PluginSpec.Map.empty
307
308 let declare_cache_obj_full obj name =
309 let name = PluginSpec.of_package name in
310 let objs = try PluginSpec.Map.find name !cache_objs with Not_found -> [] in
311 let objs = obj :: objs in
312 cache_objs := PluginSpec.Map.add name objs !cache_objs
313
314 let declare_cache_obj f name =
315 declare_cache_obj_full (CacheObj {synterp = f; interp = (fun () -> ()) }) name
316
317 (* A little box to avoid getting confused with partially applied functions *)
318 type interp_fun = InterpFun of (unit -> unit)
319
320 let iter_interp_funs l =
321 InterpFun (fun () -> List.iter (fun (InterpFun f) -> f ()) l)
322
323 let perform_cache_obj name =
324 let objs = try PluginSpec.Map.find name !cache_objs with Not_found -> [] in
325 let objs = List.rev objs in
326 let v = List.map (fun (CacheObj {synterp; interp}) ->
327 let v = synterp () in
328 InterpFun (fun () -> interp v))
329 objs
330 in
331 iter_interp_funs v
332
333 (** ml object = ml module or plugin *)
334 let dinit = CDebug.create ~name:"mltop-init" ()
335
336 let init_ml_object mname =
337 if PluginSpec.Set.mem mname !initialized_plugins
338 then dinit Pp.(fun () -> str "already initialized " ++ str (PluginSpec.pp mname))
339 else begin
340 dinit Pp.(fun () -> str "initing " ++ str (PluginSpec.pp mname));
341 let n = match PluginSpec.Map.find mname !plugin_init_functions with
342 | l -> List.iter (fun f -> f()) (List.rev l); List.length l
343 | exception Not_found -> 0
344 in
345 initialized_plugins := PluginSpec.Set.add mname !initialized_plugins;
346 dinit Pp.(fun () -> str "finished initing " ++ str (PluginSpec.pp mname) ++ str " (" ++ int n ++ str " init functions)")
347 end
348
349 let load_ml_object mname =
350 ml_load mname
351
352 (* Summary of declared ML Modules *)
353
354 (* List and not String.Set because order is important: most recent first. *)
355
356 let loaded_modules = ref []
357
358 let get_loaded_modules () = List.rev !loaded_modules
359
360 (* XXX: It seems this should be part of trigger_ml_object, and
361 moreover we should check the guard there *)
362 let add_loaded_module md =
363 if not (List.mem md !loaded_modules) then
364 loaded_modules := md :: !loaded_modules
365
366 let reset_loaded_modules () = loaded_modules := []
367
368 type load_request =
369 | Summary
370 | Regular of { implicit : bool }
371
372 let if_verbose_load req f name =
373 match req with
374 | Regular {implicit} when not !Flags.quiet -> begin
375 let info =
376 str "[Loading ML file " ++ str (PluginSpec.pp name) ++
377 (if implicit then str " (implicit dependency)" else mt()) ++ str " ..." in
378 try
379 let path = f name in
380 Feedback.msg_info (info ++ str " done]");
381 path
382 with reraise ->
383 Feedback.msg_info (info ++ str " failed]");
384 raise reraise
385 end
386 | Summary | Regular _ -> f name
387
388 (** Load a module for the first time (i.e. dynlink it) *)
389
390 let trigger_ml_object (req, plugin) =
391 let () =
392 if not @@ PluginSpec.is_loaded plugin then begin
393 if not has_dynlink then
394 CErrors.user_err
395 (str "Dynamic link not supported (module " ++ str (PluginSpec.pp plugin) ++ str ").")
396 else
397 if_verbose_load req load_ml_object plugin
398 end
399 in
400 add_loaded_module plugin
401
402 let unfreeze_ml_modules x =
403 reset_loaded_modules ();
404 List.iter
405 (fun name ->
406 let name = PluginSpec.of_package name in
407 trigger_ml_object (Summary, name)) x
408
409 (* Beware of the order to avoid double-locking *)
410 let unfreeze_ml_modules = Util.atomify unfreeze_ml_modules
411
412 let trigger_ml_object req plugin =
413 Util.atomify trigger_ml_object (req, plugin)
414
415 let () =
416 Summary.declare_ml_modules_summary
417 { stage = Summary.Stage.Synterp
418 ; Summary.freeze_function = (fun () ->
419 get_loaded_modules () |> List.map PluginSpec.to_package)
420 ; Summary.unfreeze_function = unfreeze_ml_modules
421 ; Summary.init_function = reset_loaded_modules }
422
423 (* Liboject entries of declared ML Modules *)
424 type ml_module_object =
425 { mlocal : Vernacexpr.locality_flag
426 ; mnames : (bool * PluginSpec.t) list
427 (* bool: if true then implicit dep
428 XXX should we init_ml_object even for implicit deps? *)
429 ; mdigests : Digest.t list
430 }
431
432 let cache_ml_objects mnames =
433 let map (implicit,obj) =
434 trigger_ml_object (Regular {implicit}) obj;
435 if implicit then None else begin
436 init_ml_object obj;
437 Some (perform_cache_obj obj)
438 end
439 in
440 let v = List.filter_map map mnames in
441 iter_interp_funs v
442
443 let run_interp_fun (InterpFun f) = f ()
444
445 let load_ml_objects _ {mnames; _} =
446 let iter (implicit,obj) =
447 trigger_ml_object (Regular {implicit}) obj;
448 if not implicit then init_ml_object obj
449 in
450 List.iter iter mnames
451
452 let classify_ml_objects {mlocal=mlocal} =
453 if mlocal then Libobject.Dispose else Libobject.Substitute
454
455 let inMLModule : ml_module_object -> Libobject.obj =
456 let open Libobject in
457 declare_object
458 {(default_object "ML-MODULE") with
459 object_stage = Summary.Stage.Synterp;
460 cache_function = (fun _ -> ());
461 load_function = load_ml_objects;
462 subst_function = (fun (_,o) -> o);
463 classify_function = classify_ml_objects }
464
465 let declare_ml_modules local mnames =
466 let mnames = List.map (PluginSpec.of_package ~usercode:true) mnames in
467 if Lib.sections_are_opened()
468 then CErrors.user_err Pp.(str "Cannot Declare ML Module while sections are opened.");
469 let mnames = PluginSpec.add_deps mnames in
470 let mdigests = CList.concat_map (fun (_,plugin) -> PluginSpec.digest plugin) mnames in
471 Lib.add_leaf (inMLModule {mlocal=local; mnames; mdigests});
472 (* We can't put this in cache_function: it may declare other
473 objects, and when the current module is required we want to run
474 the ML-MODULE object before them. *)
475 cache_ml_objects mnames
476
477 (* Printing of loaded ML modules *)
478
479 let print_ml_modules () =
480 let l = get_loaded_modules () in
481 str"Loaded ML Modules: " ++ pr_vertical_list str (List.map PluginSpec.pp l)
482
483 let print_gc () =
484 let stat = Gc.stat () in
485 let msg =
486 str "minor words: " ++ real stat.Gc.minor_words ++ fnl () ++
487 str "promoted words: " ++ real stat.Gc.promoted_words ++ fnl () ++
488 str "major words: " ++ real stat.Gc.major_words ++ fnl () ++
489 str "minor_collections: " ++ int stat.Gc.minor_collections ++ fnl () ++
490 str "major_collections: " ++ int stat.Gc.major_collections ++ fnl () ++
491 str "heap_words: " ++ int stat.Gc.heap_words ++ fnl () ++
492 str "heap_chunks: " ++ int stat.Gc.heap_chunks ++ fnl () ++
493 str "live_words: " ++ int stat.Gc.live_words ++ fnl () ++
494 str "live_blocks: " ++ int stat.Gc.live_blocks ++ fnl () ++
495 str "free_words: " ++ int stat.Gc.free_words ++ fnl () ++
496 str "free_blocks: " ++ int stat.Gc.free_blocks ++ fnl () ++
497 str "largest_free: " ++ int stat.Gc.largest_free ++ fnl () ++
498 str "fragments: " ++ int stat.Gc.fragments ++ fnl () ++
499 str "compactions: " ++ int stat.Gc.compactions ++ fnl () ++
500 str "top_heap_words: " ++ int stat.Gc.top_heap_words ++ fnl () ++
501 str "stack_size: " ++ int stat.Gc.stack_size
502 in
503 hv 0 msg