Debian Codegraph @

plugins/ltac/tacentries.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 open Names
15 open Libobject
16 open Genarg
17 open Extend
18 open Procq
19 open Egramml
20 open Vernacexpr
21 open Libnames
22 open Nameops
23
24 type 'a grammar_tactic_prod_item_expr = 'a Pptactic.grammar_tactic_prod_item_expr =
25 | TacTerm of string
26 | TacNonTerm of ('a * Names.Id.t option) Loc.located
27
28 type raw_argument = string * string option
29 type argument = Genarg.ArgT.any Extend.user_symbol
30
31 (**********************************************************************)
32 (* Interpret entry names of the form "ne_constr_list" as entry keys *)
33
34 let atactic n =
35 Procq.Symbol.nterml Pltac.ltac_expr (string_of_int n)
36
37 type entry_name = EntryName :
38 'a raw_abstract_argument_type * (Tacexpr.raw_tactic_expr, _, 'a) Procq.Symbol.t -> entry_name
39
40 (** Quite ad-hoc *)
41 let get_tacentry n m =
42 let check_lvl n =
43 Int.equal m n
44 && not (Int.equal m 0) (* Because tactic0 is at simple_tactic *)
45 in
46 if check_lvl n then EntryName (rawwit Tacarg.wit_tactic, Procq.Symbol.self)
47 else if check_lvl (n + 1) then EntryName (rawwit Tacarg.wit_tactic, Procq.Symbol.next)
48 else EntryName (rawwit Tacarg.wit_tactic, atactic n)
49
50 let get_separator = function
51 | None -> user_err Pp.(str "Missing separator.")
52 | Some sep -> sep
53
54 let check_separator ?loc = function
55 | None -> ()
56 | Some _ -> user_err ?loc (str "Separator is only for arguments with suffix _list_sep.")
57
58 let rec parse_user_entry ?loc s sep =
59 let open CString in
60 let matches pre suf s =
61 String.length s > (String.length pre + String.length suf) &&
62 is_prefix pre s && is_suffix suf s
63 in
64 let basename pre suf s =
65 let plen = String.length pre in
66 String.sub s plen (String.length s - (plen + String.length suf))
67 in
68 let tactic_len = String.length "tactic" in
69 if matches "ne_" "_list" s then
70 let entry = parse_user_entry ?loc (basename "ne_" "_list" s) None in
71 check_separator ?loc sep;
72 Ulist1 entry
73 else if matches "ne_" "_list_sep" s then
74 let entry = parse_user_entry ?loc (basename "ne_" "_list_sep" s) None in
75 Ulist1sep (entry, get_separator sep)
76 else if matches "" "_list" s then
77 let entry = parse_user_entry ?loc (basename "" "_list" s) None in
78 check_separator ?loc sep;
79 Ulist0 entry
80 else if matches "" "_list_sep" s then
81 let entry = parse_user_entry ?loc (basename "" "_list_sep" s) None in
82 Ulist0sep (entry, get_separator sep)
83 else if matches "" "_opt" s then
84 let entry = parse_user_entry ?loc (basename "" "_opt" s) None in
85 check_separator ?loc sep;
86 Uopt entry
87 else if String.length s = tactic_len + 1 && is_prefix "tactic" s
88 && '5' >= s.[tactic_len] && s.[tactic_len] >= '0' then
89 let n = Char.code s.[tactic_len] - Char.code '0' in
90 check_separator ?loc sep;
91 Uentryl ("tactic", n)
92 else
93 let _ = check_separator ?loc sep in
94 Uentry s
95
96 let interp_entry_name interp symb =
97 let rec eval = function
98 | Ulist1 e -> Ulist1 (eval e)
99 | Ulist1sep (e, sep) -> Ulist1sep (eval e, sep)
100 | Ulist0 e -> Ulist0 (eval e)
101 | Ulist0sep (e, sep) -> Ulist0sep (eval e, sep)
102 | Uopt e -> Uopt (eval e)
103 | Uentry s -> Uentry (interp s None)
104 | Uentryl (s, n) -> Uentryl (interp s (Some n), n)
105 in
106 eval symb
107
108 (**********************************************************************)
109 (** Grammar declaration for Tactic Notation (Rocq level) *)
110
111 let get_tactic_entry n =
112 if Int.equal n 0 then
113 Pltac.simple_tactic, None
114 else if 1<=n && n<=5 then
115 Pltac.ltac_expr, Some (string_of_int n)
116 else
117 user_err Pp.(str ("Invalid Tactic Notation level: "^(string_of_int n)^"."))
118
119 (**********************************************************************)
120 (** State of the grammar extensions *)
121
122 type tactic_grammar = {
123 tacgram_level : int;
124 tacgram_prods : Pptactic.grammar_terminals;
125 }
126
127 (* Declaration of the tactic grammar rule *)
128
129 let head_is_ident tg = match tg.tacgram_prods with
130 | TacTerm _ :: _ -> true
131 | _ -> false
132
133 let rec prod_item_of_symbol lev = function
134 | Extend.Ulist1 s ->
135 let EntryName (Rawwit typ, e) = prod_item_of_symbol lev s in
136 EntryName (Rawwit (ListArg typ), Procq.Symbol.list1 e)
137 | Extend.Ulist0 s ->
138 let EntryName (Rawwit typ, e) = prod_item_of_symbol lev s in
139 EntryName (Rawwit (ListArg typ), Procq.Symbol.list0 e)
140 | Extend.Ulist1sep (s, sep) ->
141 let EntryName (Rawwit typ, e) = prod_item_of_symbol lev s in
142 EntryName (Rawwit (ListArg typ), Procq.Symbol.list1sep e (Procq.Symbol.tokens [Procq.TPattern (CLexer.terminal sep)]))
143 | Extend.Ulist0sep (s, sep) ->
144 let EntryName (Rawwit typ, e) = prod_item_of_symbol lev s in
145 EntryName (Rawwit (ListArg typ), Procq.Symbol.list0sep e (Procq.Symbol.tokens [Procq.TPattern (CLexer.terminal sep)]))
146 | Extend.Uopt s ->
147 let EntryName (Rawwit typ, e) = prod_item_of_symbol lev s in
148 EntryName (Rawwit (OptArg typ), Procq.Symbol.opt e)
149 | Extend.Uentry arg ->
150 let ArgT.Any tag = arg in
151 let wit = ExtraArg tag in
152 EntryName (Rawwit wit, Procq.Symbol.nterm (genarg_grammar wit))
153 | Extend.Uentryl (s, n) ->
154 let ArgT.Any tag = s in
155 assert (CString.is_suffix "tactic" (ArgT.repr tag));
156 get_tacentry n lev
157
158 (** Tactic grammar extensions *)
159
160 let add_tactic_entry (kn, ml, tg) state =
161 let open Tacexpr in
162 let entry, pos = get_tactic_entry tg.tacgram_level in
163 let mkact loc l =
164 let map arg =
165 (* HACK to handle especially the tactic(...) entry *)
166 let wit = Genarg.rawwit Tacarg.wit_tactic in
167 if Genarg.has_type arg wit && not ml then
168 Tacexp (Genarg.out_gen wit arg)
169 else
170 TacGeneric (None, arg)
171 in
172 let l = List.map map l in
173 (CAst.make ~loc (TacAlias (kn,l)):raw_tactic_expr)
174 in
175 let () =
176 if Int.equal tg.tacgram_level 0 && not (head_is_ident tg) then
177 user_err Pp.(str "Notation for simple tactic must start with an identifier.")
178 in
179 let map = function
180 | TacTerm s -> GramTerminal s
181 | TacNonTerm (loc, (s, ido)) ->
182 let EntryName (typ, e) = prod_item_of_symbol tg.tacgram_level s in
183 GramNonTerminal (Loc.tag ?loc @@ (typ, e))
184 in
185 let prods = List.map map tg.tacgram_prods in
186 let rules = make_rule mkact prods in
187 let r = ExtendRule (entry, Procq.Reuse (pos, [rules])) in
188 ([r], state)
189
190 let tactic_grammar =
191 create_grammar_command "TacticGrammar" { gext_fun = add_tactic_entry; gext_eq = (==) (* FIXME *) }
192
193 let extend_tactic_grammar kn ml ntn = extend_grammar_command tactic_grammar (kn, ml, ntn)
194
195 (**********************************************************************)
196 (* Tactic Notation *)
197
198 let entry_names = ref String.Map.empty
199
200 let register_tactic_notation_entry name entry =
201 let entry = match entry with
202 | ExtraArg arg -> ArgT.Any arg
203 | _ -> assert false
204 in
205 entry_names := String.Map.add name entry !entry_names
206
207 let interp_prod_item = function
208 | TacTerm s -> TacTerm s
209 | TacNonTerm (loc, ((nt, sep), ido)) ->
210 let symbol = parse_user_entry ?loc nt sep in
211 let interp s = function
212 | None ->
213 if String.Map.mem s !entry_names then String.Map.find s !entry_names
214 else begin match ArgT.name s with
215 | None ->
216 if s = "var" then user_err Pp.(str ("var is deprecated, use hyp.")) (* to remove in 8.14 *)
217 else user_err Pp.(str ("Unknown entry "^s^"."))
218 | Some arg -> arg
219 end
220 | Some n ->
221 (* FIXME: do better someday *)
222 assert (String.equal s "tactic");
223 begin match Tacarg.wit_tactic with
224 | ExtraArg tag -> ArgT.Any tag
225 end
226 in
227 let symbol = interp_entry_name interp symbol in
228 TacNonTerm (loc, (symbol, ido))
229
230 let make_fresh_key =
231 let id = Summary.ref ~stage:Summary.Stage.Synterp ~name:"TACTIC-NOTATION-COUNTER" 0 in
232 fun prods ->
233 let cur = incr id; !id in
234 let map = function
235 | TacTerm s -> s
236 | TacNonTerm _ -> "#"
237 in
238 let prods = String.concat "_" (List.map map prods) in
239 (* We embed the hash of the kernel name in the label so that the identifier
240 should be mostly unique. This ensures that including two modules
241 together won't confuse the corresponding labels. *)
242 let hash = (cur lxor (ModPath.hash (Lib.current_mp ()))) land 0x7FFFFFFF in
243 let lbl = Id.of_string_soft (Printf.sprintf "%s_%08X" prods hash) in
244 Lib.make_kn lbl
245
246 type tactic_grammar_obj = {
247 tacobj_key : KerName.t;
248 tacobj_local : locality_flag;
249 tacobj_tacgram : tactic_grammar;
250 tacobj_forml : bool;
251 }
252
253 let pprule pa = {
254 Pptactic.pptac_level = pa.tacgram_level;
255 pptac_prods = pa.tacgram_prods;
256 }
257
258 let check_key key =
259 if Tacenv.check_alias key then
260 user_err Pp.(str "Conflicting tactic notations keys. This can happen when including \
261 twice the same module.")
262
263 let cache_tactic_notation (tobj, body) =
264 let key = tobj.tacobj_key in
265 let () = check_key key in
266 Tacenv.register_alias key body
267
268 let load_tactic_notation i (tobj, body) =
269 let key = tobj.tacobj_key in
270 let () = check_key key in
271 (* Only add the printing and interpretation rules. *)
272 Tacenv.register_alias key body
273
274 let subst_tactic_notation (subst, (tobj, body)) =
275 let open Tacenv in
276 { tobj with
277 tacobj_key = Mod_subst.subst_kn subst tobj.tacobj_key
278 },
279 { body with alias_body = Tacsubst.subst_tactic subst body.alias_body }
280
281 let classify_tactic_notation tacobj = Substitute
282
283 let ltac_notation_cat = Libobject.create_category "ltac.notations"
284
285 let inTacticGrammar : tactic_grammar_obj * Tacenv.alias_tactic -> obj =
286 declare_object {(default_object "TacticGrammar") with
287 (* no open_function for the interp side of tactic notations *)
288 load_function = load_tactic_notation;
289 cache_function = cache_tactic_notation;
290 subst_function = subst_tactic_notation;
291 classify_function = classify_tactic_notation}
292
293 let cache_tactic_syntax tobj =
294 let key = tobj.tacobj_key in
295 extend_tactic_grammar ~ignore_kw:false key tobj.tacobj_forml tobj.tacobj_tacgram;
296 Pptactic.declare_notation_tactic_pprule key (pprule tobj.tacobj_tacgram)
297
298 let open_tactic_syntax tobj =
299 let key = tobj.tacobj_key in
300 if not tobj.tacobj_local then
301 extend_tactic_grammar ~ignore_kw:false key tobj.tacobj_forml tobj.tacobj_tacgram
302
303 let load_tactic_syntax i tobj =
304 let key = tobj.tacobj_key in
305 (* Only add the printing and interpretation rules. *)
306 Pptactic.declare_notation_tactic_pprule key (pprule tobj.tacobj_tacgram);
307 if Int.equal i 1 && not tobj.tacobj_local then
308 extend_tactic_grammar ~ignore_kw:false key tobj.tacobj_forml tobj.tacobj_tacgram
309
310 let subst_tactic_syntax (subst, tobj) =
311 { tobj with
312 tacobj_key = Mod_subst.subst_kn subst tobj.tacobj_key
313 }
314
315 (* why do we not Drop when local? *)
316 let classify_tactic_syntax tacobj = Substitute
317
318 let inTacticSyntax : tactic_grammar_obj -> obj =
319 declare_object {(default_object "TacticSyntax") with
320 object_stage = Summary.Stage.Synterp;
321 open_function = simple_open ~cat:ltac_notation_cat open_tactic_syntax;
322 load_function = load_tactic_syntax;
323 cache_function = cache_tactic_syntax;
324 subst_function = subst_tactic_syntax;
325 classify_function = classify_tactic_syntax}
326
327 let cons_production_parameter = function
328 | TacTerm _ -> None
329 | TacNonTerm (_, (_, ido)) -> ido
330
331 let add_glob_tactic_notation ?deprecation tacobj ids tac =
332 let open Tacenv in
333 let body =
334 { alias_args = ids; alias_body = tac; alias_deprecation = deprecation } in
335 Lib.add_leaf (inTacticGrammar (tacobj, body))
336
337 let add_glob_tactic_notation_syntax local ~level ?deprecation prods forml =
338 let parule = {
339 tacgram_level = level;
340 tacgram_prods = prods;
341 } in
342 let tacobj = {
343 tacobj_key = make_fresh_key prods;
344 tacobj_local = local;
345 tacobj_tacgram = parule;
346 tacobj_forml = forml;
347 } in
348 Lib.add_leaf (inTacticSyntax tacobj);
349 tacobj
350
351 let add_tactic_notation ?deprecation tacobj e =
352 let ids = List.map_filter cons_production_parameter tacobj.tacobj_tacgram.tacgram_prods in
353 let tac = Tacintern.glob_tactic_env ids (Global.env()) e in
354 add_glob_tactic_notation ?deprecation tacobj ids tac
355
356 let add_tactic_notation_syntax local n ?deprecation prods =
357 let prods = List.map interp_prod_item prods in
358 add_glob_tactic_notation_syntax local ~level:n ?deprecation prods false
359
360 (**********************************************************************)
361 (* ML Tactic entries *)
362
363 exception NonEmptyArgument
364
365 (** ML tactic notations whose use can be restricted to an identifier are added
366 as true Ltac entries. *)
367 let extend_atomic_tactic name entries =
368 let open Tacexpr in
369 let map_prod prods =
370 let (hd, rem) = match prods with
371 | TacTerm s :: rem -> (s, rem)
372 | _ -> assert false (* Not handled by the ML extension syntax *)
373 in
374 let empty_value = function
375 | TacTerm s -> raise NonEmptyArgument
376 | TacNonTerm (_, (symb, _)) ->
377 let EntryName (typ, e) = prod_item_of_symbol 0 symb in
378 let Genarg.Rawwit wit = typ in
379 let inj x = CAst.make @@ TacArg ( TacGeneric (None, Genarg.in_gen typ x)) in
380 let default = epsilon_value inj e in
381 match default with
382 | None -> raise NonEmptyArgument
383 | Some def -> Tacintern.intern_tactic_or_tacarg (Genintern.empty_glob_sign ~strict:true Environ.empty_env) def
384 in
385 try Some (hd, List.map empty_value rem) with NonEmptyArgument -> None
386 in
387 let entries = List.map map_prod entries in
388 let add_atomic i args = match args with
389 | None -> ()
390 | Some (id, args) ->
391 let args = List.map (fun a -> Tacexp a) args in
392 let entry = { mltac_name = name; mltac_index = i } in
393 let body = CAst.make (TacML (entry, args)) in
394 Tacenv.register_ltac false false (Names.Id.of_string id) body
395 in
396 List.iteri add_atomic entries
397
398 let synterp_add_ml_tactic_notation name ~level ?deprecation prods =
399 let len = List.length prods in
400 let map i prods =
401 let open Tacexpr in
402 let get_id = function
403 | TacTerm s -> None
404 | TacNonTerm (_, (_, ido)) -> ido
405 in
406 let ids = List.map_filter get_id prods in
407 let entry = { mltac_name = name; mltac_index = len - i - 1 } in
408 let map id = Reference (Locus.ArgVar (CAst.make id)) in
409 let tac = CAst.make (TacML (entry, List.map map ids)) in
410 let tacobj = add_glob_tactic_notation_syntax false ~level ?deprecation prods true in
411 tacobj, { Tacenv.alias_args = ids; alias_body = tac; alias_deprecation = deprecation }
412 in
413 let for_interp = List.mapi map (List.rev prods) in
414 name, level, prods, for_interp
415
416 let interp_add_ml_tactic_notation (name, level, prods, data) =
417 List.iter (fun o -> Lib.add_leaf (inTacticGrammar o)) data;
418 (* We call [extend_atomic_tactic] only for "basic tactics" (the ones
419 at ltac_expr level 0) *)
420 let () = if Int.equal level 0 then extend_atomic_tactic name prods in
421 ()
422
423 (**********************************************************************)
424 (** Ltac quotations *)
425
426 let ltac_quotations = ref String.Set.empty
427
428 let create_ltac_quotation ~plugin name cast (e, l) : unit =
429 let () =
430 if String.Set.mem name !ltac_quotations then
431 failwith ("Ltac quotation " ^ name ^ " already registered")
432 in
433 let () = ltac_quotations := String.Set.add name !ltac_quotations in
434 let entry = match l with
435 | None -> Procq.Symbol.nterm e
436 | Some l -> Procq.Symbol.nterml e (string_of_int l)
437 in
438 let rule =
439 Procq.(
440 Rule.next
441 (Rule.next
442 (Rule.next
443 (Rule.next
444 (Rule.next
445 Rule.stop
446 (Symbol.token (CLexer.terminal name)))
447 (Symbol.token (CLexer.terminal ":")))
448 (Symbol.token (CLexer.terminal "(")))
449 entry)
450 (Symbol.token (CLexer.terminal ")")))
451 in
452 let action _ v _ _ _ loc = cast (Some loc, v) in
453 let gram = [Procq.Production.make rule action] in
454 let plugin_uid = (plugin, "tacquot:"^name) in
455 Egramml.grammar_extend ~ignore_kw:false ~plugin_uid Pltac.tactic_value (Procq.Reuse (None, gram))
456
457 (** Command *)
458
459 let is_defined_tac kn =
460 try ignore (Tacenv.interp_ltac kn); true with Not_found -> false
461
462 let warn_unusable_identifier =
463 CWarnings.create ~name:"unusable-identifier" ~category:CWarnings.CoreCategories.parsing
464 (fun id -> strbrk "The Ltac name" ++ spc () ++ Id.print id ++ spc () ++
465 strbrk "may be unusable because of a conflict with a notation.")
466
467 let register_ltac atts = function
468 | [Tacexpr.TacticRedefinition (qid, body)] ->
469 let local = Attributes.(parse explicit_hint_locality atts) in
470 let local = match local with
471 | Some local -> Locality.check_locality_nodischarge local; [local]
472 | None -> if Lib.sections_are_opened () then [Local] else [SuperGlobal; Export]
473 in
474 let kn =
475 try Tacenv.locate_tactic qid
476 with Not_found ->
477 CErrors.user_err ?loc:qid.CAst.loc
478 (str "There is no Ltac named " ++ pr_qualid qid ++ str ".")
479 in
480 let ist = Tacintern.make_empty_glob_sign ~strict:true in
481 let body = Tacintern.intern_tactic_or_tacarg ist body in
482 local |> List.iter (fun local -> Tacenv.redefine_ltac local kn body);
483 let name = Tacenv.shortest_qualid_of_tactic kn in
484 Flags.if_verbose Feedback.msg_info (Libnames.pr_qualid name ++ str " is redefined")
485
486 | tacl ->
487 let local, deprecation = Attributes.(parse Attributes.Notations.(locality ++ deprecation) atts) in
488 let local = Locality.make_module_locality local in
489 let map = function
490 | Tacexpr.TacticDefinition ({CAst.loc;v=id}, body) ->
491 let kn = Lib.make_kn id in
492 let id_pp = Id.print id in
493 let () = if is_defined_tac kn then
494 CErrors.user_err ?loc
495 (str "There is already an Ltac named " ++ id_pp ++ str".")
496 in
497 let is_shadowed =
498 try
499 match Procq.parse_string Pltac.tactic (Id.to_string id) with
500 | { CAst.v=(Tacexpr.TacArg _) } -> false
501 | _ -> true (* most probably TacAtom, i.e. a primitive tactic ident *)
502 with e when CErrors.noncritical e -> true (* prim tactics with args, e.g. "apply" *)
503 in
504 let () = if is_shadowed then warn_unusable_identifier id in
505 id, body
506 | Tacexpr.TacticRedefinition (qid, body) ->
507 CErrors.user_err Pp.(str "Ltac redefinitions not supported in a mutual block.")
508 in
509 let rfun = List.map map tacl in
510 let ist = Tacintern.make_empty_glob_sign ~strict:true in
511 let map (name, body) =
512 let body = Tacintern.intern_tactic_or_tacarg ist body in
513 (name, body)
514 in
515 let defs () =
516 (* Register locally the tactic to handle recursivity. This
517 function affects the whole environment, so that we transactify
518 it afterwards. *)
519 let iter_rec (id, _) =
520 let sp, kn = Lib.make_foname id in
521 Tacenv.push_tactic (Nametab.Until 1) sp kn
522 in
523 let () = List.iter iter_rec rfun in
524 List.map map rfun
525 in
526 let defs = Vernacstate.System.protect defs () in
527 let iter (id, tac) =
528 Tacenv.register_ltac false local id tac ?deprecation;
529 Flags.if_verbose Feedback.msg_info (Id.print id ++ str " is defined")
530 in
531 List.iter iter defs
532
533 (** Queries *)
534
535 let print_ltacs () =
536 let entries = KerName.Map.bindings (Tacenv.ltac_entries ()) in
537 let sort (kn1, _) (kn2, _) = KerName.compare kn1 kn2 in
538 let entries = List.sort sort entries in
539 let map (kn, entry) =
540 let qid =
541 try Some (Tacenv.shortest_qualid_of_tactic kn)
542 with Not_found -> None
543 in
544 match qid with
545 | None -> None
546 | Some qid -> Some (qid, entry.Tacenv.tac_body)
547 in
548 let entries = List.map_filter map entries in
549 let pr_entry (qid, body) =
550 let (l, t) = match body with
551 | {CAst.v=(Tacexpr.TacFun (l, t))} -> (l, t)
552 | _ -> ([], body)
553 in
554 let pr_ltac_fun_arg n = spc () ++ Name.print n in
555 hov 2 (pr_qualid qid ++ prlist pr_ltac_fun_arg l)
556 in
557 Feedback.msg_notice (prlist_with_sep fnl pr_entry entries)
558
559 let locatable_ltac = "Ltac"
560
561 let split_ltac_fun = function
562 | {CAst.v=(Tacexpr.TacFun (l, t))} -> (l,t)
563 | t -> ([],t)
564
565 let pr_ltac_fun_arg n = spc () ++ Name.print n
566
567 let print_ltac_body qid tac =
568 let redefined = match tac.Tacenv.tac_redef with
569 | [] -> mt ()
570 | mods ->
571 let pr_one mp =
572 let qid = try Nametab.shortest_qualid_of_module mp
573 with Not_found ->
574 try Nametab.shortest_qualid_of_dir (DirOpenModule mp)
575 with Not_found -> Nametab.shortest_qualid_of_dir (DirOpenModtype mp)
576 in
577 pr_qualid qid
578 in
579 let redef = prlist_with_sep fnl pr_one mods in
580 fnl () ++ str "Redefined by:" ++ fnl () ++ redef
581 in
582 let l,t = split_ltac_fun tac.Tacenv.tac_body in
583 hv 2 (
584 hov 2 (str "Ltac" ++ spc() ++ pr_qualid qid ++
585 prlist pr_ltac_fun_arg l ++ spc () ++ str ":=")
586 ++ spc() ++ Pptactic.pr_glob_tactic (Global.env ()) t) ++ redefined
587
588 let () =
589 let open Prettyp in
590 let locate qid = try Some (qid, Tacenv.locate_tactic qid) with Not_found -> None in
591 let locate_all qid = List.map (fun kn -> (qid,kn)) (Tacenv.locate_extended_all_tactic qid) in
592 let shortest_qualid (qid,kn) = Tacenv.shortest_qualid_of_tactic kn in
593 let name (qid,kn) = str "Ltac" ++ spc () ++ pr_path (Tacenv.path_of_tactic kn) in
594 let print (qid,kn) =
595 let entries = Tacenv.ltac_entries () in
596 let tac = KerName.Map.find kn entries in
597 print_ltac_body qid tac in
598 let about = name in
599 register_locatable locatable_ltac {
600 locate;
601 locate_all;
602 shortest_qualid;
603 name;
604 print;
605 about;
606 }
607
608 let print_located_tactic qid =
609 Feedback.msg_notice (Prettyp.print_located_other (Global.env ()) locatable_ltac qid)
610
611 let print_ltac id =
612 try
613 let kn = Tacenv.locate_tactic id in
614 let entries = Tacenv.ltac_entries () in
615 let tac = KerName.Map.find kn entries in
616 print_ltac_body id tac
617 with
618 Not_found ->
619 user_err
620 (pr_qualid id ++ spc() ++ str "is not a user defined tactic.")
621
622 (** Grammar *)
623
624 let () =
625 let open Procq.Entry in
626 let entries = [
627 Any Pltac.ltac_expr;
628 Any Pltac.simple_tactic;
629 Any Pltac.tactic_value;
630 ] in
631 register_grammars_by_name "tactic" entries
632
633 let get_identifier i =
634 (* Workaround for badly-designed generic arguments lacking a closure *)
635 Names.Id.of_string_soft (Printf.sprintf "$%i" i)
636
637 type _ ty_sig =
638 | TyNil : (Geninterp.interp_sign -> unit Proofview.tactic) ty_sig
639 | TyIdent : string * 'r ty_sig -> 'r ty_sig
640 | TyArg : ('a, 'b, 'c) Extend.ty_user_symbol * 'r ty_sig -> ('c -> 'r) ty_sig
641
642 type ty_ml = TyML : 'r ty_sig * 'r -> ty_ml
643
644 let rec untype_user_symbol : type a b c. (a,b,c) ty_user_symbol -> Genarg.ArgT.any user_symbol = fun tu ->
645 match tu with
646 | TUlist1 l -> Ulist1(untype_user_symbol l)
647 | TUlist1sep(l,s) -> Ulist1sep(untype_user_symbol l, s)
648 | TUlist0 l -> Ulist0(untype_user_symbol l)
649 | TUlist0sep(l,s) -> Ulist0sep(untype_user_symbol l, s)
650 | TUopt(o) -> Uopt(untype_user_symbol o)
651 | TUentry a -> Uentry (Genarg.ArgT.Any a)
652 | TUentryl (a,i) -> Uentryl (Genarg.ArgT.Any a,i)
653
654 let rec clause_of_sign : type a. int -> a ty_sig -> Genarg.ArgT.any Extend.user_symbol grammar_tactic_prod_item_expr list =
655 fun i sign -> match sign with
656 | TyNil -> []
657 | TyIdent (s, sig') -> TacTerm s :: clause_of_sign i sig'
658 | TyArg (a, sig') ->
659 let id = Some (get_identifier i) in
660 TacNonTerm (None, (untype_user_symbol a, id)) :: clause_of_sign (i + 1) sig'
661
662 let clause_of_ty_ml = function
663 | TyML (t,_) -> clause_of_sign 1 t
664
665 let rec eval_sign : type a. a ty_sig -> a -> Geninterp.Val.t list -> Geninterp.interp_sign -> unit Proofview.tactic =
666 fun sign tac ->
667 match sign with
668 | TyNil ->
669 begin fun vals ist -> match vals with
670 | [] -> tac ist
671 | _ :: _ -> assert false
672 end
673 | TyIdent (s, sig') -> eval_sign sig' tac
674 | TyArg (a, sig') ->
675 let f = eval_sign sig' in
676 begin fun tac vals ist -> match vals with
677 | [] -> assert false
678 | v :: vals ->
679 let v' = Taccoerce.Value.cast (topwit (Egramml.proj_symbol a)) v in
680 f (tac v') vals ist
681 end tac
682
683 let eval : ty_ml -> Geninterp.Val.t list -> Geninterp.interp_sign -> unit Proofview.tactic = function
684 | TyML (t,tac) -> eval_sign t tac
685 let eval_of_ty_ml = eval
686
687 let is_constr_entry = function
688 | TUentry a -> Option.has_some @@ genarg_type_eq (ExtraArg a) Stdarg.wit_constr
689 | _ -> false
690
691 let rec only_constr : type a. a ty_sig -> bool = function
692 | TyNil -> true
693 | TyIdent(_,_) -> false
694 | TyArg (u, s) -> if is_constr_entry u then only_constr s else false
695
696 let rec mk_sign_vars : type a. int -> a ty_sig -> Name.t list = fun i tu -> match tu with
697 | TyNil -> []
698 | TyIdent (_,s) -> mk_sign_vars i s
699 | TyArg (_, s) -> Name (get_identifier i) :: mk_sign_vars (i + 1) s
700
701 let dummy_id = Id.of_string "_"
702
703 let lift_constr_tac_to_ml_tac vars tac =
704 let tac _ ist = Proofview.Goal.enter begin fun gl ->
705 let env = Proofview.Goal.env gl in
706 let sigma = Proofview.Goal.sigma gl in
707 let map = function
708 | Anonymous -> None
709 | Name id ->
710 let c = Id.Map.find id ist.Geninterp.lfun in
711 try Some (Taccoerce.Value.of_constr @@ Taccoerce.coerce_to_closed_constr env c)
712 with Taccoerce.CannotCoerceTo ty ->
713 Taccoerce.error_ltac_variable dummy_id (Some (env,sigma)) c ty
714 in
715 let args = List.map_filter map vars in
716 tac args ist
717 end in
718 tac
719
720 let tactic_extend plugin_name tacname ~level ?deprecation sign =
721 let open Tacexpr in
722 let ml_tactic_name =
723 { mltac_tactic = tacname;
724 mltac_plugin = plugin_name }
725 in
726 match sign with
727 | [TyML (TyIdent (name, s),tac) as ml_tac] when only_constr s ->
728 (* The extension is only made of a name followed by constr
729 entries: we do not add any grammar nor printing rule and add it
730 as a true Ltac definition. *)
731 let vars = mk_sign_vars 1 s in
732 let ml = { Tacexpr.mltac_name = ml_tactic_name; Tacexpr.mltac_index = 0 } in
733 let tac = match s with
734 | TyNil -> eval ml_tac
735 (* Special handling of tactics without arguments: such tactics do
736 not do a Proofview.Goal.nf_enter to compute their arguments. It
737 matters for some whole-prof tactics like [shelve_unifiable]. *)
738 | _ -> lift_constr_tac_to_ml_tac vars (eval ml_tac)
739 in
740 (* Arguments are not passed directly to the ML tactic in the TacML
741 node, the ML tactic retrieves its arguments in the [ist]
742 environment instead. This is the rĂ´le of the
743 [lift_constr_tac_to_ml_tac] function. *)
744 let body = CAst.make (Tacexpr.TacFun (vars, CAst.make (Tacexpr.TacML (ml, [])))) in
745 let id = Names.Id.of_string name in
746 let obj () = Tacenv.register_ltac true false id body ?deprecation in
747 let () = Tacenv.register_ml_tactic ml_tactic_name [|tac|] in
748 Mltop.(declare_cache_obj_full (interp_only_obj obj) plugin_name)
749 | _ ->
750 let synterp () =
751 synterp_add_ml_tactic_notation ml_tactic_name ~level ?deprecation (List.map clause_of_ty_ml sign)
752 in
753 let interp = interp_add_ml_tactic_notation in
754 Tacenv.register_ml_tactic ml_tactic_name @@ Array.of_list (List.map eval sign);
755 Mltop.declare_cache_obj_full (CacheObj {synterp; interp}) plugin_name
756
757 type (_, 'a) ml_ty_sig =
758 | MLTyNil : ('a, 'a) ml_ty_sig
759 | MLTyArg : ('r, 'a) ml_ty_sig -> (Geninterp.Val.t -> 'r, 'a) ml_ty_sig
760
761 let rec ml_sig_len : type r a. (r, a) ml_ty_sig -> int = function
762 | MLTyNil -> 0
763 | MLTyArg sign -> 1 + ml_sig_len sign
764
765 let rec cast_ml : type r a. (r, a) ml_ty_sig -> r -> Geninterp.Val.t list -> a =
766 fun sign f ->
767 match sign with
768 | MLTyNil ->
769 begin function
770 | [] -> f
771 | _ :: _ -> CErrors.anomaly (str "Arity mismatch")
772 end
773 | MLTyArg sign ->
774 function
775 | [] -> CErrors.anomaly (str "Arity mismatch")
776 | arg :: args -> cast_ml sign (f arg) args
777
778 let ml_tactic_extend ~plugin ~name ~local ?deprecation sign tac =
779 let open Tacexpr in
780 let tac args _ = cast_ml sign tac args in
781 let ml_tactic_name = { mltac_tactic = name; mltac_plugin = plugin } in
782 let ml = { mltac_name = ml_tactic_name; mltac_index = 0 } in
783 let len = ml_sig_len sign in
784 let args = List.init len (fun i -> Id.of_string (Printf.sprintf "arg%i" i)) in
785 let vars = List.map (fun id -> Name id) args in
786 let args = List.map (fun id -> Reference (Locus.ArgVar (CAst.make id))) args in
787 let body = CAst.make (Tacexpr.TacFun (vars, CAst.make (Tacexpr.TacML (ml, args)))) in
788 let id = Names.Id.of_string name in
789 let obj () = Tacenv.register_ltac true local id body ?deprecation in
790 let () = Tacenv.register_ml_tactic ml_tactic_name [|tac|] in
791 Mltop.(declare_cache_obj_full (interp_only_obj obj) plugin)
792
793 module MLName =
794 struct
795 open Tacexpr
796 type t = ml_tactic_name
797 let compare tac1 tac2 =
798 let c = String.compare tac1.mltac_tactic tac2.mltac_tactic in
799 if c = 0 then String.compare tac1.mltac_plugin tac2.mltac_plugin
800 else c
801 end
802
803 module MLTacMap = Map.Make(MLName)
804
805 let ml_table : (Geninterp.Val.t list -> Geninterp.Val.t Ftactic.t) MLTacMap.t ref = ref MLTacMap.empty
806
807 type ml_ltac_val = {
808 tacval_tac : Tacexpr.ml_tactic_name;
809 tacval_var : Id.t list;
810 }
811
812 let in_tacval =
813 (* This is a hack to emulate value-returning ML-implemented tactics in Ltac.
814 We use a dummy generic argument to work around the limitations of the Ltac
815 runtime. Indeed, the TacML node needs to return unit values, since it is
816 considered a "tactic" in the runtime. Changing it to allow arbitrary values
817 would require to toggle this status, and thus to make it a "value" node.
818 This would in turn create too much backwards incompatibility. Instead, we
819 piggy back on the TacGeneric node, which by construction is used to return
820 values.
821
822 The trick is to represent a n-ary application of a ML function as a generic
823 argument. We store in the node the name of the tactic and its arity, while
824 giving canonical names to the bound variables of the closure. This trick is
825 already performed in several external developments for specific calls, we
826 make it here generic. The argument should not be used for other purposes, so
827 we only export the registering functions.
828 *)
829 let wit : (Empty.t, ml_ltac_val, Geninterp.Val.t) Genarg.genarg_type =
830 Genarg.create_arg "ltac:val"
831 in
832 (* No need to internalize this ever *)
833 let intern_fun _ e = Empty.abort e in
834 let subst_fun s v = v in
835 let () = Genintern.register_intern0 wit intern_fun in
836 let () = Gensubst.register_subst0 wit subst_fun in
837 (* No need to register a value tag for it via register_val0 since we will
838 never access this genarg directly. *)
839 let interp_fun ist tac =
840 let args = List.map (fun id -> Id.Map.get id ist.Geninterp.lfun) tac.tacval_var in
841 let tac = MLTacMap.get tac.tacval_tac !ml_table in
842 tac args
843 in
844 let () = Geninterp.register_interp0 wit interp_fun in
845 (fun v -> Genarg.in_gen (Genarg.Glbwit wit) v)
846
847
848 let ml_val_tactic_extend ~plugin ~name ~local ?deprecation sign tac =
849 let open Tacexpr in
850 let tac args = cast_ml sign tac args in
851 let ml_tactic_name = { mltac_tactic = name; mltac_plugin = plugin } in
852 let len = ml_sig_len sign in
853 let vars = List.init len (fun i -> Id.of_string (Printf.sprintf "arg%i" i)) in
854 let body = TacGeneric (None, in_tacval { tacval_tac = ml_tactic_name; tacval_var = vars }) in
855 let vars = List.map (fun id -> Name id) vars in
856 let body = CAst.make (Tacexpr.TacFun (vars, CAst.make (Tacexpr.TacArg body))) in
857 let id = Names.Id.of_string name in
858 let obj () = Tacenv.register_ltac true local id body ?deprecation in
859 let () = assert (not @@ MLTacMap.mem ml_tactic_name !ml_table) in
860 let () = ml_table := MLTacMap.add ml_tactic_name tac !ml_table in
861 Mltop.(declare_cache_obj_full (interp_only_obj obj) plugin)
862
863 (** ARGUMENT EXTEND *)
864
865 open Geninterp
866
867 type ('a, 'b, 'c) argument_printer =
868 'a Pptactic.raw_extra_genarg_printer *
869 'b Pptactic.glob_extra_genarg_printer *
870 'c Pptactic.extra_genarg_printer
871
872 type ('a, 'b) argument_intern =
873 | ArgInternFun : ('a, 'b) Genintern.intern_fun -> ('a, 'b) argument_intern
874 | ArgInternWit : ('a, 'b, 'c) Genarg.genarg_type -> ('a, 'b) argument_intern
875
876 type 'b argument_subst =
877 | ArgSubstFun : 'b Gensubst.subst_fun -> 'b argument_subst
878 | ArgSubstWit : ('a, 'b, 'c) Genarg.genarg_type -> 'b argument_subst
879
880 type ('b, 'c) argument_interp =
881 | ArgInterpRet : ('c, 'c) argument_interp
882 | ArgInterpFun : ('b, Val.t) interp_fun -> ('b, 'c) argument_interp
883 | ArgInterpWit : ('a, 'b, 'r) Genarg.genarg_type -> ('b, 'c) argument_interp
884 | ArgInterpSimple :
885 (Geninterp.interp_sign -> Environ.env -> Evd.evar_map -> 'b -> 'c) -> ('b, 'c) argument_interp
886
887 type ('a, 'b, 'c) tactic_argument = {
888 arg_parsing : 'a Vernacextend.argument_rule;
889 arg_tag : 'c Val.tag option;
890 arg_intern : ('a, 'b) argument_intern;
891 arg_subst : 'b argument_subst;
892 arg_interp : ('b, 'c) argument_interp;
893 arg_printer : ('a, 'b, 'c) argument_printer;
894 }
895
896 let intern_fun (type a b c) name (arg : (a, b, c) tactic_argument) : (a, b) Genintern.intern_fun =
897 match arg.arg_intern with
898 | ArgInternFun f -> f
899 | ArgInternWit wit ->
900 fun ist v ->
901 let ans = Genarg.out_gen (glbwit wit) (Tacintern.intern_genarg ist (Genarg.in_gen (rawwit wit) v)) in
902 (ist, ans)
903
904 let subst_fun (type a b c) (arg : (a, b, c) tactic_argument) : b Gensubst.subst_fun =
905 match arg.arg_subst with
906 | ArgSubstFun f -> f
907 | ArgSubstWit wit ->
908 fun s v ->
909 let ans = Genarg.out_gen (glbwit wit) (Tacsubst.subst_genarg s (Genarg.in_gen (glbwit wit) v)) in
910 ans
911
912 let interp_fun (type a b c) name (arg : (a, b, c) tactic_argument) (tag : c Val.tag) : (b, Val.t) interp_fun =
913 match arg.arg_interp with
914 | ArgInterpRet -> (fun ist v -> Ftactic.return (Geninterp.Val.inject tag v))
915 | ArgInterpFun f -> f
916 | ArgInterpWit wit ->
917 (fun ist x -> Tacinterp.interp_genarg ist (Genarg.in_gen (glbwit wit) x))
918 | ArgInterpSimple f ->
919 (fun ist v -> Ftactic.enter begin fun gl ->
920 let env = Proofview.Goal.env gl in
921 let sigma = Proofview.Goal.sigma gl in
922 let v = f ist env sigma v in
923 Ftactic.return (Geninterp.Val.inject tag v)
924 end)
925
926 let argument_extend (type a b c) ~plugin ~name ~ignore_kw (arg : (a, b, c) tactic_argument) =
927 let wit = Genarg.create_arg name in
928 let () = Genintern.register_intern0 wit (intern_fun name arg) in
929 let () = Gensubst.register_subst0 wit (subst_fun arg) in
930 let tag = match arg.arg_tag with
931 | None ->
932 let () = register_val0 wit None in
933 val_tag (topwit wit)
934 | Some tag ->
935 let () = register_val0 wit (Some tag) in
936 tag
937 in
938 let () = register_interp0 wit (interp_fun name arg tag) in
939 let entry = match arg.arg_parsing with
940 | Vernacextend.Arg_alias e ->
941 let () = Procq.register_grammar wit e in
942 e
943 | Vernacextend.Arg_rules rules ->
944 let e = Procq.create_generic_entry2 name (Genarg.rawwit wit) in
945 let plugin_uid = (plugin, "argextend:"^name) in
946 let () = Egramml.grammar_extend ~plugin_uid ~ignore_kw
947 e (Procq.Fresh (Gramlib.Gramext.First, [None, Some RightA, rules])) in
948 e
949 in
950 let (rpr, gpr, tpr) = arg.arg_printer in
951 let () = Pptactic.declare_extra_genarg_pprule wit rpr gpr tpr in
952 let () = create_ltac_quotation ~plugin name
953 (fun (loc, v) -> Tacexpr.TacGeneric (Some name,Genarg.in_gen (Genarg.rawwit wit) v))
954 (entry, None)
955 in
956 (wit, entry)