Debian Codegraph @

vernac/synterp.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 CAst
14 open Util
15 open Names
16 open Libnames
17 open Vernacexpr
18 open Locality
19 open Attributes
20
21 let get_default_proof_mode = Pvernac.get_default_proof_mode
22
23 let module_locality = Attributes.Notations.(locality >>= fun l -> return (make_module_locality l))
24
25 let with_locality ~atts f =
26 let local = Attributes.(parse locality atts) in
27 f ~local
28
29 let with_module_locality ~atts f =
30 let module_local = Attributes.(parse module_locality atts) in
31 f ~module_local
32
33 let warn_legacy_export_set =
34 CWarnings.create ~name:"legacy-export-set" ~category:Deprecation.Version.v8_18
35 Pp.(fun () -> strbrk "Syntax \"Export Set\" is deprecated, use the attribute syntax \"#[export] Set\" instead.")
36
37 let deprecated_nonuniform =
38 CWarnings.create ~name:"deprecated-nonuniform-attribute"
39 ~category:Deprecation.Version.v8_18
40 Pp.(fun () -> strbrk "Attribute '#[nonuniform]' is deprecated, \
41 use '#[warning=\"-uniform-inheritance\"]' instead.")
42
43 let warnings_att =
44 Attributes.attribute_of_list [
45 "warnings", Attributes.payload_parser ~cat:(^) ~name:"warnings";
46 "warning", Attributes.payload_parser ~cat:(^) ~name:"warning";
47 ]
48
49 let with_generic_atts ~check atts f =
50 let atts, warnings = Attributes.parse_with_extra warnings_att atts in
51 let atts, nonuniform = Attributes.parse_with_extra ComCoercion.nonuniform atts in
52 let warnings =
53 let () = if nonuniform <> None && check then deprecated_nonuniform () in
54 if nonuniform <> Some true then warnings else
55 let ui = "-uniform-inheritance" in
56 Some (match warnings with Some w -> w ^ "," ^ ui | None -> ui) in
57 match warnings with
58 | None -> f ~atts
59 | Some warnings ->
60 if check then CWarnings.check_unknown_warnings warnings;
61 CWarnings.with_warn warnings (fun () -> f ~atts) ()
62
63 type module_entry = Modintern.module_struct_expr * Names.ModPath.t * Modintern.module_kind * Entries.inline
64
65 type synterp_entry =
66 | EVernacNoop
67 | EVernacNotation of { local : bool; decl : Metasyntax.notation_interpretation_decl }
68 | EVernacBeginSection of lident
69 | EVernacEndSegment of lident
70 | EVernacRequire of
71 Library.library_t list * DirPath.t list * export_with_cats option * (qualid * import_filter_expr) list
72 | EVernacImport of (export_flag *
73 Libobject.open_filter) *
74 (Names.ModPath.t CAst.t * import_filter_expr) list
75 | EVernacDeclareMLModule of Mltop.interp_fun
76 | EVernacDeclareModule of Lib.export * lident *
77 Declaremods.module_params_expr *
78 module_entry
79 | EVernacDefineModule of Lib.export * lident *
80 Declaremods.module_params_expr *
81 ((export_flag * Libobject.open_filter) * Names.ModPath.t) list *
82 module_entry Declaremods.module_signature *
83 module_entry list
84 | EVernacDeclareModuleType of lident *
85 Declaremods.module_params_expr *
86 ((export_flag * Libobject.open_filter) * Names.ModPath.t) list *
87 module_entry list *
88 module_entry list
89 | EVernacInclude of Declaremods.module_expr list
90 | EVernacSetOption of { export : bool; key : Goptions.option_name; value : Vernacexpr.option_setting }
91 | EVernacLoad of Vernacexpr.verbose_flag * (vernac_control_entry * Vernacstate.Synterp.t) list
92 | EVernacExtend of Vernactypes.typed_vernac
93
94 and vernac_entry = synterp_entry Vernacexpr.vernac_expr_gen
95
96 and vernac_control_entry =
97 (Vernacstate.Synterp.t VernacControl.control_entry, synterp_entry)
98 Vernacexpr.vernac_control_gen_r CAst.t
99
100 let synterp_reserved_notation ~module_local ~infix l =
101 Metasyntax.add_reserved_notation ~local:module_local ~infix l
102
103 let synterp_custom_entry ~module_local s =
104 Metasyntax.declare_custom_entry module_local s
105
106 (* Assumes cats is irrelevant if f is ImportNames *)
107 let import_module_syntax_with_filter ~export cats m f =
108 match f with
109 | ImportAll -> Declaremods.Synterp.import_module cats ~export m
110 | ImportNames ns -> ()
111
112 let synterp_import_mod (export,cats) qid f =
113 let loc = qid.loc in
114 let m = try Nametab.locate_module qid
115 with Not_found ->
116 CErrors.user_err ?loc Pp.(str "Cannot find module " ++ pr_qualid qid)
117 in
118 import_module_syntax_with_filter ~export cats m f; m
119
120 let synterp_import_cats cats =
121 Option.cata
122 (fun cats -> Libobject.make_filter ~finite:(not cats.negative) cats.import_cats)
123 Libobject.unfiltered
124 cats
125
126 let check_no_filter_when_using_cats l =
127 List.iter (function
128 | _, ImportAll -> ()
129 | q, ImportNames _ ->
130 CErrors.user_err ?loc:q.loc
131 Pp.(str "Cannot combine importing by categories and importing by names."))
132 l
133
134 let synterp_import export refl =
135 if Option.has_some (snd export) then check_no_filter_when_using_cats refl;
136 let export = on_snd synterp_import_cats export in
137 export, List.map (fun (qid,f) -> CAst.make ?loc:qid.loc @@ synterp_import_mod export qid f, f) refl
138
139 let synterp_define_module export {loc;v=id} (binders_ast : module_binder list) mty_ast_o mexpr_ast_l =
140 if Lib.sections_are_opened () then
141 user_err Pp.(str "Modules and Module Types are not allowed inside sections.");
142 let export = Option.map (on_snd synterp_import_cats) export in
143 match mexpr_ast_l with
144 | [] ->
145 let binders_ast,argsexport =
146 List.fold_right
147 (fun (export,idl,ty) (args,argsexport) ->
148 (idl,ty)::args, (List.map (fun {v=i} -> Option.map (on_snd synterp_import_cats) export,i)idl)@argsexport) binders_ast
149 ([],[]) in
150 let mp, args, sign = Declaremods.Synterp.start_module export id binders_ast mty_ast_o in
151 let argsexports = List.map_filter
152 (fun (export,id) ->
153 Option.map (fun export ->
154 export, synterp_import_mod export (qualid_of_ident id) ImportAll
155 ) export
156 ) argsexport
157 in
158 export, args, argsexports, [], sign
159 | _::_ ->
160 let binders_ast = List.map
161 (fun (export,idl,ty) ->
162 if not (Option.is_empty export) then
163 user_err Pp.(str "Arguments of a functor definition can be imported only if the definition is interactive. Remove the \"Export\" and \"Import\" keywords from every functor argument.")
164 else (idl,ty)) binders_ast in
165 let mp, args, expr, sign =
166 Declaremods.Synterp.declare_module
167 id binders_ast mty_ast_o mexpr_ast_l
168 in
169 Option.iter (fun (export,cats) ->
170 ignore (synterp_import_mod (export,cats) (qualid_of_ident id) ImportAll)) export;
171 export, args, [], expr, sign
172
173 let synterp_declare_module_type_syntax {loc;v=id} binders_ast mty_sign mty_ast_l =
174 if Lib.sections_are_opened () then
175 user_err Pp.(str "Modules and Module Types are not allowed inside sections.");
176 match mty_ast_l with
177 | [] ->
178 let binders_ast,argsexport =
179 List.fold_right
180 (fun (export,idl,ty) (args,argsexport) ->
181 (idl,ty)::args, (List.map (fun {v=i} -> Option.map (on_snd synterp_import_cats) export,i)idl)@argsexport) binders_ast
182 ([],[]) in
183
184 let mp, args, sign = Declaremods.Synterp.start_modtype id binders_ast mty_sign in
185 let argsexport =
186 List.map_filter
187 (fun (export,id) ->
188 Option.map
189 (fun export -> export, synterp_import_mod export (qualid_of_ident ?loc id) ImportAll) export
190 ) argsexport
191 in
192 args, argsexport, [], sign
193 | _ :: _ ->
194 let binders_ast = List.map
195 (fun (export,idl,ty) ->
196 if not (Option.is_empty export) then
197 user_err Pp.(str "Arguments of a functor definition can be imported only if the definition is interactive. Remove the \"Export\" and \"Import\" keywords from every functor argument.")
198 else (idl,ty)) binders_ast in
199 let mp, args, expr, sign = Declaremods.Synterp.declare_modtype id binders_ast mty_sign mty_ast_l in
200 args, [], expr, sign
201
202 let synterp_declare_module export {loc;v=id} binders_ast mty_ast =
203 let binders_ast = List.map
204 (fun (export,idl,ty) ->
205 if not (Option.is_empty export) then
206 user_err Pp.(str "Arguments of a functor declaration cannot be exported. Remove the \"Export\" and \"Import\" keywords from every functor argument.")
207 else (idl,ty)) binders_ast in
208 let mp, args, expr, sign =
209 Declaremods.Synterp.declare_module id binders_ast (Declaremods.Enforce mty_ast) []
210 in
211 assert (List.is_empty expr);
212 let sign = match sign with Declaremods.Enforce x -> x | _ -> assert false in
213 let export = Option.map (on_snd synterp_import_cats) export in
214 Option.iter (fun export -> ignore @@ synterp_import_mod export (qualid_of_ident id) ImportAll) export;
215 mp, export, args, sign
216
217 let synterp_include l = Declaremods.Synterp.declare_include l
218
219 let synterp_end_module export {loc;v=id} =
220 let _ = Declaremods.Synterp.end_module () in
221 Option.map (fun export -> synterp_import_mod export (qualid_of_ident ?loc id) ImportAll) export
222
223 let synterp_end_section {CAst.loc; v} =
224 Dumpglob.dump_reference ?loc
225 (DirPath.to_string (Lib.current_dirpath true)) "<>" "sec";
226 Declaremods.Synterp.close_section ()
227
228 let synterp_end_segment ({v=id;loc} as lid) =
229 let ss = Lib.Synterp.find_opening_node ?loc id in
230 match ss with
231 | Lib.OpenedModule (false,export,_,_) -> ignore (synterp_end_module export lid)
232 | Lib.OpenedModule (true,_,_,_) -> ignore (Declaremods.Synterp.end_modtype ())
233 | Lib.OpenedSection _ -> synterp_end_section lid
234 | _ -> assert false
235
236 let err_unmapped_library ?from qid =
237 let prefix = match from with
238 | None -> mt ()
239 | Some from ->
240 str " with prefix " ++ DirPath.print from
241 in
242 strbrk "Cannot find a physical path bound to logical path "
243 ++ pr_qualid qid ++ prefix ++ str "."
244
245 let err_notfound_library ?from qid =
246 let prefix = match from with
247 | None -> mt ()
248 | Some from -> str " with prefix " ++ DirPath.print from
249 in
250 let bonus =
251 if !Loadpath.load_vos_libraries then mt ()
252 else str " (while searching for a .vos file)"
253 in
254 strbrk "Unable to locate library " ++ pr_qualid qid ++ prefix ++ bonus
255 ++ str "."
256
257 exception UnmappedLibrary of Names.DirPath.t option * Libnames.qualid
258 exception NotFoundLibrary of Names.DirPath.t option * Libnames.qualid
259
260
261 let _ = CErrors.register_handler begin function
262 | UnmappedLibrary (from, qid) -> Some (err_unmapped_library ?from qid)
263 | NotFoundLibrary (from, qid) -> Some (err_notfound_library ?from qid)
264 | _ -> None
265 end
266
267 let warn_deprecated_from_Coq =
268 CWarnings.create ~name:"deprecated-from-Coq"
269 ~category:Deprecation.Version.v9_0
270 ~quickfix:(fun ~loc qid -> [Quickfix.make ~loc (Libnames.pr_qualid qid)])
271 (fun (_qid : qualid) -> strbrk
272 "\"From Coq\" has been replaced by \"From Stdlib\".")
273
274 let deprecated_Coq from qidl =
275 let coq_id = Id.of_string "Coq" in
276 let stdlib_id =
277 (* temporary hack to enable HoTT and UniMath to compile with rocq-core *)
278 let qidl =
279 let qid2idl qid =
280 let p, id = Libnames.repr_qualid qid in
281 List.rev (id :: DirPath.repr p) in
282 let from = match from with None -> [] | Some from -> qid2idl from in
283 List.map (fun (qid, _) -> from @ qid2idl qid) qidl in
284 let ids' = List.map Id.of_string ["Init"; "Setoids"; "Ltac"] in
285 let in_rocq idl = match idl with
286 | id :: id' :: _ -> Id.equal id coq_id && (CList.mem_f Id.equal id' ids')
287 | _ -> false in
288 Id.of_string (if List.for_all in_rocq qidl then "Corelib" else "Stdlib") in
289 let repl_id id =
290 if Id.equal id coq_id then true, stdlib_id else false, id in
291 let repl_Coq_qid qid =
292 let p, id = Libnames.repr_qualid qid in
293 let warn, p, id =
294 if DirPath.is_empty p then let w, id = repl_id id in w, p, id else
295 let warn, p = match List.rev (DirPath.repr p) with
296 | id :: p' -> let w, id' = repl_id id in w, (id' :: p')
297 | [] -> false, [] in
298 warn, DirPath.make (List.rev p), id in
299 let qid = Libnames.make_qualid ?loc:qid.loc p id in
300 let warn = if warn then Some qid else None in
301 warn, Libnames.make_qualid ?loc:qid.loc p id in
302 let warn, from, qidl = match from with
303 | Some from -> let w, from = repl_Coq_qid from in w, Some from, qidl
304 | None ->
305 let w, qidl = CList.fold_left_map (fun w (qid, fe) ->
306 let w', qid = repl_Coq_qid qid in Option.append w w', (qid, fe))
307 None qidl in
308 w, from, qidl in
309 let () = warn |> Option.iter (fun qid -> warn_deprecated_from_Coq ?loc:qid.loc qid) in
310 from, qidl
311
312 let synterp_require ~intern from export qidl =
313 let from, qidl = deprecated_Coq from qidl in
314 let root = match from with
315 | None -> None
316 | Some from ->
317 let (hd, tl) = Libnames.repr_qualid from in
318 Some (Libnames.add_dirpath_suffix hd tl)
319 in
320 let locate (qid,_) =
321 let open Loadpath in
322 match locate_qualified_library ?root qid with
323 | Ok (dir,_) -> (qid.loc, dir)
324 | Error LibUnmappedDir -> Loc.raise ?loc:qid.loc (UnmappedLibrary (root, qid))
325 | Error LibNotFound -> Loc.raise ?loc:qid.loc (NotFoundLibrary (root, qid))
326 in
327 let modrefl = List.map locate qidl in
328 Coq_config.gc_ramp_up @@ fun () ->
329 let filenames = Library.require_library_syntax_from_dirpath ~intern modrefl in
330 Option.iter (fun (export,cats) ->
331 let cats = synterp_import_cats cats in
332 List.iter2 (fun (_, m) (_, f) ->
333 import_module_syntax_with_filter ~export cats (MPfile m) f)
334 modrefl qidl)
335 export;
336 filenames, List.map snd modrefl
337
338 (*****************************)
339 (* Auxiliary file management *)
340
341 let expand filename =
342 Envars.expand_path_macros ~warn:(fun x -> Feedback.msg_warning (str x)) filename
343
344 let synterp_declare_ml_module ~local l =
345 let local = Option.default false local in
346 Mltop.declare_ml_modules local l
347
348 let warn_chdir = CWarnings.create ~name:"change-dir-deprecated" ~category:Deprecation.Version.v8_20
349 (fun () -> strbrk "Command \"Cd\" is deprecated." ++ spc () ++
350 strbrk "Use command-line \"-output-directory dir\" instead, or, alternatively, " ++
351 strbrk "for extraction, \"Set Extraction Output Directory\".")
352
353 let synterp_chdir = function
354 | None -> Feedback.msg_notice (str (Sys.getcwd()))
355 | Some path ->
356 warn_chdir ();
357 begin
358 try Sys.chdir (expand path)
359 with Sys_error err ->
360 (* Cd is typically used to control the output directory of
361 extraction. A failed Cd could lead to overwriting .ml files
362 so we make it an error. *)
363 user_err Pp.(str ("Cd failed: " ^ err))
364 end;
365 Flags.if_verbose Feedback.msg_info (str (Sys.getcwd()))
366
367 (* External dependencies *)
368
369 let synterp_extra_dep ?loc from file id =
370 if Lib.sections_are_opened () then
371 user_err ?loc Pp.(str "Extra Dependencies cannot be declared inside sections.");
372 let hd, tl = Libnames.repr_qualid from in
373 let from = Libnames.add_dirpath_suffix hd tl in
374 ComExtraDeps.declare_extra_dep ?loc ~from ~file id
375
376 let synterp_begin_section ({v=id} as lid) =
377 Dumpglob.dump_definition lid true "sec";
378 Lib.Synterp.open_section id
379
380 let with_synterp_state =
381 let with_local_state () f =
382 let st = Vernacstate.Synterp.freeze () in
383 let v = f () in
384 let transient_st = Vernacstate.Synterp.freeze () in
385 Vernacstate.Synterp.unfreeze st;
386 transient_st, v
387 in
388 { VernacControl.with_local_state }
389
390 let rec synterp ~intern ?loc ~atts v =
391 match v with
392 | VernacSynterp v0 ->
393 let e = begin match v0 with
394 | VernacReservedNotation (infix, sl) ->
395 with_module_locality ~atts synterp_reserved_notation ~infix sl;
396 EVernacNoop
397 | VernacNotation (infix,ntn_decl) ->
398 let local, user_warns = Attributes.(parse Notations.(module_locality ++ user_warns) atts) in
399 let decl = Metasyntax.add_notation_syntax ~local ~infix user_warns ntn_decl in
400 EVernacNotation { local; decl }
401 | VernacDeclareCustomEntry s ->
402 with_module_locality ~atts synterp_custom_entry s;
403 EVernacNoop
404 | VernacDefineModule (export,lid,bl,mtys,mexprl) ->
405 let export, args, argsexport, expr, sign = synterp_define_module export lid bl mtys mexprl in
406 EVernacDefineModule (export,lid,args,argsexport,sign,expr)
407 | VernacDeclareModuleType (lid,bl,mtys,mtyo) ->
408 let args, argsexport, expr, sign = synterp_declare_module_type_syntax lid bl mtys mtyo in
409 EVernacDeclareModuleType (lid,args,argsexport,sign,expr)
410 | VernacDeclareModule (export,lid,bl,mtyo) ->
411 let mp, export, args, sign =
412 synterp_declare_module export lid bl mtyo
413 in
414 EVernacDeclareModule (export,lid,args,sign)
415 | VernacInclude in_asts ->
416 EVernacInclude (synterp_include in_asts)
417 | VernacBeginSection lid ->
418 synterp_begin_section lid;
419 EVernacBeginSection lid
420 | VernacEndSegment lid ->
421 synterp_end_segment lid;
422 EVernacEndSegment lid
423 | VernacRequire (from, export, qidl) ->
424 let needed, modrefl = synterp_require ~intern from export qidl in
425 EVernacRequire (needed, modrefl, export, qidl)
426 | VernacImport (export,qidl) ->
427 let export, mpl = synterp_import export qidl in
428 EVernacImport (export,mpl)
429 | VernacDeclareMLModule l ->
430 let f = with_locality ~atts synterp_declare_ml_module l in
431 EVernacDeclareMLModule f
432 | VernacChdir s ->
433 unsupported_attributes atts;
434 synterp_chdir s;
435 EVernacNoop
436 | VernacExtraDependency(from,file,id) ->
437 unsupported_attributes atts;
438 synterp_extra_dep ?loc from file id;
439 EVernacNoop
440
441 | VernacSetOption (export,key,value) ->
442 let atts = if export then begin
443 warn_legacy_export_set ?loc ();
444 CAst.make ?loc ("export", VernacFlagEmpty) :: atts
445 end
446 else atts
447 in
448 let locality = parse option_locality atts in
449 Vernacoptions.vernac_set_option ~locality ~stage:Summary.Stage.Synterp key value;
450 EVernacSetOption { export; key; value }
451 | VernacProofMode mn ->
452 unsupported_attributes atts;
453 EVernacNoop
454 | VernacLoad (verbosely, fname) ->
455 unsupported_attributes atts;
456 synterp_load ~intern verbosely fname
457 | VernacExtend (opn,args) ->
458 let f = Vernacextend.type_vernac ?loc ~atts opn args () in
459 EVernacExtend(f)
460 end in
461 VernacSynterp e
462 | VernacSynPure x -> VernacSynPure x
463
464 and synterp_load ~intern verbosely fname =
465 let fname =
466 Envars.expand_path_macros ~warn:(fun x -> Feedback.msg_warning (Pp.str x)) fname in
467 let fname = CUnix.make_suffix fname ".v" in
468 let input =
469 let longfname = Loadpath.locate_file fname in
470 let in_chan = Util.open_utf8_file_in longfname in
471 Procq.Parsable.make ~loc:Loc.(initial (InFile { dirpath=None; file=longfname}))
472 (Gramlib.Stream.of_channel in_chan) in
473 (* Parsing loop *)
474 let v_mod = if verbosely then Flags.verbosely else Flags.silently in
475 let parse_sentence proof_mode =
476 Procq.Entry.parse (Pvernac.main_entry proof_mode)
477 in
478 let proof_mode = Some (get_default_proof_mode ()) in
479 let rec load_loop entries =
480 match parse_sentence proof_mode input with
481 | None -> entries
482 | Some cmd ->
483 let entry = v_mod (synterp_control ~intern) cmd in
484 let st = Vernacstate.Synterp.freeze () in
485 (load_loop [@ocaml.tailcall]) ((entry,st)::entries)
486 in
487 let entries = List.rev @@ load_loop [] in
488 EVernacLoad(verbosely, entries)
489
490 and synterp_control ~intern CAst.{ loc; v = cmd } =
491 let fn expr =
492 with_generic_atts ~check:true cmd.attrs (fun ~atts ->
493 synterp ~intern ?loc ~atts cmd.expr)
494 in
495 let control, expr =
496 VernacControl.under_control ~loc ~with_local_state:with_synterp_state
497 (VernacControl.from_syntax cmd.control)
498 ~noop:(VernacSynterp EVernacNoop)
499 (fun () -> fn cmd.expr)
500 in
501 CAst.make ?loc { expr; control; attrs = cmd.attrs }
502
503 let synterp_control ~intern cmd =
504 Flags.with_modified_ref Flags.in_synterp_phase (fun _ -> Some true) (synterp_control ~intern) cmd