Debian Codegraph @

tactics/hints.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 Util
13 open CErrors
14 open Names
15 open Constr
16 open Context
17 open Evd
18 open EConstr
19 open Vars
20 open Environ
21 open Mod_subst
22 open Globnames
23 open Libobject
24 open Namegen
25 open Libnames
26 open Termops
27 open Inductiveops
28 open Typeclasses
29 open Pattern
30 open Patternops
31 open Tacred
32 open Printer
33
34 module NamedDecl = Context.Named.Declaration
35
36 (****************************************)
37 (* General functions *)
38 (****************************************)
39
40 type debug = Debug | Info | Off
41
42 exception Bound
43
44 let rec head_bound sigma t = match EConstr.kind sigma t with
45 | Prod (_, _, b) -> head_bound sigma b
46 | LetIn (_, _, _, b) -> head_bound sigma b
47 | App (c, _) -> head_bound sigma c
48 | Case (_, _, _, _, _, c, _) -> head_bound sigma c
49 | Ind (ind, _) -> GlobRef.IndRef ind
50 | Const (c, _) -> GlobRef.ConstRef c
51 | Construct (c, _) -> GlobRef.ConstructRef c
52 | Var id -> GlobRef.VarRef id
53 | Proj (p, _, _) -> GlobRef.ConstRef (Projection.constant p)
54 | Cast (c, _, _) -> head_bound sigma c
55 | Evar _ | Rel _ | Meta _ | Sort _ | Fix _ | Lambda _
56 | CoFix _ | Int _ | Float _ | String _ | Array _ -> raise Bound
57
58 let head_constr sigma c =
59 try head_bound sigma c
60 with Bound -> user_err (Pp.str "Head identifier must be a constant, section variable, \
61 (co)inductive type, (co)inductive type constructor, or projection.")
62
63 let decompose_app_bound sigma t =
64 let t = strip_outer_cast sigma t in
65 let _,ccl = decompose_prod_decls sigma t in
66 let hd,args = decompose_app sigma ccl in
67 let open GlobRef in
68 match EConstr.kind sigma hd with
69 | Const (c,u) -> ConstRef c, args
70 | Ind (i,u) -> IndRef i, args
71 | Construct (c,u) -> ConstructRef c, args
72 | Var id -> VarRef id, args
73 | Proj (p, _, c) -> ConstRef (Projection.constant p), Array.cons c args
74 | _ -> raise Bound
75
76 (** Compute the set of section variables that remain in the named context.
77 Starts from the top to the bottom of the context, stops at the first
78 different declaration between the named hyps and the section context. *)
79 let secvars_of_hyps hyps =
80 let secctx = Global.named_context () in
81 let open Context.Named.Declaration in
82 let pred, all =
83 List.fold_left (fun (pred,all) decl ->
84 try let _ = Context.Named.lookup (get_id decl) hyps in
85 (* Approximation, it might be an hypothesis reintroduced with same name and unconvertible types,
86 we must allow it currently, as comparing the declarations for syntactic equality is too
87 strong a check (e.g. an unfold in a section variable would make it unusable). *)
88 (Id.Pred.add (get_id decl) pred, all)
89 with Not_found -> (pred, false))
90 (Id.Pred.empty,true) secctx
91 in
92 if all then Id.Pred.full (* If the whole section context is available *)
93 else pred
94
95 let empty_hint_info =
96 { hint_priority = None; hint_pattern = None }
97
98 (************************************************************************)
99 (* The Type of Constructions Autotactic Hints *)
100 (************************************************************************)
101
102 type 'a hint_ast =
103 | Res_pf of 'a (* Hint Apply *)
104 | ERes_pf of 'a (* Hint EApply *)
105 | Give_exact of 'a
106 | Res_pf_THEN_trivial_fail of 'a (* Hint Immediate *)
107 | Unfold_nth of Evaluable.t (* Hint Unfold *)
108 | Extern of Pattern.constr_pattern option * Gentactic.glob_generic_tactic (* Hint Extern *)
109
110
111 type 'a hints_path_atom_gen =
112 | PathHints of 'a list
113 (* For forward hints, their names is the list of projections *)
114 | PathAny
115
116 type hints_path_atom = GlobRef.t hints_path_atom_gen
117
118 type 'a hints_path_gen =
119 | PathAtom of 'a hints_path_atom_gen
120 | PathStar of 'a hints_path_gen
121 | PathSeq of 'a hints_path_gen * 'a hints_path_gen
122 | PathOr of 'a hints_path_gen * 'a hints_path_gen
123 | PathEmpty
124 | PathEpsilon
125
126 type pre_hints_path = Libnames.qualid hints_path_gen
127 type hints_path = GlobRef.t hints_path_gen
128
129 type hint_term =
130 | IsGlobRef of GlobRef.t
131 | IsConstr of constr * UnivGen.sort_context_set option (* None if monomorphic *)
132
133 type 'a with_uid = {
134 obj : 'a;
135 uid : KerName.t;
136 }
137
138 type raw_hint = {
139 rhint_term : constr;
140 rhint_type : types;
141 rhint_uctx : UnivGen.sort_context_set option;
142 rhint_arty : int; (* Number of goals generated by the intended tactic *)
143 }
144
145 type hint = {
146 hint_term : constr;
147 hint_type : types;
148 hint_uctx : UnivGen.sort_context_set option; (* None if monomorphic *)
149 hint_clnv : Clenv.clausenv;
150 hint_arty : int; (* Number of goals generated by the intended tactic *)
151 }
152
153 type hint_pattern =
154 | DefaultPattern
155 | ConstrPattern of constr_pattern
156 | SyntacticPattern of constr_pattern
157
158 type ('a,'db) with_metadata =
159 { pri : int
160 (** A number lower is higher priority *)
161 ; pat : hint_pattern option
162 (** A pattern for the concl of the Goal *)
163 ; name : GlobRef.t option
164 (** A potential name to refer to the hint *)
165 ; db : 'db
166 (** The database from which the hint comes *)
167 ; secvars : Id.Pred.t
168 (** The set of section variables the hint depends on *)
169 ; code : 'a
170 (** the tactic to apply when the concl matches pat *)
171 }
172
173 type hint_db_name = string
174
175 (* db = None for local database (ie built from goal hyps) *)
176 type full_hint = (hint hint_ast with_uid, hint_db_name option) with_metadata
177
178 type hint_entry = GlobRef.t option *
179 (raw_hint hint_ast with_uid, unit) with_metadata
180
181 type hint_mode =
182 | ModeInput (* No evars *)
183 | ModeNoHeadEvar (* No evar at the head *)
184 | ModeOutput (* Anything *)
185
186 module Modes =
187 struct
188 type t = hint_mode array list GlobRef.Map.t
189 let empty = GlobRef.Map.empty
190 let union m1 m2 = GlobRef.Map.union (fun _ m1 m2 -> Some (m1@m2)) m1 m2
191 end
192
193 type 'a hints_transparency_target =
194 | HintsVariables
195 | HintsConstants
196 | HintsProjections
197 | HintsReferences of 'a list
198
199 let hint_as_term h = (h.hint_uctx, h.hint_term)
200
201 let fresh_key =
202 let id = Summary.ref ~name:"HINT-COUNTER" 0 in
203 fun () ->
204 let cur = incr id; !id in
205 let lbl = Id.of_string ("_" ^ string_of_int cur) in
206 let kn = Lib.make_kn lbl in
207 let (mp, _) = KerName.repr kn in
208 (* We embed the full path of the kernel name in the label so that
209 the identifier should be unique. This ensures that including
210 two modules together won't confuse the corresponding labels. *)
211 let lbl = Id.of_string_soft (Printf.sprintf "%s#%i"
212 (ModPath.to_string mp) cur)
213 in
214 KerName.make mp lbl
215
216 let pri_order_int (id1, {pri=pri1}) (id2, {pri=pri2}) =
217 let d = Int.compare pri1 pri2 in
218 if Int.equal d 0 then Int.compare id2 id1
219 else d
220
221 let get_default_pattern (h : hint hint_ast) = match h with
222 | Give_exact h -> h.hint_type
223 | Res_pf h | ERes_pf h | Res_pf_THEN_trivial_fail h ->
224 Clenv.clenv_type h.hint_clnv
225 | Unfold_nth _ | Extern _ ->
226 (* These hints cannot contain DefaultPattern *)
227 assert false
228
229 (* Nov 98 -- Papageno *)
230 (* Les Hints sont ré-organisés en plusieurs databases.
231
232 La table impérative "searchtable", de type "hint_db_table",
233 associe une database (hint_db) à chaque nom.
234
235 Une hint_db est une table d'association fonctionelle constr -> search_entry
236 Le constr correspond à la constante de tête de la conclusion.
237
238 Une search_entry est un triplet comprenant :
239 - la liste des tactiques qui n'ont pas de pattern associé
240 - la liste des tactiques qui ont un pattern
241 - un discrimination net borné (Btermdn.t) constitué de tous les
242 patterns de la seconde liste de tactiques *)
243
244 type stored_data = int * full_hint
245 (* First component is the index of insertion in the table, to keep most recent first semantics. *)
246
247 module Stored =
248 struct
249 type t = stored_data
250 let compare = pri_order_int
251 end
252
253 module StoredSet = Set.Make(Stored)
254
255 let merge_set s l = List.merge Stored.compare (StoredSet.elements s) l
256
257 module Bounded_net :
258 sig
259 type t
260 val empty : TransparentState.t option -> t
261 val build : TransparentState.t option -> StoredSet.t -> t
262 val add : t -> hint_pattern -> stored_data -> t
263 val lookup : Environ.env -> Evd.evar_map -> t -> EConstr.constr -> stored_data list
264 end =
265 struct
266 module Bnet = Btermdn.Make(Stored)
267
268 type diff = hint_pattern * stored_data
269
270 type data =
271 | Bnet of (TransparentState.t option * Bnet.t)
272 | Diff of diff * data ref
273 | Build of TransparentState.t option * StoredSet.t
274
275 type t = data ref
276
277 let empty st = ref (Bnet (st, Bnet.empty))
278
279 let add net p v = ref (Diff ((p, v), net))
280
281 let build st data = ref (Build (st, data))
282
283 let add0 env sigma st p v dn =
284 (* Feedback.msg_debug (let v1 = v in Pp.(str "add0: " ++ Pp.pr_opt Names.GlobRef.print (snd v1).name)); *)
285 let p = match p with
286 | ConstrPattern p -> Bnet.pattern env st p
287 | SyntacticPattern p -> Bnet.pattern_syntactic env p
288 | DefaultPattern ->
289 let c = get_default_pattern (snd v).code.obj in
290 Bnet.constr_pattern env sigma st c
291 in
292 Bnet.add dn p v
293
294 let rec force env sigma net = match !net with
295 | Bnet dn -> dn
296 | Diff ((p, v), rem) ->
297 let st, dn = force env sigma rem in
298 let dn = add0 env sigma st p v dn in
299 let () = net := (Bnet (st, dn)) in
300 st, dn
301 | Build (st, data) ->
302 let fold v dn = add0 env sigma st (Option.get (snd v).pat) v dn in
303 let ans = StoredSet.fold fold data Bnet.empty in
304 let () = net := Bnet (st, ans) in
305 st, ans
306
307 let lookup env sigma net p =
308 let st, dn = force env sigma net in
309 Bnet.lookup env sigma st dn p
310 end
311
312 module StoredData :
313 sig
314 type t
315 val empty : t
316 val mem : KerName.t -> t -> bool
317 val add : stored_data -> t -> t
318 val remove : Environ.env -> GlobRef.Set_env.t -> t -> t
319 val elements : t -> StoredSet.t
320 end =
321 struct
322
323 type t = {
324 data : StoredSet.t;
325 set : KerName.Set.t;
326 }
327
328 let empty = { data = StoredSet.empty; set = KerName.Set.empty }
329
330 let mem kn sd = KerName.Set.mem kn sd.set
331
332 let add t sd = {
333 data = StoredSet.add t sd.data;
334 set = KerName.Set.add (snd t).code.uid sd.set;
335 }
336
337 let remove env grs sd =
338 let fold ((_, h) as v) (accu, ans) =
339 let keep = match h.name with
340 | Some gr -> not (GlobRef.Set_env.mem (Environ.QGlobRef.canonize env gr) grs)
341 | None -> true
342 in
343 if keep then (accu, StoredSet.add v ans) else (KerName.Set.remove h.code.uid accu, ans)
344 in
345 let set, data = StoredSet.fold fold sd.data (sd.set, StoredSet.empty) in
346 if set == sd.set then sd
347 else { data = data; set }
348
349 let elements v = v.data
350
351 end
352
353 type search_entry = {
354 sentry_nopat : StoredData.t;
355 sentry_pat : StoredData.t;
356 sentry_bnet : Bounded_net.t;
357 sentry_mode : hint_mode array list;
358 }
359
360 let empty_se st = {
361 sentry_nopat = StoredData.empty;
362 sentry_pat = StoredData.empty;
363 sentry_bnet = Bounded_net.empty st;
364 sentry_mode = [];
365 }
366
367 let add_tac pat t se =
368 match pat with
369 | None ->
370 let uid = (snd t).code.uid in
371 if StoredData.mem uid se.sentry_nopat then se
372 else { se with sentry_nopat = StoredData.add t se.sentry_nopat }
373 | Some pat ->
374 let uid = (snd t).code.uid in
375 if StoredData.mem uid se.sentry_pat then se
376 else { se with
377 sentry_pat = StoredData.add t se.sentry_pat;
378 sentry_bnet = Bounded_net.add se.sentry_bnet pat t; }
379
380 let rebuild_dn st se =
381 let dn' = Bounded_net.build st (StoredData.elements se.sentry_pat) in
382 { se with sentry_bnet = dn' }
383
384 let lookup_tacs env sigma concl se =
385 let l' = Bounded_net.lookup env sigma se.sentry_bnet concl in
386 let sl' = List.stable_sort pri_order_int l' in
387 merge_set (StoredData.elements se.sentry_nopat) sl'
388
389 let merge_context_set_opt sigma ctx = match ctx with
390 | None -> sigma
391 | Some ctx -> Evd.merge_sort_context_set Evd.univ_flexible ~src:UState.Internal sigma ctx
392
393 let instantiate_hint env sigma p =
394 let mk_clenv { rhint_term = c; rhint_type = cty; rhint_uctx = ctx; rhint_arty = ar } =
395 let sigma = merge_context_set_opt sigma ctx in
396 let cl = Clenv.mk_clenv_from env sigma (c,cty) in
397 let cl = Clenv.clenv_strip_proj_params cl in
398 { hint_term = c; hint_type = cty; hint_uctx = ctx; hint_clnv = cl; hint_arty = ar }
399 in
400 let code = match p.code.obj with
401 | Res_pf c -> Res_pf (mk_clenv c)
402 | ERes_pf c -> ERes_pf (mk_clenv c)
403 | Res_pf_THEN_trivial_fail c ->
404 Res_pf_THEN_trivial_fail (mk_clenv c)
405 | Give_exact c -> Give_exact (mk_clenv c)
406 | (Unfold_nth _ | Extern _) as h -> h
407 in
408 { p with code = { p.code with obj = code } }
409
410 let hint_mode_eq m1 m2 = match m1, m2 with
411 | ModeInput, ModeInput -> true
412 | ModeNoHeadEvar, ModeNoHeadEvar -> true
413 | ModeOutput, ModeOutput -> true
414 | (ModeInput | ModeNoHeadEvar | ModeOutput), _ -> false
415
416 let hints_path_atom_eq env h1 h2 = match h1, h2 with
417 | PathHints l1, PathHints l2 -> List.equal (fun gr1 gr2 -> QGlobRef.equal env gr1 gr2) l1 l2
418 | PathAny, PathAny -> true
419 | _ -> false
420
421 let rec hints_path_eq env h1 h2 = match h1, h2 with
422 | PathAtom h1, PathAtom h2 -> hints_path_atom_eq env h1 h2
423 | PathStar h1, PathStar h2 -> hints_path_eq env h1 h2
424 | PathSeq (l1, r1), PathSeq (l2, r2) ->
425 hints_path_eq env l1 l2 && hints_path_eq env r1 r2
426 | PathOr (l1, r1), PathOr (l2, r2) ->
427 hints_path_eq env l1 l2 && hints_path_eq env r1 r2
428 | PathEmpty, PathEmpty -> true
429 | PathEpsilon, PathEpsilon -> true
430 | _ -> false
431
432 let path_matches env hp hints =
433 let rec aux hp hints k =
434 match hp, hints with
435 | PathAtom _, [] -> false
436 | PathAtom PathAny, (_ :: hints') -> k hints'
437 | PathAtom p, (h :: hints') ->
438 if hints_path_atom_eq env p h then k hints' else false
439 | PathStar hp', hints ->
440 k hints || aux hp' hints (fun hints' -> aux hp hints' k)
441 | PathSeq (hp, hp'), hints ->
442 aux hp hints (fun hints' -> aux hp' hints' k)
443 | PathOr (hp, hp'), hints ->
444 aux hp hints k || aux hp' hints k
445 | PathEmpty, _ -> false
446 | PathEpsilon, hints -> k hints
447 in aux hp hints (fun hints' -> true)
448
449 let rec matches_epsilon = function
450 | PathAtom _ -> false
451 | PathStar _ -> true
452 | PathSeq (p, p') -> matches_epsilon p && matches_epsilon p'
453 | PathOr (p, p') -> matches_epsilon p || matches_epsilon p'
454 | PathEmpty -> false
455 | PathEpsilon -> true
456
457 let path_matches_epsilon = matches_epsilon
458
459 let rec is_empty = function
460 | PathAtom _ -> false
461 | PathStar _ -> false
462 | PathSeq (p, p') -> is_empty p || is_empty p'
463 | PathOr (p, p') -> matches_epsilon p && matches_epsilon p'
464 | PathEmpty -> true
465 | PathEpsilon -> false
466
467 let path_seq p p' =
468 match p, p' with
469 | PathEpsilon, p' -> p'
470 | p, PathEpsilon -> p
471 | p, p' -> PathSeq (p, p')
472
473 let rec path_derivate env hp hint =
474 let rec derivate_atoms env hints hints' =
475 match hints, hints' with
476 | gr :: grs, gr' :: grs' when QGlobRef.equal env gr gr' -> derivate_atoms env grs grs'
477 | [], [] -> PathEpsilon
478 | [], hints -> PathEmpty
479 | grs, [] -> PathAtom (PathHints grs)
480 | _, _ -> PathEmpty
481 in
482 match hp with
483 | PathAtom PathAny -> PathEpsilon
484 | PathAtom (PathHints grs) ->
485 (match grs, hint with
486 | h :: _, PathAny -> PathEmpty
487 | hints, PathHints hints' -> derivate_atoms env hints hints'
488 | _, _ -> assert false)
489 | PathStar p -> if path_matches env p [hint] then hp else PathEpsilon
490 | PathSeq (hp, hp') ->
491 let hpder = path_derivate env hp hint in
492 if matches_epsilon hp then
493 PathOr (path_seq hpder hp', path_derivate env hp' hint)
494 else if is_empty hpder then PathEmpty
495 else path_seq hpder hp'
496 | PathOr (hp, hp') ->
497 PathOr (path_derivate env hp hint, path_derivate env hp' hint)
498 | PathEmpty -> PathEmpty
499 | PathEpsilon -> PathEmpty
500
501 let rec normalize_path env h =
502 match h with
503 | PathStar PathEpsilon -> PathEpsilon
504 | PathOr (p, q) ->
505 (match normalize_path env p with
506 | PathEmpty -> normalize_path env q
507 | p' ->
508 match normalize_path env q with
509 | PathEmpty -> p'
510 | q' -> if hints_path_eq env p' q' then p' else PathOr (p', q'))
511 | PathSeq (p, q) ->
512 (match normalize_path env p with
513 | PathEmpty -> PathEmpty
514 | PathEpsilon -> normalize_path env q
515 | p' ->
516 match normalize_path env q with
517 | PathEmpty -> PathEmpty
518 | PathEpsilon -> p'
519 | q' -> PathSeq (p', q'))
520 | _ -> h
521
522 let path_derivate env hp hint =
523 let hint = match hint with
524 | None -> PathAny
525 | Some gr -> PathHints [gr]
526 in
527 normalize_path env (path_derivate env hp hint)
528
529 let pp_hints_path_atom prg a =
530 match a with
531 | PathAny -> str"_"
532 | PathHints grs -> pr_sequence prg grs
533
534 let pp_hints_path_gen prg =
535 let rec aux = function
536 | PathAtom pa -> pp_hints_path_atom prg pa
537 | PathStar (PathAtom PathAny) -> str"_*"
538 | PathStar p -> str "(" ++ aux p ++ str")*"
539 | PathSeq (p, p') -> aux p ++ spc () ++ aux p'
540 | PathOr (p, p') ->
541 str "(" ++ aux p ++ spc () ++ str"|" ++ cut () ++ spc () ++
542 aux p' ++ str ")"
543 | PathEmpty -> str"emp"
544 | PathEpsilon -> str"eps"
545 in aux
546
547 let pp_hints_path = pp_hints_path_gen pr_global
548
549 let glob_hints_path_atom p =
550 match p with
551 | PathHints g -> PathHints (List.map Nametab.global g)
552 | PathAny -> PathAny
553
554 let glob_hints_path =
555 let rec aux = function
556 | PathAtom pa -> PathAtom (glob_hints_path_atom pa)
557 | PathStar p -> PathStar (aux p)
558 | PathSeq (p, p') -> PathSeq (aux p, aux p')
559 | PathOr (p, p') -> PathOr (aux p, aux p')
560 | PathEmpty -> PathEmpty
561 | PathEpsilon -> PathEpsilon
562 in aux
563
564 let subst_path_atom subst p =
565 match p with
566 | PathAny -> p
567 | PathHints grs ->
568 let gr' gr = fst (subst_global subst gr) in
569 let grs' = List.Smart.map gr' grs in
570 if grs' == grs then p else PathHints grs'
571
572 let rec subst_hints_path subst hp =
573 match hp with
574 | PathAtom p ->
575 let p' = subst_path_atom subst p in
576 if p' == p then hp else PathAtom p'
577 | PathStar p -> let p' = subst_hints_path subst p in
578 if p' == p then hp else PathStar p'
579 | PathSeq (p, q) ->
580 let p' = subst_hints_path subst p in
581 let q' = subst_hints_path subst q in
582 if p' == p && q' == q then hp else PathSeq (p', q')
583 | PathOr (p, q) ->
584 let p' = subst_hints_path subst p in
585 let q' = subst_hints_path subst q in
586 if p' == p && q' == q then hp else PathOr (p', q')
587 | _ -> hp
588
589 type mode_match =
590 | NoMode
591 | WithMode of hint_mode array
592
593 type 'a with_mode =
594 | ModeMatch of mode_match * 'a
595 | ModeMismatch
596
597 module Hint_db :
598 sig
599 type t
600 val empty : ?name:hint_db_name -> TransparentState.t -> bool -> t
601 val map_none : secvars:Id.Pred.t -> t -> full_hint list
602 val map_all : secvars:Id.Pred.t -> GlobRef.t -> t -> full_hint list
603 val map_eauto : Environ.env -> evar_map -> secvars:Id.Pred.t ->
604 (GlobRef.t * constr array) -> constr -> t -> full_hint list with_mode
605 val map_auto : Environ.env -> evar_map -> secvars:Id.Pred.t ->
606 (GlobRef.t * constr array) -> constr -> t -> full_hint list
607 val add_list : env -> evar_map -> hint_entry list -> t -> t
608 val remove_one : Environ.env -> GlobRef.t -> t -> t
609 val remove_list : Environ.env -> GlobRef.t list -> t -> t
610 val iter : (GlobRef.t option -> hint_mode array list -> full_hint list -> unit) -> t -> unit
611 val use_dn : t -> bool
612 val transparent_state : t -> TransparentState.t
613 val set_transparent_state : t -> TransparentState.t -> t
614 val add_cut : Environ.env -> hints_path -> t -> t
615 val add_mode : GlobRef.t -> hint_mode array -> t -> t
616 val cut : t -> hints_path
617 val unfolds : t -> Id.Set.t * Cset.t * PRset.t
618 val add_modes : hint_mode array list GlobRef.Map.t -> t -> t
619 val modes : t -> hint_mode array list GlobRef.Map.t
620 val find_mode : env -> GlobRef.t -> t -> hint_mode array list
621 val fold : (GlobRef.t option -> hint_mode array list -> full_hint list -> 'a -> 'a) ->
622 t -> 'a -> 'a
623 end =
624 struct
625
626 type t = {
627 hintdb_state : TransparentState.t;
628 hintdb_cut : hints_path;
629 hintdb_unfolds : Id.Set.t * Cset.t * PRset.t;
630 hintdb_max_id : int;
631 use_dn : bool;
632 hintdb_map : search_entry GlobRef.Map.t;
633 (* A list of unindexed entries with no associated pattern. *)
634 hintdb_nopat : stored_data list;
635 hintdb_name : string option;
636 }
637
638 let next_hint_id db =
639 let h = db.hintdb_max_id in
640 { db with hintdb_max_id = succ db.hintdb_max_id }, h
641
642 let empty ?name st use_dn = { hintdb_state = st;
643 hintdb_cut = PathEmpty;
644 hintdb_unfolds = (Id.Set.empty, Cset.empty, PRset.empty);
645 hintdb_max_id = 0;
646 use_dn = use_dn;
647 hintdb_map = GlobRef.Map.empty;
648 hintdb_nopat = [];
649 hintdb_name = name; }
650
651 let dn_ts db = if db.use_dn then (Some db.hintdb_state) else None
652
653 let find key db =
654 try GlobRef.Map.find key db.hintdb_map
655 with Not_found -> empty_se (dn_ts db)
656
657 let realize_tac secvars (id,tac) =
658 if Id.Pred.subset tac.secvars secvars then Some tac
659 else
660 (* Warn about no longer typable hint? *)
661 None
662
663 let has_no_head_evar sigma c =
664 let rec hrec c = match EConstr.kind sigma c with
665 | Evar (evk,_) -> false
666 | App (c,_) -> hrec c
667 | Cast (c,_,_) -> hrec c
668 | _ -> true
669 in
670 hrec c
671
672 let match_mode sigma m arg =
673 match m with
674 | ModeInput -> not (occur_existential sigma arg)
675 | ModeNoHeadEvar -> has_no_head_evar sigma arg
676 | ModeOutput -> true
677
678 let matches_mode sigma args mode =
679 if Array.length mode == Array.length args &&
680 Array.for_all2 (match_mode sigma) mode args then Some mode
681 else None
682
683 let matches_modes sigma args modes =
684 if List.is_empty modes then Some NoMode
685 else
686 Option.map (fun x -> WithMode x) (List.find_map (matches_mode sigma args) modes)
687
688 let merge_entry secvars db nopat pat =
689 let h = List.sort pri_order_int db.hintdb_nopat in
690 let h = List.merge pri_order_int h nopat in
691 let h = List.merge pri_order_int h pat in
692 List.map_filter (realize_tac secvars) h
693
694 let map_none ~secvars db =
695 merge_entry secvars db [] []
696
697 let map_all ~secvars k db =
698 let se = find k db in
699 let h = List.sort pri_order_int db.hintdb_nopat in
700 let h = merge_set (StoredData.elements se.sentry_nopat) h in
701 let h = merge_set (StoredData.elements se.sentry_pat) h in
702 List.map_filter (realize_tac secvars) h
703
704 (* Precondition: concl has no existentials *)
705 let map_auto env sigma ~secvars (k,args) concl db =
706 let se = find k db in
707 let pat = lookup_tacs env sigma concl se in
708 merge_entry secvars db [] pat
709
710 (* [c] contains an existential *)
711 let map_eauto env sigma ~secvars (k,args) concl db =
712 let se = find k db in
713 match matches_modes sigma args se.sentry_mode with
714 | Some m ->
715 let pat = lookup_tacs env sigma concl se in
716 ModeMatch (m, merge_entry secvars db [] pat)
717 | None -> ModeMismatch
718
719 let is_exact = function
720 | Give_exact _ -> true
721 | _ -> false
722
723 let addkv gr id v db =
724 let idv = id, { v with db = db.hintdb_name } in
725 match gr with
726 | None ->
727 let is_present (_, v') = KerName.equal v.code.uid v'.code.uid in
728 if not (List.exists is_present db.hintdb_nopat) then
729 (* FIXME *)
730 { db with hintdb_nopat = idv :: db.hintdb_nopat }
731 else db
732 | Some gr ->
733 let pat =
734 if not db.use_dn && is_exact v.code.obj then None
735 else v.pat
736 in
737 let oval = find gr db in
738 { db with hintdb_map = GlobRef.Map.add gr (add_tac pat idv oval) db.hintdb_map }
739
740 let rebuild_db st' db =
741 let db' =
742 { db with hintdb_map = GlobRef.Map.map (rebuild_dn (Some st')) db.hintdb_map;
743 hintdb_state = st'; hintdb_nopat = [] }
744 in
745 List.fold_left (fun db (id, v) -> addkv None id v db) db' db.hintdb_nopat
746
747 let add_one env sigma (k, v) db =
748 let v = instantiate_hint env sigma v in
749 let db = match v.code.obj with
750 | Unfold_nth egr ->
751 let open TransparentState in
752 let ts = db.hintdb_state in
753 let (ids, csts, prjs) = db.hintdb_unfolds in
754 let state, unfs = match egr with
755 | Evaluable.EvalVarRef id ->
756 { ts with tr_var = Id.Pred.add id ts.tr_var }, (Id.Set.add id ids, csts, prjs)
757 | Evaluable.EvalConstRef cst ->
758 { ts with tr_cst = Cpred.add cst ts.tr_cst }, (ids, Cset.add cst csts, prjs)
759 | Evaluable.EvalProjectionRef p ->
760 { ts with tr_prj = PRpred.add p ts.tr_prj }, (ids, csts, PRset.add p prjs)
761 in
762 let db = { db with hintdb_unfolds = unfs } in
763 if db.use_dn then rebuild_db state db else db
764 | _ -> db
765 in
766 let db, id = next_hint_id db in
767 addkv k id v db
768
769 let add_list env sigma l db = List.fold_left (fun db k -> add_one env sigma k db) db l
770
771 let remove env st grs se =
772 let fold accu gr = GlobRef.Set_env.add (Environ.QGlobRef.canonize env gr) accu in
773 let grs = List.fold_left fold GlobRef.Set_env.empty grs in
774 let nopat = StoredData.remove env grs se.sentry_nopat in
775 let pat = StoredData.remove env grs se.sentry_pat in
776 if pat == se.sentry_pat && nopat == se.sentry_nopat then se
777 else
778 let se = { se with sentry_nopat = nopat; sentry_pat = pat } in
779 rebuild_dn st se
780
781 let remove_list env grs db =
782 let eq gr1 gr2 = QGlobRef.equal env gr1 gr2 in
783 let filter (_, h) =
784 match h.name with Some gr -> not (List.mem_f eq gr grs) | None -> true in
785 let hintmap = GlobRef.Map.map (fun e -> remove env (dn_ts db) grs e) db.hintdb_map in
786 let hintnopat = List.filter filter db.hintdb_nopat in
787 { db with hintdb_map = hintmap; hintdb_nopat = hintnopat }
788
789 let remove_one env gr db = remove_list env [gr] db
790
791 let get_entry se =
792 let h = merge_set (StoredData.elements se.sentry_nopat) (merge_set (StoredData.elements se.sentry_pat) []) in
793 List.map snd h
794
795 let iter f db =
796 let iter_se k se = f (Some k) se.sentry_mode (get_entry se) in
797 f None [] (List.map snd db.hintdb_nopat);
798 GlobRef.Map.iter iter_se db.hintdb_map
799
800 let fold f db accu =
801 let accu = f None [] (List.map snd db.hintdb_nopat) accu in
802 GlobRef.Map.fold (fun k se -> f (Some k) se.sentry_mode (get_entry se)) db.hintdb_map accu
803
804 let transparent_state db = db.hintdb_state
805
806 let set_transparent_state db st =
807 if db.use_dn then rebuild_db st db
808 else { db with hintdb_state = st }
809
810 let add_cut env path db =
811 { db with hintdb_cut = normalize_path env (PathOr (db.hintdb_cut, path)) }
812
813 let add_mode gr m db =
814 let se = find gr db in
815 let se = { se with sentry_mode = m :: List.remove (Array.equal hint_mode_eq) m se.sentry_mode } in
816 { db with hintdb_map = GlobRef.Map.add gr se db.hintdb_map }
817
818 let cut db = db.hintdb_cut
819
820 let unfolds db = db.hintdb_unfolds
821
822 let add_modes modes db =
823 let f gr e me =
824 Some { e with sentry_mode = me.sentry_mode @ e.sentry_mode }
825 in
826 let mode_entries = GlobRef.Map.map (fun m -> { (empty_se (dn_ts db)) with sentry_mode = m }) modes in
827 { db with hintdb_map = GlobRef.Map.union f db.hintdb_map mode_entries }
828
829 let modes db = GlobRef.Map.map (fun se -> se.sentry_mode) db.hintdb_map
830
831 let find_mode _env gr db = (GlobRef.Map.find gr db.hintdb_map).sentry_mode
832
833 let use_dn db = db.use_dn
834
835 end
836
837 module Hintdbmap = String.Map
838
839 type hint_db = Hint_db.t
840
841 let searchtable = Summary.ref ~name:"searchtable" Hintdbmap.empty
842
843 let searchtable_map name =
844 Hintdbmap.find name !searchtable
845 let searchtable_add (name, db) =
846 (* XXX see #21114 *)
847 (* let () = assert (Hintdbmap.mem name !searchtable) in *)
848 searchtable := Hintdbmap.add name db !searchtable
849 let searchtable_create (name, db) =
850 (* let () = assert (not @@ Hintdbmap.mem name !searchtable) in *)
851 searchtable := Hintdbmap.add name db !searchtable
852 let current_db_names () = Hintdbmap.domain !searchtable
853 let current_db () = Hintdbmap.bindings !searchtable
854
855 let current_pure_db () = List.map snd (current_db ())
856
857 let error_no_such_hint_database x =
858 user_err (str "No such Hint database: " ++ str x ++ str ".")
859
860 (**************************************************************************)
861 (* Auxiliary functions to prepare AUTOHINT objects *)
862 (**************************************************************************)
863
864 (* adding and removing tactics in the search table *)
865
866 let with_uid c = { obj = c; uid = fresh_key () }
867
868 let secvars_of_idset s =
869 Id.Set.fold (fun id p ->
870 if is_section_variable (Global.env ()) id then
871 Id.Pred.add id p
872 else p) s Id.Pred.empty
873
874 let secvars_of_constr env sigma c =
875 secvars_of_idset (Termops.global_vars_set env sigma c)
876
877 let secvars_of_global env gr =
878 secvars_of_idset (vars_of_global env gr)
879
880 let make_exact_entry env sigma info ?name (c, cty, ctx) =
881 let secvars = secvars_of_constr env sigma c in
882 let cty = strip_outer_cast sigma cty in
883 match EConstr.kind sigma cty with
884 | Prod _ -> failwith "make_exact_entry"
885 | _ ->
886 let hd =
887 try head_bound sigma cty
888 with Bound -> failwith "make_exact_entry"
889 in
890 let pri = match info.hint_priority with None -> 0 | Some p -> p in
891 let pat = match info.hint_pattern with
892 | Some pat -> ConstrPattern (snd pat)
893 | None -> DefaultPattern
894 in
895 let h = { rhint_term = c; rhint_type = cty; rhint_uctx = ctx; rhint_arty = 0 } in
896 (Some hd,
897 { pri; pat = Some pat; name;
898 db = (); secvars;
899 code = with_uid (Give_exact h); })
900
901 let name_of_hint = function
902 | IsGlobRef gr -> Some gr
903 | IsConstr _ -> None
904
905 let make_apply_entry env sigma hnf info ?name (c, cty, ctx) =
906 let cty = if hnf then hnf_constr0 env sigma cty else cty in
907 match EConstr.kind sigma cty with
908 | Prod _ ->
909 let cty = if hnf then Reductionops.nf_betaiota env sigma cty else cty in
910 let sigma' = merge_context_set_opt sigma ctx in
911 let ce = Clenv.mk_clenv_from env sigma' (c,cty) in
912 let c' = Clenv.clenv_type (* ~reduce:false *) ce in
913 let hd =
914 try head_bound (Clenv.clenv_evd ce) c'
915 with Bound -> failwith "make_apply_entry" in
916 let miss, hyps = Clenv.clenv_missing ce in
917 let nmiss = List.length miss in
918 let secvars = secvars_of_constr env sigma c in
919 let pri = match info.hint_priority with None -> hyps + nmiss | Some p -> p in
920 let pat = match info.hint_pattern with
921 | Some p -> ConstrPattern (snd p)
922 | None -> DefaultPattern
923 in
924 let h = { rhint_term = c; rhint_type = cty; rhint_uctx = ctx; rhint_arty = hyps; } in
925 if Int.equal nmiss 0 then
926 (Some hd,
927 { pri; pat = Some pat; name;
928 db = ();
929 secvars;
930 code = with_uid (Res_pf h); })
931 else
932 (Some hd,
933 { pri; pat = Some pat; name;
934 db = (); secvars;
935 code = with_uid (ERes_pf h); })
936 | _ -> failwith "make_apply_entry"
937
938 (* flags is (e,h,v) with e=true if eapply and h=true if hnf and v=true if verbose
939 c is a constr
940 cty is the type of constr *)
941
942 let fresh_global_or_constr env sigma cr = match cr with
943 | IsGlobRef gr ->
944 let (c, ctx) = UnivGen.fresh_global_instance env gr in
945 let ctx = if Environ.is_polymorphic env gr then Some ctx else None in
946 (EConstr.of_constr c, ctx)
947 | IsConstr (c, ctx) -> (c, ctx)
948
949 let make_resolves env sigma (eapply, hnf) info ~check cr =
950 let name = name_of_hint cr in
951 let c, ctx = fresh_global_or_constr env sigma cr in
952 let cty = Retyping.get_type_of env sigma c in
953 let try_apply f =
954 try
955 let (_, hint) as ans = f (c, cty, ctx) in
956 match hint.code.obj with
957 | ERes_pf _ -> if not eapply then None else Some ans
958 | _ -> Some ans
959 with Failure _ -> None
960 in
961 let ents = List.map_filter try_apply
962 [make_exact_entry env sigma info ?name;
963 make_apply_entry env sigma hnf info ?name]
964 in
965 if check && List.is_empty ents then
966 user_err
967 (pr_leconstr_env env sigma c ++ spc() ++
968 (if eapply then str"cannot be used as a hint."
969 else str "can be used as a hint only for eauto."));
970 ents
971
972 (* used to add an hypothesis to the local hint database *)
973 let make_resolve_hyp env sigma hname =
974 let decl = EConstr.lookup_named hname env in
975 let c = mkVar hname in
976 try
977 [make_apply_entry env sigma true empty_hint_info
978 ~name:(GlobRef.VarRef hname)
979 (c, NamedDecl.get_type decl, None)]
980 with
981 | Failure _ -> []
982 | e when noncritical e -> anomaly (Pp.str "make_resolve_hyp.")
983
984 (* REM : in most cases hintname = id *)
985
986 let make_unfold eref =
987 let g = global_of_evaluable_reference eref in
988 (Some g,
989 { pri = 4;
990 pat = None;
991 name = Some g;
992 db = ();
993 secvars = secvars_of_global (Global.env ()) g;
994 code = with_uid (Unfold_nth eref) })
995
996 let make_extern pri pat tacast =
997 let hdconstr = match pat with
998 | None -> None
999 | Some c ->
1000 try Some (head_pattern_bound c)
1001 with BoundPattern ->
1002 user_err (Pp.str "Head pattern or sub-pattern must be a global constant, a section variable, \
1003 an if, case, or let expression, an application, or a projection.")
1004 in
1005 (hdconstr,
1006 { pri = pri;
1007 pat = Option.map (fun p -> SyntacticPattern p) pat;
1008 name = None;
1009 db = ();
1010 secvars = Id.Pred.empty; (* Approximation *)
1011 code = with_uid (Extern (pat, tacast)) })
1012
1013 let make_mode ref m =
1014 let open Term in
1015 let ty, _ = Typeops.type_of_global_in_context (Global.env ()) ref in
1016 let ctx, t = decompose_prod_decls ty in
1017 let n = Context.Rel.nhyps ctx in
1018 let m' = Array.of_list m in
1019 if not (n == Array.length m') then
1020 user_err
1021 (pr_global ref ++ str" has " ++ int n ++
1022 str" arguments while the mode declares " ++ int (Array.length m') ++ str ".")
1023 else m'
1024
1025 let make_trivial env sigma r =
1026 let name = Some r in
1027 let c,ctx = fresh_global_or_constr env sigma (IsGlobRef r) in
1028 let sigma = merge_context_set_opt sigma ctx in
1029 let t = hnf_constr env sigma (Retyping.get_type_of env sigma c) in
1030 let hd = head_constr sigma t in
1031 let h = { rhint_term = c; rhint_type = t; rhint_uctx = ctx; rhint_arty = 0 } in
1032 (Some hd,
1033 { pri=1;
1034 pat = Some DefaultPattern;
1035 name = name;
1036 db = ();
1037 secvars = secvars_of_constr env sigma c;
1038 code= with_uid (Res_pf_THEN_trivial_fail h) })
1039
1040
1041
1042 (**************************************************************************)
1043 (* declaration of the AUTOHINT library object *)
1044 (**************************************************************************)
1045
1046 (* If the database does not exist, it is created *)
1047 (* TODO: should a warning be printed in this case ?? *)
1048
1049 let get_db dbname =
1050 try searchtable_map dbname
1051 with Not_found -> Hint_db.empty ~name:dbname TransparentState.empty false
1052
1053 let add_hint dbname hintlist =
1054 let db = get_db dbname in
1055 let env = Global.env () in
1056 let sigma = Evd.from_env env in
1057 let db' = Hint_db.add_list env sigma hintlist db in
1058 searchtable_add (dbname, db')
1059
1060 let add_transparency dbname target b =
1061 let open TransparentState in
1062 let db = get_db dbname in
1063 let st = Hint_db.transparent_state db in
1064 let st' =
1065 match target with
1066 | HintsVariables -> { st with tr_var = (if b then Id.Pred.full else Id.Pred.empty) }
1067 | HintsConstants -> { st with tr_cst = (if b then Cpred.full else Cpred.empty) }
1068 | HintsProjections -> { st with tr_prj = (if b then PRpred.full else PRpred.empty) }
1069 | HintsReferences grs ->
1070 List.fold_left (fun st gr ->
1071 match gr with
1072 | Evaluable.EvalConstRef c -> { st with tr_cst = (if b then Cpred.add else Cpred.remove) c st.tr_cst }
1073 | Evaluable.EvalVarRef v -> { st with tr_var = (if b then Id.Pred.add else Id.Pred.remove) v st.tr_var }
1074 | Evaluable.EvalProjectionRef p -> { st with tr_prj = (if b then PRpred.add else PRpred.remove) p st.tr_prj } )
1075 st grs
1076 in
1077 searchtable_add (dbname, Hint_db.set_transparent_state db st')
1078
1079 let remove_hint dbname grs =
1080 let env = Global.env () in
1081 let db = get_db dbname in
1082 let db' = Hint_db.remove_list env grs db in
1083 searchtable_add (dbname, db')
1084
1085 let add_cut dbname path =
1086 let env = Global.env () in
1087 let db = get_db dbname in
1088 let db' = Hint_db.add_cut env path db in
1089 searchtable_add (dbname, db')
1090
1091 let add_mode dbname l m =
1092 let db = get_db dbname in
1093 let db' = Hint_db.add_mode l m db in
1094 searchtable_add (dbname, db')
1095
1096 type db_obj = {
1097 db_local : bool;
1098 db_name : string;
1099 db_use_dn : bool;
1100 db_ts : TransparentState.t;
1101 }
1102
1103 let warn_mismatch_create_hintdb = CWarnings.create ~name:"mismatched-hint-db" ~category:CWarnings.CoreCategories.automation
1104 Pp.(fun {db_name;db_use_dn} ->
1105 str "Hint Db " ++ str db_name ++ str " already exists and " ++
1106 (if db_use_dn then str "is not" else str "is") ++ str " discriminated.")
1107
1108 let cache_db ({db_name=name; db_use_dn=b; db_ts=ts} as o) =
1109 match searchtable_map name with
1110 | exception Not_found -> searchtable_create (name, Hint_db.empty ~name ts b)
1111 | db ->
1112 (* Explicit DBs start with full TS, implicit DBs start with empty TS
1113 This should probably be controllable in Create Hint Db,
1114 otherwise we have to do eg "Create HintDb foo. Hint Constants Opaque : foo."
1115 and if someone else creates foo and puts some transparency hints they will be overwritten. *)
1116 if Hint_db.use_dn db <> b then warn_mismatch_create_hintdb o
1117
1118 let load_db _ x = cache_db x
1119
1120 let classify_db db = if db.db_local then Dispose else Substitute
1121
1122 let inDB : db_obj -> obj =
1123 declare_object {(default_object "AUTOHINT_DB") with
1124 cache_function = cache_db;
1125 load_function = load_db;
1126 subst_function = (fun (_,x) -> x);
1127 classify_function = classify_db; }
1128
1129 let create_hint_db l n ts b =
1130 let hint = {db_local=l; db_name=n; db_use_dn=b; db_ts=ts} in
1131 Lib.add_leaf (inDB hint)
1132
1133 type hint_action =
1134 | AddTransparency of {
1135 grefs : Evaluable.t hints_transparency_target;
1136 state : bool;
1137 }
1138 | AddHints of hint_entry list
1139 | RemoveHints of GlobRef.t list
1140 | AddCut of hints_path
1141 | AddMode of { gref : GlobRef.t; mode : hint_mode array }
1142
1143 type hint_locality = Libobject.locality = Local | Export | SuperGlobal
1144
1145 type hint_obj = {
1146 hint_local : hint_locality;
1147 hint_name : string;
1148 hint_action : hint_action;
1149 }
1150
1151 let is_trivial_action = function
1152 | AddTransparency { grefs } ->
1153 begin match grefs with
1154 | HintsVariables | HintsConstants | HintsProjections -> false
1155 | HintsReferences l -> List.is_empty l
1156 end
1157 | AddHints l -> List.is_empty l
1158 | RemoveHints l -> List.is_empty l
1159 | AddCut _ | AddMode _ -> false
1160
1161 let rec is_section_path = function
1162 | PathAtom PathAny -> false
1163 | PathAtom (PathHints grs) ->
1164 let check c = isVarRef c && Global.is_in_section c in
1165 List.exists check grs
1166 | PathStar p -> is_section_path p
1167 | PathSeq (p, q) | PathOr (p, q) -> is_section_path p || is_section_path q
1168 | PathEmpty | PathEpsilon -> false
1169
1170 let superglobal h = match h.hint_local with
1171 | SuperGlobal -> true
1172 | Local | Export -> false
1173
1174 let load_autohint _ h =
1175 let name = h.hint_name in
1176 let superglobal = superglobal h in
1177 match h.hint_action with
1178 | AddTransparency { grefs; state } ->
1179 if superglobal then add_transparency name grefs state
1180 | AddHints hints ->
1181 if superglobal then add_hint name hints
1182 | RemoveHints hints ->
1183 if superglobal then remove_hint name hints
1184 | AddCut paths ->
1185 if superglobal then add_cut name paths
1186 | AddMode { gref; mode } ->
1187 if superglobal then add_mode name gref mode
1188
1189 let open_autohint h =
1190 let superglobal = superglobal h in
1191 match h.hint_action with
1192 | AddHints hints ->
1193 if not superglobal then add_hint h.hint_name hints
1194 | AddCut paths ->
1195 if not superglobal then add_cut h.hint_name paths
1196 | AddTransparency { grefs; state } ->
1197 if not superglobal then add_transparency h.hint_name grefs state
1198 | RemoveHints hints ->
1199 if not superglobal then remove_hint h.hint_name hints
1200 | AddMode { gref; mode } ->
1201 if not superglobal then add_mode h.hint_name gref mode
1202
1203 let cache_autohint o =
1204 load_autohint 1 o; open_autohint o
1205
1206 let subst_autohint (subst, obj) =
1207 let subst_key gr =
1208 let (gr', t) = subst_global subst gr in
1209 match t with
1210 | None -> gr'
1211 | Some t ->
1212 (try head_bound Evd.empty (EConstr.of_constr t.UVars.univ_abstracted_value)
1213 with Bound -> gr')
1214 in
1215 let subst_mps subst c = EConstr.of_constr (subst_mps subst (EConstr.Unsafe.to_constr c)) in
1216 let subst_aux ({ rhint_term = c; rhint_type = t; rhint_uctx = ctx; rhint_arty = ar } as h) =
1217 let c' = subst_mps subst c in
1218 let t' = subst_mps subst t in
1219 if c==c' && t'==t then h else { rhint_term = c'; rhint_type = t'; rhint_uctx = ctx; rhint_arty = ar }
1220 in
1221 let subst_hint (k,data as hint) =
1222 let k' = Option.Smart.map subst_key k in
1223 let env = Global.env () in
1224 let sigma = Evd.from_env env in
1225 let subst_hint_pattern = function
1226 | DefaultPattern -> DefaultPattern
1227 | ConstrPattern p as p0 ->
1228 let p' = subst_pattern env sigma subst p in
1229 if p' == p then p0 else ConstrPattern p'
1230 | SyntacticPattern p as p0 ->
1231 let p' = subst_pattern env sigma subst p in
1232 if p' == p then p0 else SyntacticPattern p'
1233 in
1234 let pat' = Option.Smart.map subst_hint_pattern data.pat in
1235 let code' = match data.code.obj with
1236 | Res_pf h ->
1237 let h' = subst_aux h in
1238 if h == h' then data.code.obj else Res_pf h'
1239 | ERes_pf h ->
1240 let h' = subst_aux h in
1241 if h == h' then data.code.obj else ERes_pf h'
1242 | Give_exact h ->
1243 let h' = subst_aux h in
1244 if h == h' then data.code.obj else Give_exact h'
1245 | Res_pf_THEN_trivial_fail h ->
1246 let h' = subst_aux h in
1247 if h == h' then data.code.obj else Res_pf_THEN_trivial_fail h'
1248 | Unfold_nth ref ->
1249 let ref' = subst_evaluable_reference subst ref in
1250 if ref==ref' then data.code.obj else Unfold_nth ref'
1251 | Extern (pat, tac) ->
1252 let pat' = Option.Smart.map (subst_pattern env sigma subst) pat in
1253 let tac' = Gentactic.subst subst tac in
1254 if pat==pat' && tac==tac' then data.code.obj else Extern (pat', tac')
1255 in
1256 let name' = Option.Smart.map (subst_global_reference subst) data.name in
1257 let uid' = subst_kn subst data.code.uid in
1258 let data' =
1259 if data.code.uid == uid' && data.pat == pat' &&
1260 data.name == name' && data.code.obj == code' then data
1261 else { data with pat = pat'; name = name'; code = { obj = code'; uid = uid' } }
1262 in
1263 if k' == k && data' == data then hint else (k',data')
1264 in
1265 let action = match obj.hint_action with
1266 | AddTransparency { grefs = target; state = b } ->
1267 let target' =
1268 match target with
1269 | HintsVariables -> target
1270 | HintsConstants -> target
1271 | HintsProjections -> target
1272 | HintsReferences grs ->
1273 let grs' = List.Smart.map (subst_evaluable_reference subst) grs in
1274 if grs == grs' then target
1275 else HintsReferences grs'
1276 in
1277 if target' == target then obj.hint_action else AddTransparency { grefs = target'; state = b }
1278 | AddHints hints ->
1279 let hints' = List.Smart.map subst_hint hints in
1280 if hints' == hints then obj.hint_action else AddHints hints'
1281 | RemoveHints grs ->
1282 let grs' = List.Smart.map (subst_global_reference subst) grs in
1283 if grs == grs' then obj.hint_action else RemoveHints grs'
1284 | AddCut path ->
1285 let path' = subst_hints_path subst path in
1286 if path' == path then obj.hint_action else AddCut path'
1287 | AddMode { gref = l; mode = m } ->
1288 let l' = subst_global_reference subst l in
1289 if l' == l then obj.hint_action else AddMode { gref = l'; mode = m }
1290 in
1291 if action == obj.hint_action then obj else { obj with hint_action = action }
1292
1293 let is_hint_local = function Local -> true | Export | SuperGlobal -> false
1294
1295 let classify_autohint obj =
1296 if is_hint_local obj.hint_local || is_trivial_action obj.hint_action then Dispose
1297 else Substitute
1298
1299 let discharge_autohint obj =
1300 if is_hint_local obj.hint_local then None
1301 else
1302 let action = match obj.hint_action with
1303 | AddTransparency { grefs; state } ->
1304 let grefs = match grefs with
1305 | HintsVariables | HintsConstants | HintsProjections -> grefs
1306 | HintsReferences grs ->
1307 let filter e = match e with
1308 | Evaluable.EvalConstRef c -> Some e
1309 | Evaluable.EvalProjectionRef p ->
1310 let p = Global.discharge_proj_repr p in
1311 Some (Evaluable.EvalProjectionRef p)
1312 | Evaluable.EvalVarRef id ->
1313 if Global.is_in_section (GlobRef.VarRef id) then None else Some e
1314 in
1315 let grs = List.filter_map filter grs in
1316 HintsReferences grs
1317 in
1318 AddTransparency { grefs; state }
1319 | AddHints _ | RemoveHints _ ->
1320 (* not supported yet *)
1321 assert false
1322 | AddCut path ->
1323 if is_section_path path then AddHints [] (* dummy *) else obj.hint_action
1324 | AddMode { gref; mode } ->
1325 if Global.is_in_section gref then
1326 if isVarRef gref then AddHints [] (* dummy *)
1327 else
1328 let inst = Global.section_instance gref in
1329 (* Default mode for discharged parameters is output *)
1330 let mode = Array.append (Array.make (Array.length inst) ModeOutput) mode in
1331 AddMode { gref; mode }
1332 else obj.hint_action
1333 in
1334 if is_trivial_action action then None
1335 else Some { obj with hint_action = action }
1336
1337 let hint_cat = create_category "hints"
1338
1339 let inAutoHint : hint_obj -> obj =
1340 declare_object
1341 {(default_object "AUTOHINT") with
1342 cache_function = cache_autohint;
1343 load_function = load_autohint;
1344 open_function = simple_open ~cat:hint_cat open_autohint;
1345 subst_function = subst_autohint;
1346 classify_function = classify_autohint;
1347 discharge_function = discharge_autohint;
1348 }
1349
1350 let check_locality locality =
1351 let not_local what =
1352 CErrors.user_err
1353 Pp.(str "This command does not support the " ++
1354 str what ++ str " attribute in sections.")
1355 in
1356 if Lib.sections_are_opened () then
1357 match locality with
1358 | Local -> ()
1359 | SuperGlobal -> not_local "global"
1360 | Export -> not_local "export"
1361
1362 let make_hint ~locality name action =
1363 {
1364 hint_local = locality;
1365 hint_name = name;
1366 hint_action = action;
1367 }
1368
1369 let remove_hints ~locality dbnames grs =
1370 let () = check_locality locality in
1371 let dbnames = if List.is_empty dbnames then ["core"] else dbnames in
1372 List.iter
1373 (fun dbname ->
1374 let hint = make_hint ~locality dbname (RemoveHints grs) in
1375 Lib.add_leaf (inAutoHint hint))
1376 dbnames
1377
1378 (**************************************************************************)
1379 (* The "Hint" vernacular command *)
1380 (**************************************************************************)
1381
1382 let add_resolves env sigma clist ~locality dbnames =
1383 List.iter
1384 (fun dbname ->
1385 let r =
1386 List.flatten (List.map (fun (pri, hnf, gr) ->
1387 make_resolves env sigma (true, hnf) pri ~check:true (IsGlobRef gr)) clist)
1388 in
1389 let check (_, hint) = match hint.code.obj with
1390 | ERes_pf { rhint_term = c; rhint_type = cty; rhint_uctx = ctx } ->
1391 let sigma' = merge_context_set_opt sigma ctx in
1392 let ce = Clenv.mk_clenv_from env sigma' (c,cty) in
1393 let miss, _ = Clenv.clenv_missing ce in
1394 let nmiss = List.length miss in
1395 let variables = str (CString.plural nmiss "variable") in
1396 Feedback.msg_info (
1397 strbrk "The hint " ++
1398 pr_leconstr_env env sigma' c ++
1399 strbrk " will only be used by eauto, because applying " ++
1400 pr_leconstr_env env sigma' c ++
1401 strbrk " would leave " ++ variables ++ Pp.spc () ++
1402 Pp.prlist_with_sep Pp.pr_comma Name.print miss ++
1403 strbrk " as unresolved existential " ++ variables ++ str "."
1404 )
1405 | _ -> ()
1406 in
1407 let () = if not !Flags.quiet then List.iter check r in
1408 let hint = make_hint ~locality dbname (AddHints r) in
1409 Lib.add_leaf (inAutoHint hint))
1410 dbnames
1411
1412 let add_unfolds l ~locality dbnames =
1413 List.iter
1414 (fun dbname ->
1415 let hint = make_hint ~locality dbname (AddHints (List.map make_unfold l)) in
1416 Lib.add_leaf (inAutoHint hint))
1417 dbnames
1418
1419 let add_cuts l ~locality dbnames =
1420 List.iter
1421 (fun dbname ->
1422 let hint = make_hint ~locality dbname (AddCut l) in
1423 Lib.add_leaf (inAutoHint hint))
1424 dbnames
1425
1426 let add_mode l m ~locality dbnames =
1427 List.iter
1428 (fun dbname ->
1429 let m' = make_mode l m in
1430 let hint = make_hint ~locality dbname (AddMode { gref = l; mode = m' }) in
1431 Lib.add_leaf (inAutoHint hint))
1432 dbnames
1433
1434 let add_transparency l b ~locality dbnames =
1435 List.iter
1436 (fun dbname ->
1437 let hint = make_hint ~locality dbname (AddTransparency { grefs = l; state = b }) in
1438 Lib.add_leaf (inAutoHint hint))
1439 dbnames
1440
1441 let add_extern info tacast ~locality dbname =
1442 let pat = match info.hint_pattern with
1443 | None -> None
1444 | Some (_, pat) -> Some pat
1445 in
1446 let hint = make_hint ~locality dbname
1447 (AddHints [make_extern (Option.get info.hint_priority) pat tacast]) in
1448 Lib.add_leaf (inAutoHint hint)
1449
1450 let add_externs info tacast ~locality dbnames =
1451 List.iter (add_extern info tacast ~locality) dbnames
1452
1453 let add_trivials env sigma l ~locality dbnames =
1454 List.iter
1455 (fun dbname ->
1456 let l = List.map (fun c -> make_trivial env sigma c) l in
1457 let hint = make_hint ~locality dbname (AddHints l) in
1458 Lib.add_leaf (inAutoHint hint))
1459 dbnames
1460
1461 type hnf = bool
1462
1463 type nonrec hint_info = hint_info
1464
1465 type hints_entry =
1466 | HintsResolveEntry of (hint_info * hnf * GlobRef.t) list
1467 | HintsImmediateEntry of GlobRef.t list
1468 | HintsCutEntry of hints_path
1469 | HintsUnfoldEntry of Evaluable.t list
1470 | HintsTransparencyEntry of Evaluable.t hints_transparency_target * bool
1471 | HintsModeEntry of GlobRef.t * hint_mode list
1472 | HintsExternEntry of hint_info * Gentactic.glob_generic_tactic
1473
1474 let default_prepare_hint_ident = Id.of_string "H"
1475
1476 exception Found of constr * types
1477
1478 let prepare_hint env init (sigma,c) =
1479 let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in
1480 (* We re-abstract over uninstantiated evars and universes.
1481 It is actually a bit stupid to generalize over evars since the first
1482 thing make_resolves will do is to re-instantiate the products *)
1483 let c = Evarutil.nf_evar sigma c in
1484 let c = drop_extra_implicit_args sigma c in
1485 let vars = ref (collect_vars sigma c) in
1486 let subst = ref [] in
1487 let rec find_next_evar c = match EConstr.kind sigma c with
1488 | Evar (evk,args as ev) ->
1489 (* We skip the test whether args is the identity or not *)
1490 let t = Evarutil.nf_evar sigma (existential_type sigma ev) in
1491 let t = List.fold_right (fun (e,id) c -> replace_term sigma e id c) !subst t in
1492 if not (closed0 sigma c) then
1493 user_err Pp.(str "Hints with holes dependent on a bound variable not supported.");
1494 if occur_existential sigma t then
1495 (* Not clever enough to construct dependency graph of evars *)
1496 user_err Pp.(str "Not clever enough to deal with evars dependent in other evars.");
1497 raise (Found (c,t))
1498 | _ -> EConstr.iter sigma find_next_evar c in
1499 let rec iter c =
1500 try find_next_evar c; c
1501 with Found (evar,t) ->
1502 let id = next_ident_away_from default_prepare_hint_ident (fun id -> Id.Set.mem id !vars) in
1503 vars := Id.Set.add id !vars;
1504 subst := (evar,mkVar id)::!subst;
1505 mkNamedLambda sigma (make_annot id ERelevance.relevant) t (iter (replace_term sigma evar (mkVar id) c)) in
1506 let c' = iter c in
1507 let diff = UnivGen.diff_sort_context (Evd.sort_context_set sigma) (Evd.sort_context_set init) in
1508 (c', diff)
1509
1510 let warn_non_local_section_hint =
1511 CWarnings.create ~name:"non-local-section-hint" ~category:CWarnings.CoreCategories.automation
1512 (fun () -> strbrk "This hint is not local but depends on a section variable. It will disappear when the section is closed.")
1513
1514 let is_notlocal = function
1515 | Local -> false
1516 | Export | SuperGlobal -> true
1517
1518 let add_hints ~locality dbnames h =
1519 let () = match h with
1520 | HintsResolveEntry _ | HintsImmediateEntry _ | HintsUnfoldEntry _ | HintsExternEntry _ ->
1521 check_locality locality
1522 | HintsTransparencyEntry ((HintsVariables | HintsConstants | HintsProjections), _) -> ()
1523 | HintsTransparencyEntry (HintsReferences grs, _) ->
1524 let iter gr =
1525 let gr = global_of_evaluable_reference gr in
1526 if is_notlocal locality && isVarRef gr && Global.is_in_section gr then warn_non_local_section_hint ()
1527 in
1528 List.iter iter grs
1529 | HintsCutEntry p ->
1530 if is_notlocal locality && is_section_path p then warn_non_local_section_hint ()
1531 | HintsModeEntry (gr, _) ->
1532 if is_notlocal locality && isVarRef gr && Global.is_in_section gr then warn_non_local_section_hint ()
1533 in
1534 if String.List.mem "nocore" dbnames then
1535 user_err Pp.(str "The hint database \"nocore\" is meant to stay empty.");
1536 assert (not (List.is_empty dbnames));
1537 let env = Global.env() in
1538 let sigma = Evd.from_env env in
1539 match h with
1540 | HintsResolveEntry lhints -> add_resolves env sigma lhints ~locality dbnames
1541 | HintsImmediateEntry lhints -> add_trivials env sigma lhints ~locality dbnames
1542 | HintsCutEntry lhints -> add_cuts lhints ~locality dbnames
1543 | HintsModeEntry (l,m) -> add_mode l m ~locality dbnames
1544 | HintsUnfoldEntry lhints -> add_unfolds lhints ~locality dbnames
1545 | HintsTransparencyEntry (lhints, b) ->
1546 add_transparency lhints b ~locality dbnames
1547 | HintsExternEntry (info, tacexp) ->
1548 add_externs info tacexp ~locality dbnames
1549
1550 let warn_non_reference_hint_using =
1551 CWarnings.create ~name:"non-reference-hint-using" ~category:CWarnings.CoreCategories.deprecated
1552 Pp.(fun (env, sigma, c) -> str "Use of the non-reference term " ++ pr_leconstr_env env sigma c ++ str " in \"using\" clauses is deprecated")
1553
1554 let expand_constructor_hints env sigma lems =
1555 List.map_append (fun lem ->
1556 let evd, lem = lem env sigma in
1557 let lem0 = drop_extra_implicit_args evd lem in
1558 match EConstr.kind evd lem0 with
1559 | Ind (ind,u) ->
1560 List.init (nconstructors env ind)
1561 (fun i -> IsGlobRef (GlobRef.ConstructRef ((ind,i+1))))
1562 | Const (cst, _) -> [IsGlobRef (GlobRef.ConstRef cst)]
1563 | Var id -> [IsGlobRef (GlobRef.VarRef id)]
1564 | Construct (cstr, _) -> [IsGlobRef (GlobRef.ConstructRef cstr)]
1565 | _ ->
1566 let () = warn_non_reference_hint_using (env, evd, lem) in
1567 let (c, ctx) = prepare_hint env sigma (evd,lem) in
1568 let ctx = if UnivGen.is_empty_sort_context ctx then None else Some ctx in
1569 [IsConstr (c, ctx)]) lems
1570 (* builds a hint database from a constr signature *)
1571 (* typically used with (lid, ltyp) = pf_hyps_types <some goal> *)
1572
1573 let constructor_hints env sigma eapply lems =
1574 let lems = expand_constructor_hints env sigma lems in
1575 List.map_append (fun lem ->
1576 make_resolves env sigma (eapply, true) empty_hint_info ~check:true lem) lems
1577
1578 let make_local_hint_db env sigma ts eapply lems =
1579 let sign = EConstr.named_context env in
1580 let ts = match ts with
1581 | None -> Hint_db.transparent_state (searchtable_map "core")
1582 | Some ts -> ts
1583 in
1584 let hintlist = List.map_append (fun decl -> make_resolve_hyp env sigma (Named.Declaration.get_id decl)) sign in
1585 Hint_db.empty ts false
1586 |> Hint_db.add_list env sigma hintlist
1587 |> Hint_db.add_list env sigma (constructor_hints env sigma eapply lems)
1588
1589 let make_local_hint_db env sigma ?ts eapply lems =
1590 make_local_hint_db env sigma ts eapply lems
1591
1592 let make_db_list dbnames =
1593 let fold (core, nocore) db =
1594 if String.equal db "core" then (true, nocore)
1595 else if String.equal db "nocore" then (core, true)
1596 else (core, nocore)
1597 in
1598 let has_core, has_nocore = List.fold_left fold (false, false) dbnames in
1599 let dbnames = match has_core, has_nocore with
1600 | true, true -> user_err Pp.(str "The core and nocore databases are mutually exclusive")
1601 | true, false -> dbnames
1602 | false, true -> List.remove String.equal "nocore" dbnames
1603 | false, false -> "core" :: dbnames
1604 in
1605 let lookup db =
1606 try searchtable_map db with Not_found -> error_no_such_hint_database db
1607 in
1608 List.map lookup dbnames
1609
1610 let push_resolves env sigma hint db =
1611 let entries = make_resolves env sigma (true, false) empty_hint_info ~check:false (IsGlobRef hint) in
1612 Hint_db.add_list env sigma entries db
1613
1614 let push_resolve_hyp env sigma decl db =
1615 let entries = make_resolve_hyp env sigma decl in
1616 Hint_db.add_list env sigma entries db
1617
1618 (**************************************************************************)
1619 (* Functions for printing the hints *)
1620 (**************************************************************************)
1621
1622 let pr_hint_elt env sigma h = pr_econstr_env env sigma h.hint_term
1623
1624 let pr_hint env sigma h = match h.obj with
1625 | Res_pf c -> (str"simple apply " ++ pr_hint_elt env sigma c)
1626 | ERes_pf c -> (str"simple eapply " ++ pr_hint_elt env sigma c)
1627 | Give_exact c -> (str"exact " ++ pr_hint_elt env sigma c)
1628 | Res_pf_THEN_trivial_fail c ->
1629 (str"simple apply " ++ pr_hint_elt env sigma c ++ str" ; trivial")
1630 | Unfold_nth c ->
1631 str"unfold " ++ pr_evaluable_reference c
1632 | Extern (_, tac) ->
1633 str "(*external*) " ++ Gentactic.print_glob env sigma ~level:(LevelLe 0) tac
1634
1635 let pr_default_pattern env sigma = function
1636 | Give_exact h ->
1637 pr_leconstr_env env sigma h.hint_type
1638 | Res_pf h | ERes_pf h | Res_pf_THEN_trivial_fail h ->
1639 let sigma, f = Clenv.replace_clenv_metas env sigma h.hint_clnv in
1640 pr_leconstr_env env sigma (f (Clenv.clenv_type h.hint_clnv))
1641 | Unfold_nth _ | Extern _ ->
1642 (* These hints cannot contain DefaultPattern *)
1643 assert false
1644
1645 let pr_id_hint env sigma (id, v) =
1646 let pr_pat p = match p.pat with
1647 | None -> mt ()
1648 | Some (ConstrPattern p | SyntacticPattern p) -> str", pattern " ++ pr_lconstr_pattern_env env sigma p
1649 | Some DefaultPattern -> str", pattern " ++ (pr_default_pattern env sigma v.code.obj)
1650 in
1651 (pr_hint env sigma v.code ++ str" (cost " ++ int v.pri ++ pr_pat v
1652 ++ str", id " ++ int id ++ str ")")
1653
1654 let pr_hint_list env sigma hintlist =
1655 (str " " ++ hov 0 (prlist_with_sep fnl (pr_id_hint env sigma) hintlist) ++ fnl ())
1656
1657 let pr_hints_db env sigma (name,db,hintlist) =
1658 (str "In the database " ++ str name ++ str ":" ++
1659 if List.is_empty hintlist then (str " nothing" ++ fnl ())
1660 else (fnl () ++ pr_hint_list env sigma hintlist))
1661
1662 (* Print all hints associated to head c in any database *)
1663 let pr_hint_list_for_head env sigma c =
1664 let dbs = current_db () in
1665 let validate (name, db) =
1666 let hints = List.map (fun v -> 0, v) (Hint_db.map_all ~secvars:Id.Pred.full c db) in
1667 (name, db, hints)
1668 in
1669 let valid_dbs = List.map validate dbs in
1670 if List.is_empty valid_dbs then
1671 (str "No hint declared for :" ++ pr_global c)
1672 else
1673 hov 0
1674 (str"For " ++ pr_global c ++ str" -> " ++ fnl () ++
1675 hov 0 (prlist (pr_hints_db env sigma) valid_dbs))
1676
1677 let pr_hint_ref ref = pr_hint_list_for_head ref
1678
1679 (* Print all hints associated to head id in any database *)
1680
1681 let pr_hint_term env sigma cl =
1682 try
1683 let dbs = current_db () in
1684 let valid_dbs =
1685 let fn = try
1686 let hdc = decompose_app_bound sigma cl in
1687 if occur_existential sigma cl then
1688 (fun db -> match Hint_db.map_eauto env sigma ~secvars:Id.Pred.full hdc cl db with
1689 | ModeMatch (_, l) -> l
1690 | ModeMismatch -> [])
1691 else Hint_db.map_auto env sigma ~secvars:Id.Pred.full hdc cl
1692 with Bound -> Hint_db.map_none ~secvars:Id.Pred.full
1693 in
1694 let fn db = List.map (fun x -> 0, x) (fn db) in
1695 List.map (fun (name, db) -> (name, db, fn db)) dbs
1696 in
1697 if List.is_empty valid_dbs then
1698 (str "No hint applicable for current goal")
1699 else
1700 (str "Applicable Hints :" ++ fnl () ++
1701 hov 0 (prlist (pr_hints_db env sigma) valid_dbs))
1702 with Match_failure _ | Failure _ ->
1703 (str "No hint applicable for current goal")
1704
1705 (* print all hints that apply to the concl of the current goal *)
1706 let pr_applicable_hint pf =
1707 let env = Global.env () in
1708 let Proof.{goals;sigma} = Proof.data pf in
1709 match goals with
1710 | [] -> CErrors.user_err Pp.(str "No focused goal.")
1711 | g::_ ->
1712 pr_hint_term env sigma (Evd.evar_concl (Evd.find_undefined sigma g))
1713
1714 let parse_mode s =
1715 match s with
1716 | "+" -> ModeInput
1717 | "-" -> ModeOutput
1718 | "!" -> ModeNoHeadEvar
1719 | _ -> CErrors.user_err Pp.(str"Unrecognized hint mode " ++ str s)
1720
1721 let parse_modes s =
1722 let modes = String.split_on_char ' ' s in
1723 List.map parse_mode modes
1724
1725 let string_of_mode = function
1726 | ModeInput -> "+"
1727 | ModeOutput -> "-"
1728 | ModeNoHeadEvar -> "!"
1729
1730 let pp_hint_mode m = str (string_of_mode m)
1731
1732 (* displays the whole hint database db *)
1733 let pr_hint_db_env env sigma db =
1734 let pr_mode = prvect_with_sep spc pp_hint_mode in
1735 let pr_modes l =
1736 if List.is_empty l then mt ()
1737 else str" (modes " ++ prlist_with_sep pr_comma pr_mode l ++ str")"
1738 in
1739 let content =
1740 let pr_one (head, modes, hintlist) =
1741 let goal_descr = match head with
1742 | None -> str "For any goal"
1743 | Some head -> str "For " ++ pr_global head ++ pr_modes modes
1744 in
1745 (* sort because db.hintdb_nopat isn't kept in priority sorted order;
1746 "auto" sorts on priority before using the hintdb *)
1747 let sorted = List.stable_sort (fun a b -> Int.compare a.pri b.pri) hintlist in
1748 (* always prints "id 0" in Print HintDb *)
1749 let hints = pr_hint_list env sigma (List.map (fun x -> (0, x)) sorted) in
1750 hov 0 (goal_descr ++ str " -> " ++ hints)
1751 in
1752 let hints =
1753 let name x = Nametab.shortest_qualid_of_global Id.Set.empty x in
1754 let order (h1, _, _) (h2, _, _) =
1755 Option.compare (fun a b ->
1756 let a = name a and b = name b in
1757 let rv = Id.compare (qualid_basename a) (qualid_basename b) in
1758 if rv <> 0 then rv else
1759 String.compare (string_of_qualid a) (string_of_qualid b))
1760 h1 h2
1761 in
1762 let hints = Hint_db.fold (fun h m hl l -> (h, m, hl) :: l) db [] in
1763 List.stable_sort order hints in
1764 Pp.prlist pr_one hints
1765 in
1766 let { TransparentState.tr_var = ids; tr_cst = csts; tr_prj = ps } =
1767 Hint_db.transparent_state db
1768 in
1769 hov 0
1770 ((if Hint_db.use_dn db then str"Discriminated database"
1771 else str"Non-discriminated database")) ++ fnl () ++
1772 hov 2 (str"Unfoldable variable definitions: " ++ pr_idpred ids) ++ fnl () ++
1773 hov 2 (str"Unfoldable constant definitions: " ++ pr_cpred csts) ++ fnl () ++
1774 hov 2 (str"Unfoldable projection definitions: " ++ pr_prpred ps) ++ fnl () ++
1775 hov 2 (str"Cut: " ++ pp_hints_path (Hint_db.cut db)) ++ fnl () ++
1776 content
1777
1778 let pr_hint_db_by_name env sigma dbname =
1779 try
1780 let db = searchtable_map dbname in pr_hint_db_env env sigma db
1781 with Not_found ->
1782 error_no_such_hint_database dbname
1783
1784 (* displays all the hints of all databases *)
1785 let pr_searchtable env sigma =
1786 let fold name db accu =
1787 accu ++ str "In the database " ++ str name ++ str ":" ++ fnl () ++
1788 pr_hint_db_env env sigma db ++ fnl ()
1789 in
1790 Hintdbmap.fold fold !searchtable (mt ())
1791
1792 module FullHint =
1793 struct
1794 type t = full_hint
1795 let priority (h : t) = h.pri
1796 let database (h : t) = h.db
1797 let pattern (h : t) = match h.pat with
1798 | None -> None
1799 | Some (ConstrPattern p | SyntacticPattern p) -> Some p
1800 | Some DefaultPattern -> None
1801 let run (h : t) k = k h.code.obj
1802 let print env sigma (h : t) = pr_hint env sigma h.code
1803 let name (h : t) = h.name
1804
1805 let subgoals (h : t) = match h.code.obj with
1806 | Res_pf h | ERes_pf h | Give_exact h | Res_pf_THEN_trivial_fail h -> Some h.hint_arty
1807 | Unfold_nth _ -> Some 1
1808 | Extern _ -> None
1809
1810 let repr (h : t) = h.code.obj
1811 end
1812
1813 let connect_hint_clenv h gl =
1814 let { hint_uctx = ctx; hint_clnv = clenv } = h in
1815 (* [clenv] has been generated by a hint-making function, so the only relevant
1816 data in its evarmap is the set of metas. The function
1817 below just replaces the metas of sigma by those coming from the clenv. *)
1818 let env = Proofview.Goal.env gl in
1819 let sigma = Proofview.Goal.sigma gl in
1820 Clenv.clenv_refresh env sigma ctx clenv
1821
1822 let fresh_hint env sigma h =
1823 let { hint_term = c; hint_uctx = ctx } = h in
1824 match h.hint_uctx with
1825 | None -> sigma, c
1826 | Some ctx ->
1827 (* Refresh the instance of the hint *)
1828 let (subst, ctx) = UnivGen.fresh_sort_context_instance ctx in
1829 let c = Vars.subst_univs_level_constr subst c in
1830 let sigma = Evd.merge_sort_context_set Evd.univ_flexible ~src:UState.Internal sigma ctx in
1831 sigma, c
1832
1833 let hint_res_pf ?with_evars ?with_classes ?flags h =
1834 Proofview.Goal.enter begin fun gl ->
1835 let clenv = connect_hint_clenv h gl in
1836 Clenv.res_pf ?with_evars ?with_classes ?flags clenv
1837 end