Debian Codegraph @

src/rocq_elpi_vernacular.ml

raw symbols SCIP
1 (* rocq-elpi: Coq terms as the object language of elpi *)
2 (* license: GNU Lesser General Public License Version 2.1 or later *)
3 (* ------------------------------------------------------------------------- *)
4
5 module API = Elpi.API
6 module EC = API.Compile
7 module EPP = API.Pp
8 module EU = API.Utils
9 module ET = API.RawData
10
11 open Rocq_elpi_utils
12 open Rocq_elpi_arg_HOAS
13 module Programs = Rocq_elpi_programs
14
15 (* ******************** Vernacular commands ******************************* *)
16
17 open Programs
18
19 let default_max_step = max_int
20
21 let main_quotedc = ET.Constants.declare_global_symbol "main-quoted"
22 let mainc = ET.Constants.declare_global_symbol "main"
23 let main_interpc = ET.Constants.declare_global_symbol "main-interp"
24 let main_interp_proofc = ET.Constants.declare_global_symbol "main-interp-proof"
25 let main_interp_qedc = ET.Constants.declare_global_symbol "main-interp-qed"
26 let main_synterpc = ET.Constants.declare_global_symbol "main-synterp"
27 let attributesc = ET.Constants.declare_global_symbol "attributes"
28
29 [%%if coq = "9.0" || coq = "9.1"]
30 exception ParseError = Gramlib.Grammar.Error
31 [%%else]
32 exception ParseError = Gramlib.Grammar.ParseError
33 [%%endif]
34
35 let atts2impl ~depth loc phase
36 state atts q =
37 let open Rocq_elpi_builtins_synterp in
38 let rec convert_att_r = function
39 | (name,Attributes.VernacFlagEmpty) -> name, AttributeEmpty
40 | (name,Attributes.VernacFlagList l) -> name, AttributeList (convert_atts l)
41 | (name,Attributes.VernacFlagLeaf v) -> name, AttributeLeaf (convert_att_value v)
42 and convert_att att = convert_att_r att.CAst.v
43 and convert_atts l = List.map convert_att l
44 and convert_att_value = function
45 | Attributes.FlagQualid q -> AttributeString (Libnames.string_of_qualid q)
46 | Attributes.FlagString s -> AttributeString s
47 in
48 let phase = match phase with Summary.Stage.Interp -> "interp" | Summary.Stage.Synterp -> "synterp" in
49 let atts =
50 ("elpi.loc", AttributeLeaf (AttributeLoc loc)) ::
51 ("elpi.phase", AttributeLeaf (AttributeString phase)) ::
52 convert_atts atts in
53 let atts =
54 match Sys.getenv_opt "COQ_ELPI_ATTRIBUTES" with
55 | None -> atts
56 | Some txt ->
57 match Procq.parse_string (Pvernac.main_entry None) (Printf.sprintf "#[%s] Qed." txt) |> Option.map (fun x -> x.CAst.v) with
58 | None -> atts
59 | Some { Vernacexpr.attrs ; _ } -> List.map (fun {CAst.v=(name,v)} -> convert_att_r ("elpi."^name,v)) attrs @ atts
60 | exception ParseError msg ->
61 CErrors.user_err Pp.(str"Environment variable COQ_ELPI_ATTRIBUTES contains ill formed value:" ++ spc () ++ str txt ++ cut () ++ str msg) in
62 let state, atts, _ = EU.map_acc (Rocq_elpi_builtins_synterp.attribute.API.Conversion.embed ~depth) state atts in
63 let atts = ET.mkApp attributesc (EU.list_to_lp_list atts) [] in
64 state, ET.mkBuiltin ET.Impl [atts;q]
65
66 let same_phase y x =
67 match x, y with
68 | _, Both -> true
69 | Summary.Stage.Interp, Interp -> true
70 | Summary.Stage.Synterp, Synterp -> true
71 | _ -> false
72
73 let skip ?only ~ph ~phase f x =
74 let m rex = Str.string_match rex Coq_config.version 0 in
75 let exec1 =
76 match only with
77 | None -> true
78 | Some (None, None) -> true
79 | Some (Some skip, None) -> not (List.exists m skip)
80 | Some (None, Some keep) -> List.exists m keep
81 | Some (Some _, Some _) -> CErrors.user_err Pp.(str "Attributes #[skip] and #[only] cannot be used at the same time")
82 in
83 let exec2 =
84 match ph with
85 | None -> same_phase Interp phase
86 | Some ph -> same_phase ph phase
87 in
88 if exec1 && exec2 then f x else ()
89
90 type query =
91 | Ast of (API.Data.state -> API.Data.state) * API.Ast.query
92 | Fun of (API.Data.state -> API.Data.state * API.RawData.term * Elpi.API.Conversion.extra_goals)
93
94 type atts = ((clause_scope * (Str.regexp list option * Str.regexp list option)) * phase option)
95
96 let warn_scope_not_regular = CWarnings.create ~name:"elpi.accumulate-scope" ~category:elpi_cat (fun x -> x)
97 let warn_scope_not_regular ~loc = function
98 | Regular -> ()
99 | _ -> warn_scope_not_regular ~loc Pp.(str "Scope attribute not supported, this accumulation has a superglobal scope")
100
101 module Compiler(P : Programs) = struct
102
103 module Summary = struct
104 include Summary
105 let ref ?local ~name x = Summary.ref ~stage:P.stage ?local ~name:(P.in_stage name) x
106 end
107
108 let skip = skip ~phase:P.stage
109
110 let trace_options = Summary.ref ~name:"elpi-trace" []
111 let max_steps = Summary.ref ~name:"elpi-steps" default_max_step
112
113 let debug vl = P.debug_vars := List.fold_right EC.StrSet.add vl EC.StrSet.empty
114 let debug ~atts:ph vl = skip ~ph debug vl
115
116 let bound_steps n =
117 if n <= 0 then max_steps := default_max_step else max_steps := n
118 let bound_steps ~atts:ph n = skip ~ph bound_steps n
119
120 let trace_filename_gen (add_counter: string) =
121 "/tmp/traced.tmp" ^ (add_counter) ^ ".json"
122
123 let trace_filename = trace_filename_gen ""
124
125 let run ~loc program query =
126 let t1 = Unix.gettimeofday () in
127
128 let query =
129 handle_elpi_compiler_errors ~loc (fun () ->
130 match query with
131 | Ast (f,query_ast) -> API.RawQuery.compile_ast program query_ast f
132 | Fun query_builder -> API.RawQuery.compile_raw_term program query_builder) in
133 let t2 = Unix.gettimeofday () in
134 let _ = API.Setup.trace [] in
135 let t3 = Unix.gettimeofday () in
136 let leftovers = API.Setup.trace !trace_options in
137 if (!trace_options <> [] && Sys.file_exists trace_filename) then
138 Sys.command (Printf.sprintf "mv %s %s" trace_filename (trace_filename_gen (Printf.sprintf "_%.0f" @@ Unix.gettimeofday ()))) |> ignore;
139 if leftovers <> [] then
140 CErrors.user_err Pp.(str"Unknown trace options: " ++ prlist_with_sep spc str leftovers);
141 let exe = EC.optimize query in
142 let t4 = Unix.gettimeofday () in
143 let print_debug with_error =
144 let t5 = Unix.gettimeofday () in
145 let txt = Printf.sprintf "Elpi: query-compilation:%1.4f static-check:%1.4f optimization:%1.4f runtime:%1.4f %s\n"
146 (t2 -. t1) (t3 -. t2) (t4 -. t3) (t5 -. t4) (if with_error then "(with error)" else "(with success)") in
147 Rocq_elpi_utils.debug Pp.(fun () -> str txt);
148 Rocq_elpi_utils.elpitime Pp.(fun () -> str txt)
149 in
150 try
151 let rc = API.Execute.once ~max_steps:!max_steps exe in
152 print_debug false;
153 rc
154 with e ->
155 let e = Exninfo.capture e in
156 print_debug true;
157 Exninfo.iraise e
158 ;;
159
160 let elpi_fails program_name =
161 let open Pp in
162 let kind = "tactic/command" in
163 let name = show_qualified_name program_name in
164 CErrors.user_err (strbrk (String.concat " " [
165 "The elpi"; kind; name ;
166 "failed without giving a specific error message" ^ (Summary.Stage.(match P.stage with Interp -> "." | Synterp -> " (during the parsing phase, aka synterp)."));
167 "Please report this inconvenience to the authors of the program."
168 ]))
169
170 let run_and_print ~print ~loc program_name program_ast query_ast : _ * Rocq_elpi_builtins_synterp.SynterpAction.RZipper.zipper * API.State.t * ET.term API.Setup.StrMap.t * _ * _=
171 match run ~loc program_ast query_ast
172 with
173 | API.Execute.Failure -> elpi_fails program_name
174 | API.Execute.NoMoreSteps ->
175 CErrors.user_err Pp.(str "elpi run out of steps ("++int !max_steps++str")")
176 | API.Execute.Success {
177 assignments ; constraints; state; pp_ctx; relocate_assignment_to_runtime;
178 } ->
179 if print then begin
180 if not (API.Setup.StrMap.is_empty assignments) then begin
181 Feedback.msg_notice
182 Pp.(str"Query assignments:");
183 API.Setup.StrMap.iter (fun name term ->
184 Feedback.msg_notice
185 Pp.(str" " ++ str name ++ str " = " ++
186 str (pp2string (EPP.term pp_ctx) term)))
187 assignments;
188 end;
189 let scst = pp2string (EPP.constraints pp_ctx) constraints in
190 if scst <> "" then
191 Feedback.msg_notice Pp.(str"Syntactic constraints:" ++ spc()++str scst);
192 if P.stage = Summary.Stage.Interp then begin
193 let sigma = Rocq_elpi_HOAS.get_sigma state in
194 let ccst = Evd.ustate sigma in
195 if not (UState.is_empty ccst) then
196 Feedback.msg_notice Pp.(str"Universe constraints:" ++ spc() ++
197 UState.pr ccst);
198 end
199 end;
200 (* We add clauses declared via coq.elpi.accumulate *)
201 let clauses_to_add =
202 API.State.get
203 (match P.stage with
204 | Summary.Stage.Synterp -> Rocq_elpi_builtins_synterp.clauses_for_later_synterp
205 | Summary.Stage.Interp -> Rocq_elpi_builtins.clauses_for_later_interp)
206 state in
207
208 (* TODO: this code is duplicate, see set_accumulate_to_db_* *)
209 let elpi = P.ensure_initialized () in
210 let clauses_to_add = clauses_to_add |> group_clauses |>
211 List.map (fun (dbname,asts,vs,scope) ->
212 let base = P.get_and_compile_existing_db ~loc dbname in
213 (* maybe this should be a fold otherwise all clauses have to be independent (the second cannot mention the first one) *)
214 let scoped_asts = List.concat (List.map (EC.scope_ast ~elpi) asts) in
215 let units = scoped_asts |> List.map (P.unit_from_ast ~error_header:(Format.asprintf "accumulating clause to %s" (String.concat "." dbname)) ~elpi ~base ~loc) in
216 dbname,units,vs,scope) in
217 clauses_to_add |> List.iter (fun (dbname,units,vs,scope) ->
218 P.accumulate_units_to_db ~loc ~db:dbname ~units ~secvars:vs ~scope);
219 relocate_assignment_to_runtime,
220 (if P.stage = Summary.Stage.Synterp then
221 API.State.get Rocq_elpi_builtins_synterp.SynterpAction.log state |> Rocq_elpi_builtins_synterp.SynterpAction.RZipper.of_w
222 else
223 API.State.get Rocq_elpi_builtins_synterp.SynterpAction.read state),
224 state,
225 assignments,
226 constraints,
227 pp_ctx
228 ;;
229
230 let current_program = Summary.ref ~name:"elpi-cur-program-name" None
231 let set_current_program n =
232 current_program := Some n
233
234 let current_program () =
235 match !current_program with
236 | None -> CErrors.user_err Pp.(str "No current Elpi Program")
237 | Some x -> x
238
239
240 let run_in_program ~loc ?(program = current_program ()) ?(st_setup=fun _ x -> x) (qloc, query) =
241 let elpi = P.ensure_initialized () in
242 P.get_and_compile ~loc ~even_if_empty:true program |> Option.map (fun (base, _) ->
243 let query_ast = Ast (st_setup base, P.parse_goal ~loc ~elpi qloc query) in
244 run_and_print ~print:true ~loc program base query_ast |>
245 (fun (x,y,_,_,_,_) -> x,y))
246
247 let accumulate_extra_dep ~loc ~program ~scope ~what file =
248 if P.db_exists program then
249 P.accumulate_file_to_db ~loc ~db:program ~scope ~what ~file
250 else begin
251 warn_scope_not_regular ~loc scope;
252 P.accumulate_file_to_program ~loc ~program ~what ~file
253 end
254
255
256 let accumulate_elpifile ~loc ~program ~scope ~what ast =
257 if P.db_exists program then
258 P.accumulate_ast_to_db ~loc ~db:program ~what ~ast ~scope
259 else begin
260 warn_scope_not_regular ~loc scope;
261 P.accumulate_ast_to_program ~loc ~program ~what ~ast
262 end
263
264 let resolve_extra_dep_or_elpifile ~loc id =
265 let cid = Names.Id.of_string_soft (String.concat "." id) in
266 try `ExtraDep (ComExtraDeps.query_extra_dep cid)
267 with
268 | Failure s -> CErrors.user_err ~loc Pp.(str s)
269 | Not_found ->
270 try `ElpiFile (P.ast_of_elpifile id)
271 with
272 | Failure s -> CErrors.user_err Pp.(str s)
273 | Not_found when P.stage = Summary.Stage.Interp ->
274 CErrors.user_err ~loc Pp.(str"File " ++ Names.Id.print cid ++ str " not found")
275 | Not_found ->
276 err Pp.(str"File " ++ pr_qualified_name id ++
277 str" is unknown; please add a directive like 'From .. Extra Dependency .. as " ++
278 pr_qualified_name id ++ str"' or 'Elpi File .. lp:{{ ... }}'.")
279
280
281 let accumulate_extra_dep_or_elpifile ~loc ~program ~scope ~what id =
282 match resolve_extra_dep_or_elpifile ~loc id with
283 | `ExtraDep s -> accumulate_extra_dep ~loc ~program ~scope ~what s
284 | `ElpiFile s -> List.iter (accumulate_elpifile ~loc ~program ~scope ~what) s
285
286 let accumulate_extra_deps_or_elpifiles ~loc ?(program=current_program()) ~scope ~what ids =
287 ids |> List.iter (accumulate_extra_dep_or_elpifile ~loc ~program ~scope ~what)
288
289 let accumulate_extra_deps ~atts:((scope,only),ph) ~loc ?program ~what ids =
290 skip ~only ~ph (accumulate_extra_deps_or_elpifiles ~loc ?program ~scope ~what) ids
291
292
293 let accumulate_plugin ~loc ?(program=current_program()) ~scope id =
294 warn_scope_not_regular ~loc scope;
295 if P.db_exists program then
296 err ~loc:(of_coq_loc loc) Pp.(str "TODO")
297 else
298 let plugin =
299 try Elpi.API.BuiltIn.of_file id
300 with Not_found -> err ~loc:(of_coq_loc loc) Pp.(str "Elpi plugin " ++ str id ++
301 str " not found." ++ spc () ++ str "Did you have a Declare ML Module for the plugin?"++ spc () ++
302 str "Does the plugin run Elpi.API.BuiltIn.declare ~file_name:\"" ++ str id ++ str "\"?") in
303 P.accumulate_plugin_to_program ~loc ~program ~plugin
304
305 let accumulate_plugin ~atts:((scope,only),ph) ~loc ?program id = skip ~only ~ph (accumulate_plugin ~loc ?program ~scope) id
306
307 let accumulate_file ~loc ~program ~scope file =
308 let what = Rocq_elpi_programs.Code in
309 if P.db_exists program then
310 P.accumulate_file_to_db ~loc ~db:program ~file ~scope ~what
311 else begin
312 warn_scope_not_regular ~loc scope;
313 P.accumulate_file_to_program ~loc ~program ~file ~what
314 end
315
316 let accumulate_files ~loc ?(program=current_program()) ~scope sl = List.iter (accumulate_file ~loc ~program ~scope) sl
317 let accumulate_files ~atts:((scope,only),ph) ~loc ?program s = skip ~only ~ph (accumulate_files ~loc ?program ~scope) s
318
319 let accumulate_string ~loc ?(program=current_program()) ~scope code =
320 if P.db_exists program then
321 P.accumulate_string_to_db ~loc ~db:program ~code ~scope
322 else begin
323 warn_scope_not_regular ~loc scope;
324 P.accumulate_string_to_program ~loc ~program ~code
325 end
326
327 let accumulate_string ~atts:((scope,only),ph) ~loc ?program sloc = skip ~only ~ph (accumulate_string ~loc ?program ~scope) sloc
328
329
330 let accumulate_db ~loc ?(program=current_program()) db =
331 P.accumulate_db_to_program ~loc ~program ~db
332 let accumulate_db ~atts:((scope,only),ph) ~loc ?program name =
333 warn_scope_not_regular ~loc scope;
334 skip ~only ~ph (accumulate_db ~loc ?program) name
335
336 let accumulate_db_header ~loc ?(program=current_program()) ~scope name =
337 if P.db_exists name then
338 let header = P.header_of_db name in
339 if P.db_exists program then
340 P.accumulate_header_to_db ~loc ~db:program ~header ~scope
341 else
342 let () = warn_scope_not_regular ~loc scope in
343 P.accumulate_header_to_program ~loc ~program ~header
344 (* let units = List.map (fun dast -> DatabaseHeader { dast }) units in *)
345 else CErrors.user_err Pp.(str "Db " ++ pr_qualified_name name ++ str" not found")
346 let accumulate_db_header ~atts:((scope,only),ph) ~loc ?program name =
347 skip ~only ~ph (accumulate_db_header ~loc ?program ~scope) name
348
349 let accumulate_to_db ~loc db code ~scope idl =
350 P.accumulate_string_to_db ~loc ~code ~db ~scope
351 let accumulate_to_db ~atts:((scope,only),ph) ~loc db sloc idl = skip ~only ~ph (accumulate_to_db ~loc db sloc ~scope) idl
352
353
354 let mk_trace_opts start stop preds =
355 [ "-trace-on"
356 ; "-trace-at"; "run"; string_of_int start; string_of_int stop
357 ; "-trace-only"; "\\(run\\|select\\|user:\\)"
358 ; "-trace-tty-maxbox"; "30"
359 ] @ List.(flatten (map (fun x -> ["-trace-only-pred"; x]) preds))
360
361 let trace start stop preds opts =
362 if start = 0 && stop = 0 then trace_options := []
363 else trace_options := mk_trace_opts start stop preds @ opts
364 let trace ~atts start stop preds opts = skip ~ph:atts (trace start stop preds) opts
365
366 let trace_browser _opts =
367 trace_options :=
368 [ "-trace-on"; "json"; trace_filename
369 ; "-trace-at"; "run"; "0"; string_of_int max_int
370 ; "-trace-only"; "user"
371 ];
372 Feedback.msg_notice
373 Pp.(strbrk "Now click \"Start watching\" in the Elpi Trace Browser panel and then execute the Command/Tactic/Query you want to trace. Also try \"F1 Elpi\".")
374 let trace_browser ~atts opts = skip ~ph:atts trace_browser opts
375
376 let print ~loc ~name ~args output =
377 let program =
378 if P.db_exists name then
379 Some (P.get_and_compile_existing_db ~loc name)
380 else
381 Option.map fst @@ P.get_and_compile ~loc name in
382 program |> Option.iter @@ fun program ->
383 let fname =
384 Rocq_elpi_programs.resolve_file_path
385 ~must_exist:false ~allow_absolute:false ~only_elpi:false output
386 in
387 let fname_txt = fname ^ ".txt" in
388 let oc = open_out fname_txt in
389 let fmt = Format.formatter_of_out_channel oc in
390 EPP.program fmt program;
391 Format.pp_print_flush fmt ();
392 close_out oc
393 let print ~atts ~loc ~name ~args output =
394 skip ~ph:atts (print ~loc ~name ~args) output
395
396 let create_command ~atts:(raw_args) ~loc n =
397 let raw_args = Option.default false raw_args in
398 P.declare_program n (Command { raw_args });
399 P.init_command n ~loc;
400 set_current_program (snd n)
401
402 let create_tactic ~loc n =
403 P.declare_program n Tactic;
404 if P.stage = Summary.Stage.Interp then P.init_tactic n ~loc;
405 set_current_program (snd n)
406
407 let create_program ~atts:(raw_args) ~loc n ~init =
408 let raw_args = Option.default false raw_args in
409 P.declare_program n (Program { raw_args });
410 if P.stage = Summary.Stage.Interp then begin
411 P.init_program n ~loc init;
412 end;
413 set_current_program (snd n)
414
415 let create_db ~atts ~loc n ~init:(sloc,s) =
416 let do_init =
417 match atts with
418 | None -> same_phase Interp P.stage
419 | Some phase -> same_phase phase P.stage in
420 if do_init then begin
421 P.declare_db n;
422 P.init_db n ~loc (sloc,s)
423 end
424
425 let create_file ~atts ~loc n ~init:(sloc,s) =
426 let do_init =
427 match atts with
428 | None -> same_phase Interp P.stage
429 | Some phase -> same_phase phase P.stage in
430 if do_init then begin
431 P.declare_file n;
432 P.init_file ~loc n (sloc, s)
433 end
434
435 let load_command = P.load_command
436 let load_tactic = P.load_tactic
437
438 let get_and_compile ~loc qn = P.get_and_compile ?even_if_empty:None qn ~loc
439
440 end
441
442 module type Common = sig
443 val get_and_compile :
444 loc:Loc.t -> qualified_name -> (Elpi.API.Compile.program * bool) option
445 val run : loc:Loc.t ->
446 Elpi.API.Compile.program ->
447 query ->
448 Elpi.API.Execute.outcome
449
450 val accumulate_files : atts:atts -> loc:Loc.t -> ?program:qualified_name -> string list -> unit
451 val accumulate_extra_deps : atts:atts -> loc:Loc.t -> ?program:qualified_name -> what:what -> qualified_name list -> unit
452 val accumulate_plugin : atts:atts -> loc:Loc.t -> ?program:qualified_name -> string -> unit
453 val accumulate_string : atts:atts -> loc:Loc.t -> ?program:qualified_name -> Elpi.API.Ast.Loc.t * string -> unit
454 val accumulate_db : atts:atts -> loc:Loc.t -> ?program:qualified_name -> qualified_name -> unit
455 val accumulate_db_header : atts:atts -> loc:Loc.t -> ?program:qualified_name -> qualified_name -> unit
456 val accumulate_to_db : atts:atts -> loc:Loc.t -> qualified_name -> Elpi.API.Ast.Loc.t * string -> Names.Id.t list -> unit
457 val load_tactic : loc:Loc.t -> string -> unit
458 val load_command : loc:Loc.t -> string -> unit
459
460 val debug : atts:phase option -> string list -> unit
461 val trace : atts:phase option -> int -> int -> string list -> string list -> unit
462 val trace_browser : atts:phase option -> string list -> unit
463 val bound_steps : atts:phase option -> int -> unit
464 val print : atts:phase option -> loc:Loc.t -> name:qualified_name -> args:string list -> string -> unit
465
466 val create_program : atts:bool option -> loc:Loc.t -> program_name -> init:(Elpi.API.Ast.Loc.t * string) -> unit
467 val create_command : atts:bool option -> loc:Loc.t -> program_name -> unit
468 val create_tactic : loc:Loc.t -> program_name -> unit
469 val create_db : atts:phase option -> loc:Loc.t -> program_name -> init:(Elpi.API.Ast.Loc.t * string) -> unit
470 val create_file : atts:phase option -> loc:Loc.t -> program_name -> init:(Elpi.API.Ast.Loc.t * string) -> unit
471
472 end
473
474 module Synterp = struct
475 include Compiler(Rocq_elpi_programs.Synterp)
476
477 let main_syterp args syndata =
478 ET.mkApp API.RawData.Constants.orc
479 (ET.mkApp main_synterpc (EU.list_to_lp_list args) [syndata])
480 [ET.mkApp mainc (EU.list_to_lp_list args) []]
481
482 let run_program ~loc name ~atts args =
483 get_and_compile ~loc name |> Option.map (fun (program, raw_args) ->
484 let initial_synterp_state = Vernacstate.Synterp.freeze () in
485 let query state =
486 let loc = Rocq_elpi_utils.of_coq_loc loc in
487 let depth = 0 in
488 let state, args, gls = EU.map_acc
489 (Rocq_elpi_arg_HOAS.in_elpi_cmd_synterp ~depth)
490 state args in
491 let state, ek = API.FlexibleData.Elpi.make ~name:"NewData" state in
492 let data = ET.mkUnifVar ek ~args:[] state in
493 let state, q = atts2impl loc Summary.Stage.Synterp ~depth state atts (main_syterp args data) in
494 let state = API.State.set Rocq_elpi_builtins_synterp.invocation_site_loc_synterp state loc in
495 state, q, gls in
496 try
497 let relocate, synterplog, _, _, _,_ = run_and_print ~loc ~print:false name program (Fun query) in
498 initial_synterp_state, synterplog, relocate "NewData"
499 with Rocq_elpi_builtins_synterp.SynterpAction.Error x -> err x)
500
501 let run_in_program ~loc ?program query =
502 try run_in_program ~loc ?program query |> Option.map (fun (_,x) -> x)
503 with Rocq_elpi_builtins_synterp.SynterpAction.Error x -> err x
504
505 end
506
507 let document_builtins = document_builtins
508
509 module Interp = struct
510
511 include Compiler(Rocq_elpi_programs.Interp)
512
513 let main_or_main_interp args more_args =
514 ET.mkApp API.RawData.Constants.orc
515 (ET.mkApp main_interpc (EU.list_to_lp_list args) more_args)
516 [ET.mkApp mainc (EU.list_to_lp_list args) []]
517
518 let main_begin_proof args more_args =
519 ET.mkApp main_interp_proofc (EU.list_to_lp_list args) more_args
520
521 let main_end_proof args more_args =
522 ET.mkApp main_interp_qedc (EU.list_to_lp_list args) more_args
523
524 let missing_synterp = let open Pp in
525 fnl() ++
526 strbrk "The command lacks code for the synterp phase. In order to add code to this phase use '#[synterp] Elpi Accumulate'. See also https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_command.html#parsing-and-execution"
527
528 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
529 let empty_glob_sign env = Genintern.empty_glob_sign ~strict:true env
530 [%%else]
531 let empty_glob_sign env = Genintern.empty_glob_sign ~strict:true env UnivNames.empty_binders
532 [%%endif]
533
534
535 let run_program ~loc name ~main ~atts ~syndata ?sigma args more_args =
536 get_and_compile ~loc name |> Option.map (fun (program, raw_args) ->
537 let env = Global.env () in
538 let sigma = match sigma with Some x -> x | None -> Evd.from_env env in
539 let args = args
540 |> List.map (Rocq_elpi_arg_HOAS.Cmd.glob (empty_glob_sign env))
541 |> List.map (Rocq_elpi_arg_HOAS.Cmd.interp (Ltac_plugin.Tacinterp.default_ist ()) env sigma)
542 in
543 let initial_synterp_state, synterplog =
544 match syndata with
545 | None ->
546 let initial_synterp_state = Vernacstate.Synterp.freeze () in
547 initial_synterp_state,
548 Rocq_elpi_builtins_synterp.SynterpAction.RZipper.empty
549 | Some (initial_synterp_state,log) -> initial_synterp_state, log in
550 let query state =
551 let state = Rocq_elpi_HOAS.set_initial_sigma state sigma in
552 let depth = 0 in
553 let state, args, gls = EU.map_acc
554 (Rocq_elpi_arg_HOAS.in_elpi_cmd ~loc ~depth ~base:program ~raw:raw_args
555 Rocq_elpi_HOAS.(empty_conv_context ~options:(default_options ()) state))
556 state args in
557 let loc = Rocq_elpi_utils.of_coq_loc loc in
558
559 let state, more_args_gls = more_args |> List.fold_left_map (fun state f ->
560 match f ~target:program ~depth state with
561 | Stdlib.Result.Ok (s,x,gl) -> s,(x,gl)
562 | Stdlib.Result.Error s -> err Pp.(str"Data returned by the synterp phase cannot be passed to the interp phase due to unknown symbol: " ++ str s)) state in
563 let more_args, more_gls = List.split more_args_gls in
564
565 let state, q = atts2impl loc Summary.Stage.Interp ~depth state atts (main args more_args) in
566 let state = API.State.set Rocq_elpi_builtins.base state (Some program) in
567 let state = API.State.set Rocq_elpi_builtins.tactic_mode state false in
568 let state = API.State.set Rocq_elpi_builtins_synterp.invocation_site_loc state loc in
569 let state = API.State.set Rocq_elpi_builtins_synterp.SynterpAction.read state synterplog in
570 state, q, gls @ List.concat more_gls in
571 let final_synterp_state = Vernacstate.Synterp.freeze () in
572 Vernacstate.Synterp.unfreeze initial_synterp_state;
573 try begin
574 try
575 let relocate, synterp_left, state, assignments, csts, ppctx = run_and_print ~loc ~print:false name program (Fun query) in
576 match Rocq_elpi_builtins_synterp.SynterpAction.RZipper.is_empty synterp_left with
577 | `Empty ->
578 Vernacstate.Synterp.unfreeze final_synterp_state;
579 relocate, state, assignments, csts, ppctx
580 | `Group g ->
581 let g = Rocq_elpi_builtins_synterp.SynterpAction.Tree.group_name g in
582 err Pp.(strbrk"The execution phase did not consume all the parse time actions. Next in the queue is group " ++ str g)
583 | `Action a ->
584 err Pp.(strbrk"The execution phase did not consume all the parse time actions. Next in the queue is action " ++ Rocq_elpi_builtins_synterp.SynterpAction.pp a)
585 with
586 | Rocq_elpi_builtins_synterp.SynterpAction.Error x when syndata = None ->
587 err Pp.(x ++ missing_synterp)
588 | Rocq_elpi_builtins_synterp.SynterpAction.Error x ->
589 err x
590 end with e ->
591 let e = Exninfo.capture e in
592 Vernacstate.Synterp.unfreeze final_synterp_state;
593 (match fst e with
594 | CErrors.UserError _ -> ()
595 | _ -> Feedback.msg_debug Pp.(str "elpi lets escape exception: " ++ CErrors.iprint e));
596 Exninfo.iraise e)
597
598 let run_in_program ~loc ?program ~syndata query =
599 let st_setup base state =
600 let syndata = Option.default (Rocq_elpi_builtins_synterp.SynterpAction.RZipper.empty) syndata in
601 let state = API.State.set Rocq_elpi_builtins.base state (Some base) in
602 API.State.set Rocq_elpi_builtins_synterp.SynterpAction.read state syndata in
603 try ignore @@ run_in_program ~loc ?program ~st_setup query
604 with
605 | Rocq_elpi_builtins_synterp.SynterpAction.Error x when syndata = None -> err Pp.(x ++ missing_synterp)
606 | Rocq_elpi_builtins_synterp.SynterpAction.Error x -> err x
607
608 let stash = Summary.ref ~local:true ~name:"elpi:proof_stash" None
609 let set_stash x = stash := Some x
610 let get_stash ~default_name =
611 match !stash with
612 | None -> (fun ~target ~depth -> Ok(API.RawOpaqueData.of_string (Names.Id.to_string default_name))), [], None
613 | Some x -> stash := None; x
614
615 [%%if coq = "9.0"]
616 let compat_typ sigma typ = EConstr.to_constr ~abort_on_undefined_evars:false sigma typ
617 let void () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.False.type")
618 [%%else]
619 let compat_typ _sigma typ = typ
620 let void () = EConstr.of_constr @@ UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.False.type")
621 [%%endif]
622
623 let run_program_open_proof ~loc name ~atts ~syndata args : Declare.Proof.t =
624 let syn, syndata =
625 match syndata with
626 | None -> (fun ~target ~depth s -> Ok(s, ET.mkDiscard, [])), None
627 | Some(x,y,f) -> (fun ~target ~depth s -> f ~target ~depth |> Result.map (fun x -> s,x,[])), (Some(x,y)) in
628 let goals ~target:_ ~depth state =
629 let state, ek = API.FlexibleData.Elpi.make ~name:"GoalsList" state in
630 let data = ET.mkUnifVar ek ~args:[] state in
631 Ok(state, data, []) in
632 let root ~target:_ ~depth state =
633 let state, ek = API.FlexibleData.Elpi.make ~name:"RootTerm" state in
634 let data = ET.mkUnifVar ek ~args:[] state in
635 Ok(state, data,[]) in
636 let data ~target:_ ~depth state =
637 let state, ek = API.FlexibleData.Elpi.make ~name:"Data" state in
638 let data = ET.mkUnifVar ek ~args:[] state in
639 Ok(state, data,[]) in
640 (run_program ~loc name ~main:main_begin_proof ~atts ~syndata args [syn;root;goals;data]) |> (function
641 | None -> err Pp.(str"This program did not open a proof")
642 | Some (relocate, state, assignments, constraints, pp_ctx) ->
643 let goals =
644 try
645 let sigma = Rocq_elpi_HOAS.get_sigma state in
646 let t = API.Setup.StrMap.find "GoalsList" assignments in
647 match Rocq_elpi_HOAS.sealed_goals2ev ~depth:0 constraints state pp_ctx t with
648 | None -> Evd.undefined_map sigma |> Evar.Map.bindings |> List.map fst
649 | Some evs -> evs
650 with Not_found | Elpi.API.Conversion.TypeErr _ -> [] in
651 let state, root =
652 try
653 let t = API.Setup.StrMap.find "RootTerm" assignments in
654 let state, t, _ = Rocq_elpi_HOAS.lp2constr ~depth:0 Rocq_elpi_HOAS.(upcast @@ empty_conv_context ~options:(default_options()) state) constraints state t in
655 state, Some t
656 with Not_found | Elpi.API.Conversion.TypeErr _ -> state, None in
657 let data = relocate "Data" in
658 set_stash (data,goals,root);
659 let info = Declare.Info.make () in
660 let name =
661 Names.Id.of_string_soft (Format.asprintf "This lemma must be closed by an Elpi command, i.e. not Qed or Defined") in
662 let cinfo = Declare.CInfo.make ~name ~typ:(void ()) () in
663 let tac =
664 let goals = List.map Proofview_monad.with_empty_state goals in
665 Proofview.Unsafe.tclSETGOALS goals in
666 let sigma = Rocq_elpi_HOAS.get_sigma state in
667 Declare.Proof.start_definition ~info ~cinfo sigma |>
668 Declare.Proof.map ~f:(fun p -> Proof.run_tactic (Global.env ()) tac p |> fun (p,_,_) -> p))
669
670 let run_program_close_proof ~loc name ~atts ~syndata args ~lemma =
671 let syn, syndata =
672 match syndata with
673 | None -> (fun ~target ~depth s -> Ok(s, ET.mkDiscard, [])), None
674 | Some(x,y,f) -> (fun ~target ~depth s -> f ~target ~depth |> Result.map (fun x -> s,x,[])), (Some(x,y)) in
675 let data, goals, root = get_stash ~default_name:(Declare.Proof.get_name lemma) in
676 let sigma = Declare.Proof.(get lemma) |> fun x -> Proof.(data x).Proof.sigma in
677 let goals ~target:_ ~depth state =
678 let state, l, gls = EU.map_acc (Rocq_elpi_HOAS.sealed_maybe_solved_goal2lp ~depth) state goals in
679 let l = EU.list_to_lp_list l in
680 Ok(state, l, gls) in
681 let root ~target:_ ~depth state =
682 match root with
683 | None ->
684 let p = Declare.Proof.get lemma |> Proof.partial_proof |> List.hd in
685 let state, r, gls = Rocq_elpi_HOAS.constr2lp ~calldepth:0 Rocq_elpi_HOAS.(upcast @@ empty_conv_context ~options:(default_options()) state) ET.no_constraints ~depth state p in
686 Ok(state,r, gls)
687 | Some root ->
688 let state, r, gls = Rocq_elpi_HOAS.constr2lp ~calldepth:0 Rocq_elpi_HOAS.(upcast @@ empty_conv_context ~options:(default_options()) state) ET.no_constraints ~depth state root in
689 Ok(state, r, gls) in
690 let data ~target ~depth state = data ~target ~depth |> Result.map (fun x -> state,x,[]) in
691 (run_program ~loc name ~main:main_end_proof ~atts ~syndata ~sigma args [syn;root;goals;data]) |> (function
692 | None -> err Pp.(str"This program did not colse the proof")
693 | Some _ -> ()
694 )
695
696 let run_program ~loc name ~atts ~syndata args =
697 let syn, syndata =
698 match syndata with
699 | None -> (fun ~target ~depth s -> Ok(s, ET.mkDiscard,[])), None
700 | Some(x,y,f) -> (fun ~target ~depth s -> f ~target ~depth |> Result.map (fun x -> s,x,[]) ), (Some(x,y)) in
701 let _ : _ option = run_program ~loc name ~main:main_or_main_interp ~atts ~syndata args [syn] in
702 ()
703
704 end
705
706 open Tacticals
707
708 let run_tactic_common ~loc program ~main ?(atts=[]) () =
709 let open Proofview in
710 let open Notations in
711 let open Interp in
712 Unsafe.tclGETGOALS >>= fun gls ->
713 let gls = CList.map Proofview.drop_state gls in
714 Proofview.tclEVARMAP >>= fun sigma ->
715 let sigma = Evd.push_future_goals sigma in (* avoid touching unrelated future goals *)
716 let query ~base state =
717 let loc = of_coq_loc loc in
718 let depth = 0 in
719 let state, main_query, gls = main ~base sigma gls state in
720 let state, main_query = atts2impl ~depth loc Summary.Stage.Interp state atts main_query in
721 let state = API.State.set Rocq_elpi_builtins.tactic_mode state true in
722 let state = API.State.set Rocq_elpi_builtins_synterp.invocation_site_loc state loc in
723 state, main_query, gls
724 in
725 get_and_compile ~loc program |> Option.cata (fun (cprogram, _) ->
726 match run ~loc cprogram (Fun (query ~base:cprogram)) with
727 | API.Execute.Success solution -> Rocq_elpi_HOAS.tclSOLUTION2EVD ~eta_contract_solution:false sigma solution gls
728 | API.Execute.NoMoreSteps -> CErrors.user_err Pp.(str "elpi run out of steps")
729 | API.Execute.Failure -> elpi_fails program
730 | exception (Rocq_elpi_utils.LtacFail (level, msg)) -> tclFAILn level msg
731 | exception (CErrors.UserError _ as e) -> let e = Exninfo.capture e in Exninfo.iraise e
732 | exception e when CErrors.noncritical e -> let e = Exninfo.capture e in (Feedback.msg_debug Pp.(str "elpi lets escape exception: " ++ CErrors.iprint e); Exninfo.iraise e))
733 tclIDTAC
734
735 let run_tactic ~loc program ~atts _ist args =
736 run_tactic_common ~loc program ~atts ~main:(fun ~base sigma gls state ->
737 Rocq_elpi_HOAS.solvegoals2query sigma gls (Rocq_elpi_utils.of_coq_loc loc) ~main:args ~base
738 ~in_elpi_tac_arg:Rocq_elpi_arg_HOAS.(in_elpi_tac ~loc) ~depth:0 state) ()
739
740 let run_in_tactic ~loc ?(program = Interp.current_program ()) (qloc,query) _ist =
741 run_tactic_common ~loc program ~main:(fun ~base sigma gls state ->
742 Rocq_elpi_HOAS.txtgoals2query sigma gls qloc ~main:query ~base ~depth:0 state)
743 ()
744
745 let loc_merge l1 l2 =
746 try Loc.merge l1 l2
747 with Failure _ -> l1
748
749 let has_att s l =
750 let open Attributes in
751 l |> List.exists (function
752 | { CAst.v = s',VernacFlagEmpty } -> String.equal s s'
753 | _ -> false)
754
755 [%%if coq = "9.0"]
756 let classifier proof _loc0 _args _loc1 =
757 match proof with
758 | Some (Begin None) -> Vernacextend.(VtStartProof (Doesn'tGuaranteeOpacity,[]))
759 | Some End -> Vernacextend.(VtQed (VtKeep VtKeepAxiom))
760 | _ -> Vernacextend.VtSideff ([], VtNow)
761 let execution proof p loc0 args loc1 ?loc ~atts () =
762 let loc = Option.default (loc_merge loc0 loc1) loc in
763 let syndata = Synterp.run_program ~loc p ~atts args in
764 match proof with
765 | Some (Begin None) -> Vernactypes.vtopenproof (fun () -> Interp.run_program_open_proof ~loc p ~atts ~syndata args)
766 | Some End -> Vernactypes.vtcloseproof (fun ~lemma ~pm -> Interp.run_program_close_proof ~loc p ~atts ~syndata args ~lemma; pm)
767 | _ -> Vernactypes.vtdefault (fun () -> Interp.run_program ~loc p ~atts ~syndata args)
768 [%%else]
769 let classifier proof _loc0 _args _loc1 ~atts =
770 match proof with
771 | Some (Begin None) -> Vernacextend.(VtStartProof (Doesn'tGuaranteeOpacity,[]))
772 | Some (Begin (Some a)) when has_att a atts -> Vernacextend.(VtStartProof (Doesn'tGuaranteeOpacity,[]))
773 | Some End -> Vernacextend.(VtQed (VtKeep VtKeepAxiom))
774 | _ -> Vernacextend.VtSideff ([], VtNow)
775 let execution proof p loc0 args loc1 ?loc ~atts () =
776 let loc = Option.default (loc_merge loc0 loc1) loc in
777 let syndata = Synterp.run_program ~loc p ~atts args in
778 match proof with
779 | Some (Begin None) -> Vernactypes.vtopenproof (fun () -> Interp.run_program_open_proof ~loc p ~atts ~syndata args)
780 | Some (Begin (Some a)) when has_att a atts -> Vernactypes.vtopenproof (fun () -> Interp.run_program_open_proof ~loc p ~atts ~syndata args)
781 | Some End -> Vernactypes.vtcloseproof (fun ~lemma ~pm -> Interp.run_program_close_proof ~loc p ~atts ~syndata args ~lemma; pm)
782 | _ -> Vernactypes.vtdefault (fun () -> Interp.run_program ~loc p ~atts ~syndata args)
783 [%%endif]
784
785 [%%if coq = "9.0" || coq = "9.1"]
786 let extend_vernac_command_grammar ext : unit =
787 Egramml.extend_vernac_command_grammar ~undoable:true ext
788 [%%else]
789 let extend_vernac_command_grammar ext : unit =
790 Egramml.extend_vernac_command_grammar ~ignore_kw:false ~undoable:true ext
791 [%%endif]
792
793 let cache_program (proof,nature,p,q) =
794 let p_str = String.concat "." q in
795 match nature with
796 | Command _ ->
797 let command = Vernacexpr.{
798 ext_plugin = "rocq-elpi.elpi";
799 ext_entry = "Elpi" ^ p_str;
800 ext_index = 0;
801 } in
802 let ext =
803 Vernacextend.declare_dynamic_vernac_extend
804 ~command
805 ?entry:None
806 ~depr:false
807
808 (classifier proof)
809
810 (Vernacextend.TyNonTerminal
811 (Extend.TUentry
812 (Genarg.get_arg_tag Rocq_elpi_arg_syntax.wit_elpi_loc),
813 Vernacextend.TyTerminal
814 (p_str,
815 Vernacextend.TyNonTerminal
816 (Extend.TUlist0
817 (Extend.TUentry (Genarg.get_arg_tag Rocq_elpi_arg_syntax.wit_elpi_cmd_arg))
818 ,Vernacextend.TyNonTerminal
819 (Extend.TUentry (Genarg.get_arg_tag Rocq_elpi_arg_syntax.wit_elpi_loc),
820 Vernacextend.TyNil)))))
821
822 (execution proof p)
823 in
824 extend_vernac_command_grammar ext
825
826 | Tactic ->
827 Rocq_elpi_builtins.cache_tac_abbrev ~code:p ~name:q
828 | Program _ ->
829 CErrors.user_err Pp.(str "elpi: Only commands and tactics can be exported")
830
831 let subst_program = function
832 | _, x -> x (* qualified_names and nature: no GRefs to substitute *)
833
834 let in_exported_program : proof option * nature * qualified_name * qualified_name -> Libobject.obj =
835 let open Libobject in
836 declare_object @@ { (global_object_nodischarge "ELPI-EXPORTED"
837 ~cache:cache_program
838 ~subst:(Some subst_program)) with object_stage = Summary.Stage.Synterp }
839
840 let export_command ~atts:proof ?as_ p =
841 let q =
842 match as_ with
843 | None -> p
844 | Some x -> x in
845 let nature = Rocq_elpi_programs.Synterp.get_nature p in
846 Lib.add_leaf (in_exported_program (proof,nature,p,q))
847