Debian Codegraph @

tactics/eauto.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 Constr
16 open Termops
17 open EConstr
18 open Tactics
19 open Auto
20 open Genredexpr
21 open Locus
22 open Locusops
23 open Hints
24 open Proofview.Notations
25
26 module NamedDecl = Context.Named.Declaration
27
28 let eauto_unif_flags = auto_flags_of_state TransparentState.full
29
30 let e_give_exact ?(flags=eauto_unif_flags) c =
31 Proofview.Goal.enter begin fun gl ->
32 let env = Proofview.Goal.env gl in
33 let sigma = Proofview.Goal.sigma gl in
34 let concl = Proofview.Goal.concl gl in
35 let sigma, t1 = Typing.type_of env sigma c in
36 if occur_existential sigma t1 || occur_existential sigma concl then
37 Tacticals.tclTHENLIST
38 [Proofview.Unsafe.tclEVARS sigma;
39 Clenv.unify ~flags ~cv_pb:CUMUL t1;
40 exact_no_check c]
41 else exact_check c
42 end
43
44 let e_assumption =
45 Proofview.Goal.enter begin fun gl ->
46 let hyps = Proofview.Goal.hyps gl in
47 let sigma = Proofview.Goal.sigma gl in
48 let concl = Proofview.Goal.concl gl in
49 if List.is_empty hyps then
50 Tacticals.tclZEROMSG (str "No applicable tactic.")
51 else
52 let not_ground = occur_existential sigma concl in
53 let map decl =
54 let id = NamedDecl.get_id decl in
55 let t = NamedDecl.get_type decl in
56 if not_ground || occur_existential sigma t then
57 Clenv.unify ~cv_pb:CUMUL ~flags:eauto_unif_flags t <*> exact_no_check (mkVar id)
58 else
59 exact_check (mkVar id)
60 in
61 Tacticals.tclFIRST (List.map map hyps)
62 end
63
64 (************************************************************************)
65 (* PROLOG tactic *)
66 (************************************************************************)
67
68 open Auto
69
70 (***************************************************************************)
71 (* A tactic similar to Auto, but using EApply, Assumption and e_give_exact *)
72 (***************************************************************************)
73
74 let unify_e_resolve flags h =
75 Hints.hint_res_pf ~with_evars:true ~with_classes:true ~flags h
76
77 type cost = {
78 cost_priority : int;
79 cost_subgoals : int;
80 }
81
82 let hintmap_of env sigma secvars concl =
83 (* Warning: for computation sharing, we need to return a closure *)
84 let hdc = try Some (decompose_app_bound sigma concl) with Bound -> None in
85 match hdc with
86 | None -> fun db -> Hint_db.map_none ~secvars db
87 | Some hdc ->
88 if occur_existential sigma concl then
89 (fun db ->
90 match Hint_db.map_eauto env sigma ~secvars hdc concl db with
91 | ModeMatch (_, l) -> l
92 | ModeMismatch -> [])
93 else (fun db -> Hint_db.map_auto env sigma ~secvars hdc concl db)
94 (* FIXME: should be (Hint_db.map_eauto hdc concl db) *)
95
96 let e_exact _flags h =
97 (* XXX: we never use the argument flags *)
98 let flags = eauto_unif_flags in
99 Hints.hint_res_pf ~with_evars:false ~with_classes:false ~flags h
100
101 let rec e_trivial_fail_db db_list local_db =
102 let next = Proofview.Goal.enter begin fun gl ->
103 let env = Proofview.Goal.env gl in
104 let sigma = Proofview.Goal.sigma gl in
105 let d = match EConstr.named_context env with
106 | [] -> assert false
107 | d :: _ -> NamedDecl.get_id d
108 in
109 let local_db = push_resolve_hyp env sigma d local_db in
110 e_trivial_fail_db db_list local_db
111 end in
112 Proofview.Goal.enter begin fun gl ->
113 let env = Proofview.Goal.env gl in
114 let sigma = Proofview.Goal.sigma gl in
115 let concl = Proofview.Goal.concl gl in
116 let secvars = compute_secvars gl in
117 let tacl =
118 e_assumption ::
119 (Tacticals.tclTHEN Tactics.intro next) :: (e_trivial_resolve env sigma db_list local_db secvars concl)
120 in
121 Tacticals.tclSOLVE tacl
122 end
123
124 and e_my_find_search env sigma db_list local_db secvars concl =
125 let hint_of_db = hintmap_of env sigma secvars concl in
126 let hintl =
127 List.map_append (fun db ->
128 let flags = auto_flags_of_state (Hint_db.transparent_state db) in
129 List.map (fun x -> flags, x) (hint_of_db db)) (local_db::db_list)
130 in
131 let tac_of_hint =
132 fun (st, h) ->
133 let priority = match FullHint.repr h with
134 | Unfold_nth _ -> 1
135 | _ -> FullHint.priority h
136 in
137 let tac = function
138 | Res_pf h -> unify_resolve st h
139 | ERes_pf h -> unify_e_resolve st h
140 | Give_exact h -> e_exact st h
141 | Res_pf_THEN_trivial_fail h ->
142 Tacticals.tclTHEN (unify_e_resolve st h)
143 (e_trivial_fail_db db_list local_db)
144 | Unfold_nth c -> reduce (Unfold [AllOccurrences,c]) onConcl
145 | Extern (pat, tacast) -> conclPattern concl pat tacast
146 in
147 (* We cannot determine statically the cost of subgoals of an Extern hint,
148 so approximate it by the hint's priority. *)
149 let subgoals = match FullHint.subgoals h with
150 | Some subgoals -> subgoals
151 | None -> priority
152 in
153 let b = { cost_priority = priority; cost_subgoals = subgoals } in
154 let tac = FullHint.run h tac in
155 (tac, b, lazy (FullHint.print env sigma h))
156 in
157 List.map tac_of_hint hintl
158
159 and e_trivial_resolve env sigma db_list local_db secvars gl =
160 let filter (tac, pr, _) = if Int.equal pr.cost_priority 0 then Some tac else None in
161 try List.map_filter filter (e_my_find_search env sigma db_list local_db secvars gl)
162 with Not_found -> []
163
164 let e_possible_resolve env sigma db_list local_db secvars gl =
165 try e_my_find_search env sigma db_list local_db secvars gl
166 with Not_found -> []
167
168 type delayed_db = Environ.env -> Evd.evar_map -> hint_db
169
170 type search_state = {
171 depth : int; (*r depth of search before failing *)
172 tacres : (Proofview_monad.goal_with_state * delayed_db) list;
173 last_tactic : Pp.t Lazy.t;
174 prev : prev_search_state;
175 }
176
177 and prev_search_state = (* for info eauto *)
178 | Unknown
179 | Init
180 | State of search_state
181
182 (*s Tactics handling a list of goals. *)
183
184 (* first_goal : goal list sigma -> goal sigma *)
185
186 module Search = struct
187
188 let is_solved p = Int.equal p.cost_subgoals 0
189
190 let solve_order p1 p2 = match is_solved p1, is_solved p2 with
191 | true, true | false, false -> 0
192 | false, true -> 1
193 | true, false -> -1 (* solved comes first *)
194
195 (* Ordering of states is lexicographic:
196 1. tactics known to solve the goal
197 2. priority
198 3. number of generated goals. *)
199 let compare (_, p1, _) (_, p2, _) =
200 let d = solve_order p1 p2 in
201 let d' = Int.compare p1.cost_priority p2.cost_priority in
202 if not (Int.equal d 0) then d
203 else if not (Int.equal d' 0) then d'
204 else Int.compare p1.cost_subgoals p2.cost_subgoals
205
206 let branching db dblist local_lemmas =
207 Proofview.Goal.enter_one begin fun gl ->
208 let env = Proofview.Goal.env gl in
209 let sigma = Proofview.Goal.sigma gl in
210 let concl = Proofview.Goal.concl gl in
211 let hyps = EConstr.named_context env in
212 let db = db env sigma in
213 let secvars = secvars_of_hyps hyps in
214 let assumption_tacs =
215 let mkdb env sigma = assert false in (* no goal can be generated *)
216 let map_assum id = (false, mkdb, e_give_exact (mkVar id), lazy (str "exact" ++ spc () ++ Id.print id)) in
217 List.map map_assum (ids_of_named_context hyps)
218 in
219 let intro_tac =
220 let mkdb env sigma =
221 push_resolve_hyp env sigma (NamedDecl.get_id (List.hd (EConstr.named_context env))) db
222 in
223 (false, mkdb, Tactics.intro, lazy (str "intro"))
224 in
225 let rec_tacs =
226 let mkdb env sigma =
227 let hyps' = EConstr.named_context env in
228 if hyps' == hyps then db
229 else make_local_hint_db env sigma ~ts:TransparentState.full true local_lemmas
230 in
231 let tacs = e_possible_resolve env sigma dblist db secvars concl in
232 let tacs = List.sort compare tacs in
233 let tacs = List.map (fun (tac, _, pp) -> (true, mkdb, tac, pp)) tacs in
234 Proofview.tclUNIT tacs
235 in
236 rec_tacs >>= fun rec_tacs ->
237 Proofview.tclUNIT (assumption_tacs @ intro_tac :: rec_tacs)
238 end
239
240 let msg_with_position (p : int list) s = match p with
241 | [] -> ()
242 | _ :: _ ->
243 let pp = hov 0 (str " depth=" ++ int s.depth ++ spc () ++ (Lazy.force s.last_tactic)) in
244 let rec pp_rec = function
245 | [] -> mt ()
246 | [i] -> int i
247 | i :: l -> pp_rec l ++ str "." ++ int i
248 in
249 Feedback.msg_debug (h (pp_rec p) ++ pp)
250
251 let push i p = match p with [] -> [] | _ :: _ -> i :: p
252
253 exception SearchFailure
254
255 let is_failure (e, _) = match e with SearchFailure -> true | _ -> false
256
257 let search ?(debug=false) dblist local_lemmas s =
258 let rec explore p s =
259 let () = msg_with_position p s in
260 if Int.equal s.depth 0 then Proofview.tclZERO SearchFailure
261 else match s.tacres with
262 | [] -> Proofview.tclUNIT s
263 | (gl, db) :: rest ->
264 Proofview.tclEVARMAP >>= fun sigma ->
265 match Proofview.Unsafe.undefined sigma [gl] with
266 | [] -> explore p { s with tacres = rest }
267 | gl :: _ ->
268 Proofview.Unsafe.tclSETGOALS [gl] <*>
269 let ps = if s.prev == Unknown then Unknown else State s in
270 branching db dblist local_lemmas >>= fun tacs ->
271 let map (isrec, mkdb, tac, pp) =
272 Proofview.tclONCE tac >>= fun () ->
273 Proofview.Unsafe.tclGETGOALS >>= fun lgls ->
274 Proofview.tclEVARMAP >>= fun sigma ->
275 let map gl = gl, mkdb in
276 let depth =
277 if isrec then if List.is_empty lgls then s.depth else pred s.depth
278 else s.depth
279 in
280 let lgls = List.map map lgls in
281 Proofview.tclUNIT { depth; tacres = lgls @ rest; last_tactic = pp; prev = ps; }
282 in
283 let tacs = List.map map tacs in
284 explore_many 1 p tacs
285
286 and explore_many i p = function
287 | [] -> Proofview.tclZERO SearchFailure
288 | tac :: l ->
289 Proofview.tclORELSE (tac >>= fun s -> explore (push i p) s)
290 (fun e -> explore_many (if is_failure e then succ i else i) p l)
291 (* discriminate between search failures and [tac] raising an error *)
292 in
293 let pos = if debug then [1] else [] in
294 explore pos s
295
296 end
297
298 (** Utilities for debug eauto / info eauto *)
299
300 let global_debug_eauto = ref false
301 let global_info_eauto = ref false
302
303 let () =
304 Goptions.(declare_bool_option
305 { optstage = Summary.Stage.Interp;
306 optdepr = None;
307 optkey = ["Debug";"Eauto"];
308 optread = (fun () -> !global_debug_eauto);
309 optwrite = (:=) global_debug_eauto })
310
311 let () =
312 Goptions.(declare_bool_option
313 { optstage = Summary.Stage.Interp;
314 optdepr = None;
315 optkey = ["Info";"Eauto"];
316 optread = (fun () -> !global_info_eauto);
317 optwrite = (:=) global_info_eauto })
318
319 let mk_eauto_dbg d =
320 if d == Debug || !global_debug_eauto then Debug
321 else if d == Info || !global_info_eauto then Info
322 else Off
323
324 let pr_info_nop = function
325 | Info -> Feedback.msg_notice (str "idtac.")
326 | _ -> ()
327
328 let pr_dbg_header = function
329 | Off -> ()
330 | Debug -> Feedback.msg_notice (str "(* debug eauto: *)")
331 | Info -> Feedback.msg_notice (str "(* info eauto: *)")
332
333 let pr_info dbg s =
334 if dbg != Info then ()
335 else
336 let rec loop s =
337 match s.prev with
338 | Unknown | Init -> s.depth
339 | State sp ->
340 let mindepth = loop sp in
341 let indent = String.make (mindepth - sp.depth) ' ' in
342 Feedback.msg_notice (str indent ++ Lazy.force s.last_tactic ++ str ".");
343 mindepth
344 in
345 ignore (loop s)
346
347 (** Eauto main code *)
348
349 let make_initial_state evk dbg n localdb =
350 { depth = n;
351 tacres = [evk, localdb];
352 last_tactic = lazy (mt());
353 prev = if dbg == Info then Init else Unknown;
354 }
355
356 let e_search_auto ?(debug = Off) ?depth lems db_list =
357 Proofview.Goal.enter begin fun gl ->
358 let p = Option.default default_search_depth depth in
359 let local_db env sigma = make_local_hint_db env sigma ~ts:TransparentState.full true lems in
360 let d = mk_eauto_dbg debug in
361 let debug = match d with Debug -> true | Info | Off -> false in
362 let tac s = Search.search ~debug db_list lems s in
363 let () = pr_dbg_header d in
364 Proofview.tclORELSE
365 begin
366 let evk = Proofview.goal_with_state (Proofview.Goal.goal gl) (Proofview.Goal.state gl) in
367 tac (make_initial_state evk d p local_db) >>= fun s ->
368 let () = pr_info d s in
369 let () = assert (List.is_empty s.tacres) in
370 Proofview.Unsafe.tclSETGOALS []
371 end
372 begin function
373 | (Search.SearchFailure, _) ->
374 let () = pr_info_nop d in
375 Proofview.tclUNIT ()
376 | (e, info) -> Proofview.tclZERO ~info e
377 end
378 end
379
380 let eauto_with_bases ?debug ?depth lems db_list =
381 e_search_auto ?debug ?depth lems db_list
382
383 let gen_eauto ?debug ?depth lems dbs =
384 Proofview.wrap_exceptions @@ fun () ->
385 let dbs = match dbs with None -> current_pure_db () | Some dbs -> make_db_list dbs in
386 eauto_with_bases ?debug ?depth lems dbs
387
388 let autounfolds ids csts prjs gl cls =
389 let hyps = Tacmach.pf_ids_of_hyps gl in
390 let env = Proofview.Goal.env gl in
391 let sigma = Proofview.Goal.sigma gl in
392 let ids = List.filter (fun id -> List.mem id hyps && Tacred.is_evaluable env sigma (EvalVarRef id)) ids in
393 let csts = List.filter (fun cst -> Tacred.is_evaluable env sigma (EvalConstRef cst)) csts in
394 let prjs = List.filter (fun p -> Tacred.is_evaluable env sigma (EvalProjectionRef p)) prjs in
395 let flags =
396 let flags = RedFlags.red_add_transparent RedFlags.all TransparentState.empty in
397 let flags = List.fold_left (fun flags id -> RedFlags.(red_add flags (fVAR id))) flags ids in
398 let flags = List.fold_left (fun flags cst -> RedFlags.(red_add flags (fCONST cst))) flags csts in
399 List.fold_left (fun flags p -> RedFlags.(red_add flags (fPROJ p))) flags prjs
400 in reduct_option ~check:false (Reductionops.clos_norm_flags flags, DEFAULTcast) cls
401
402 let cons a l = a :: l
403
404 exception UnknownDatabase of string
405
406 let autounfold db cls =
407 if not (Locusops.clause_with_generic_occurrences cls) then
408 user_err (str "\"at\" clause not supported.");
409 match List.fold_left (fun (ids, csts, prjs) dbname ->
410 let db = try searchtable_map dbname
411 with Not_found -> raise (UnknownDatabase dbname)
412 in
413 let (db_ids, db_csts, db_prjs) = Hint_db.unfolds db in
414 (Id.Set.fold cons db_ids ids, Cset.fold cons db_csts csts, PRset.fold cons db_prjs prjs)) ([], [], []) db
415 with
416 | (ids, csts, prjs) -> Proofview.Goal.enter begin fun gl ->
417 let cls = concrete_clause_of (fun () -> Tacmach.pf_ids_of_hyps gl) cls in
418 let tac = autounfolds ids csts prjs gl in
419 Tacticals.tclMAP (function
420 | OnHyp (id, _, where) -> tac (Some (id, where))
421 | OnConcl _ -> tac None) cls
422 end
423 | exception UnknownDatabase dbname -> Tacticals.tclZEROMSG (str "Unknown database " ++ str dbname)
424
425 let autounfold_tac db cls =
426 Proofview.tclUNIT () >>= fun () ->
427 let dbs = match db with
428 | None -> String.Set.elements (current_db_names ())
429 | Some [] -> ["core"]
430 | Some l -> l
431 in
432 autounfold dbs cls
433
434 let transparent_constant csts prjs c =
435 match Structures.PrimitiveProjections.find_opt c with
436 | None -> Cset.mem c csts
437 | Some p -> PRset.mem p prjs
438
439 let unfold_head env sigma (ids, csts, prjs) c =
440 (* TODO use prjs *)
441 let rec aux c =
442 match EConstr.kind sigma c with
443 | Var id when Id.Set.mem id ids ->
444 (match Environ.named_body id env with
445 | Some b -> true, EConstr.of_constr b
446 | None -> false, c)
447 | Const (cst, u) when transparent_constant csts prjs cst ->
448 let u = EInstance.kind sigma u in
449 true, EConstr.of_constr (Environ.constant_value_in env (cst, u))
450 | App (f, args) ->
451 (match aux f with
452 | true, f' -> true, Reductionops.whd_betaiota env sigma (mkApp (f', args))
453 | false, _ ->
454 let done_, args' =
455 Array.fold_left_i (fun i (done_, acc) arg ->
456 if done_ then done_, arg :: acc
457 else match aux arg with
458 | true, arg' -> true, arg' :: acc
459 | false, arg' -> false, arg :: acc)
460 (false, []) args
461 in
462 if done_ then true, mkApp (f, Array.of_list (List.rev args'))
463 else false, c)
464 | _ ->
465 let done_ = ref false in
466 let c' = EConstr.map sigma (fun c ->
467 if !done_ then c else
468 let x, c' = aux c in
469 done_ := x; c') c
470 in !done_, c'
471 in aux c
472
473 let autounfold_one db cl =
474 Proofview.Goal.enter begin fun gl ->
475 let env = Proofview.Goal.env gl in
476 let sigma = Proofview.Goal.sigma gl in
477 let concl = Proofview.Goal.concl gl in
478 let st =
479 List.fold_left (fun (i,c,p) dbname ->
480 let db = try searchtable_map dbname
481 with Not_found -> user_err (str "Unknown database " ++ str dbname ++ str ".")
482 in
483 let (ids, csts, prjs) = Hint_db.unfolds db in
484 (Id.Set.union ids i, Cset.union csts c, PRset.union prjs p)) (Id.Set.empty, Cset.empty, PRset.empty) db
485 in
486 let did, c' = unfold_head env sigma st
487 (match cl with Some (id, _) -> Tacmach.pf_get_hyp_typ id gl | None -> concl)
488 in
489 if did then
490 match cl with
491 | Some hyp -> change_in_hyp ~check:true None (make_change_arg c') hyp
492 | None -> convert_concl ~cast:false ~check:false c' DEFAULTcast
493 else
494 let info = Exninfo.reify () in
495 Tacticals.tclFAIL ~info (str "Nothing to unfold")
496 end