Debian Codegraph @

tactics/class_tactics.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 Names
14 open Constr
15 open Termops
16 open EConstr
17 open Tactics
18 open Typeclasses
19 open Evd
20 open Locus
21 open Proofview.Notations
22 open Hints
23
24 module NamedDecl = Context.Named.Declaration
25
26 (** Hint database named "typeclass_instances", created in prelude *)
27 let typeclasses_db = "typeclass_instances"
28
29 let check_typeclasses_db ?loc () =
30 try ignore (Hints.searchtable_map typeclasses_db)
31 with Not_found ->
32 CErrors.user_err (strbrk "The built-in typeclass hint database " ++
33 quote (str typeclasses_db) ++ strbrk " has not been registered.")
34 (** Options handling *)
35
36 let typeclasses_depth_opt_name = ["Typeclasses";"Depth"]
37 let { Goptions.get = get_typeclasses_depth } =
38 Goptions.declare_intopt_option_and_ref
39 ~key:typeclasses_depth_opt_name
40 ~value:None
41 ()
42
43 let set_typeclasses_depth =
44 Goptions.set_int_option_value typeclasses_depth_opt_name
45
46 (** When this flag is enabled, the resolution of type classes tries to avoid
47 useless introductions. This is no longer useful since we have eta, but is
48 here for compatibility purposes. Another compatibility issues is that the
49 cost (in terms of search depth) can differ. *)
50 let { Goptions.get = get_typeclasses_limit_intros } =
51 Goptions.declare_bool_option_and_ref
52 ~key:["Typeclasses";"Limit";"Intros"]
53 ~value:true
54 ()
55
56 let { Goptions.get = get_typeclasses_dependency_order } =
57 Goptions.declare_bool_option_and_ref
58 ~key:["Typeclasses";"Dependency";"Order"]
59 ~value:false
60 ()
61
62 let iterative_deepening_opt_name = ["Typeclasses";"Iterative";"Deepening"]
63 let { Goptions.get = get_typeclasses_iterative_deepening } =
64 Goptions.declare_bool_option_and_ref
65 ~key:iterative_deepening_opt_name
66 ~value:false
67 ()
68
69 module Debug : sig
70 val ppdebug : int -> (unit -> Pp.t) -> unit
71
72 val get_debug : unit -> int
73
74 val set_typeclasses_debug : bool -> unit
75 end = struct
76 let typeclasses_debug = ref 0
77
78 let set_typeclasses_debug d = (:=) typeclasses_debug (if d then 1 else 0)
79 let get_typeclasses_debug () = if !typeclasses_debug > 0 then true else false
80
81 let set_typeclasses_verbose = function
82 | None -> typeclasses_debug := 0
83 | Some n -> typeclasses_debug := n
84 let get_typeclasses_verbose () =
85 if !typeclasses_debug = 0 then None else Some !typeclasses_debug
86
87 let () =
88 let open Goptions in
89 declare_bool_option
90 { optstage = Summary.Stage.Interp;
91 optdepr = None;
92 optkey = ["Typeclasses";"Debug"];
93 optread = get_typeclasses_debug;
94 optwrite = set_typeclasses_debug; }
95
96 let () =
97 let open Goptions in
98 declare_int_option
99 { optstage = Summary.Stage.Interp;
100 optdepr = None;
101 optkey = ["Typeclasses";"Debug";"Verbosity"];
102 optread = get_typeclasses_verbose;
103 optwrite = set_typeclasses_verbose; }
104
105 let ppdebug lvl pp =
106 if !typeclasses_debug > lvl then Feedback.msg_debug (hov 2 @@ pp())
107
108 let get_debug () = !typeclasses_debug
109 end
110 open Debug
111 let set_typeclasses_debug = set_typeclasses_debug
112
113 type search_strategy = Dfs | Bfs
114
115 let set_typeclasses_strategy = function
116 | Dfs -> Goptions.set_bool_option_value iterative_deepening_opt_name false
117 | Bfs -> Goptions.set_bool_option_value iterative_deepening_opt_name true
118
119 let pr_ev evs ev =
120 let evi = Evd.find_undefined evs ev in
121 let env = Evd.evar_filtered_env (Global.env ()) evi in
122 Printer.pr_econstr_env env evs (Evd.evar_concl evi)
123
124 let pr_ev_with_id evs ev =
125 Evar.print ev ++ str " : " ++ pr_ev evs ev
126
127 (** Typeclasses instance search tactic / eauto *)
128
129 open Auto
130 open Unification
131
132 let auto_core_unif_flags st allowed_evars = {
133 modulo_conv_on_closed_terms = Some st;
134 use_metas_eagerly_in_conv_on_closed_terms = true;
135 use_evars_eagerly_in_conv_on_closed_terms = false;
136 modulo_delta = st;
137 modulo_delta_types = st;
138 check_applied_meta_types = false;
139 use_pattern_unification = true;
140 use_meta_bound_pattern_unification = true;
141 allowed_evars;
142 restrict_conv_on_strict_subterms = false; (* ? *)
143 modulo_betaiota = true;
144 modulo_eta = false;
145 }
146
147 let auto_unif_flags ?(allowed_evars = Evarsolve.AllowedEvars.all) st =
148 let fl = auto_core_unif_flags st allowed_evars in
149 { core_unify_flags = fl;
150 merge_unify_flags = fl;
151 subterm_unify_flags = fl;
152 allow_K_in_toplevel_higher_order_unification = false;
153 resolve_evars = false
154 }
155
156 let e_give_exact flags h =
157 Hints.hint_res_pf ~with_evars:false ~with_classes:false ~flags h
158
159 let unify_resolve ~with_evars flags h diff = match diff with
160 | None ->
161 Hints.hint_res_pf ~with_evars ~with_classes:false ~flags h
162 | Some (diff, ty) ->
163 let () = assert (Option.is_empty (fst @@ hint_as_term @@ h)) in
164 Proofview.Goal.enter begin fun gl ->
165 let env = Proofview.Goal.env gl in
166 let sigma = Proofview.Goal.sigma gl in
167 let sigma, c = Hints.fresh_hint env sigma h in
168 let clenv = Clenv.mk_clenv_from_n env sigma diff (c, ty) in
169 Clenv.res_pf ~with_evars ~with_classes:false ~flags clenv
170 end
171
172 (** Dealing with goals of the form A -> B and hints of the form
173 C -> A -> B.
174 *)
175 let with_prods nprods h f =
176 if get_typeclasses_limit_intros () then
177 Proofview.Goal.enter begin fun gl ->
178 if Option.has_some (fst @@ hint_as_term h) || Int.equal nprods 0 then f None
179 else
180 let sigma = Proofview.Goal.sigma gl in
181 let ty = Retyping.get_type_of (Proofview.Goal.env gl) sigma (snd @@ hint_as_term h) in
182 let diff = nb_prod sigma ty - nprods in
183 if (>=) diff 0 then f (Some (diff, ty))
184 else Tacticals.tclZEROMSG (str"Not enough premisses")
185 end
186 else Proofview.Goal.enter
187 begin fun gl ->
188 if Int.equal nprods 0 then f None
189 else Tacticals.tclZEROMSG (str"Not enough premisses") end
190
191 (** Semantics of type class resolution lemma application:
192
193 - Use unification to find a well-typed substitution. There might
194 be evars in the goal and the lemma. Evars in the goal can get refined.
195 - Independent evars are turned into goals, whatever their kind is.
196 - Dependent evars of the lemma corresponding to arguments which appear
197 in independent goals or the conclusion are turned into subgoals iff
198 they are of typeclass kind.
199 - The remaining dependent evars not of typeclass type are shelved,
200 and resolution must fill them for it to succeed, otherwise we
201 backtrack.
202 *)
203
204 let pr_gls sigma gls =
205 prlist_with_sep spc
206 (fun ev -> int (Evar.repr ev) ++ spc () ++ pr_ev sigma ev) gls
207
208 (** Ensure the dependent subgoals are shelved after an apply/eapply. *)
209 let shelve_dependencies gls =
210 let open Proofview in
211 if CList.is_empty gls then tclUNIT ()
212 else
213 tclEVARMAP >>= fun sigma ->
214 ppdebug 1 (fun () -> str" shelving dependent subgoals: " ++ pr_gls sigma gls);
215 shelve_goals gls
216
217 let hintmap_of env sigma hdc secvars concl =
218 match hdc with
219 | None -> fun db -> ModeMatch (NoMode, Hint_db.map_none ~secvars db)
220 | Some hdc ->
221 fun db -> Hint_db.map_eauto env sigma ~secvars hdc concl db
222
223 type hint_v = {
224 hint_tac : unit Proofview.tactic;
225 hint_prio : int;
226 hint_extern : bool;
227 hint_name : Names.GlobRef.t option;
228 hint_pp : Pp.t lazy_t;
229 }
230
231 (** Hack to properly solve dependent evars that are typeclasses *)
232 let rec e_trivial_fail_db db_list local_db secvars =
233 let open Tacticals in
234 let trivial_fail =
235 Proofview.Goal.enter
236 begin fun gl ->
237 let env = Proofview.Goal.env gl in
238 let sigma = Proofview.Goal.sigma gl in
239 let d = match EConstr.named_context env with
240 | [] -> assert false
241 | d :: _ -> NamedDecl.get_id d
242 in
243 let hints = push_resolve_hyp env sigma d local_db in
244 e_trivial_fail_db db_list hints secvars
245 end
246 in
247 let trivial_resolve =
248 Proofview.Goal.enter begin fun gl ->
249 let env = Proofview.Goal.env gl in
250 let sigma = Proofview.Goal.sigma gl in
251 let concl = Proofview.Goal.concl gl in
252 let tacs = e_trivial_resolve db_list local_db secvars env sigma concl in
253 tclFIRST (List.map (fun h -> h.hint_tac) tacs)
254 end
255 in
256 let tacl =
257 Eauto.e_assumption ::
258 (tclTHEN Tactics.intro trivial_fail :: [trivial_resolve])
259 in
260 tclSOLVE tacl
261
262 and e_my_find_search db_list local_db secvars hdc complete env sigma concl0 =
263 let prods, concl = EConstr.decompose_prod_decls sigma concl0 in
264 let nprods = List.length prods in
265 let allowed_evars =
266 let all = Evarsolve.AllowedEvars.all in
267 match hdc with
268 | Some (hd,_) ->
269 begin match Typeclasses.class_info env hd with
270 | Some cl ->
271 if cl.cl_strict then
272 let undefined = lazy (Evarutil.undefined_evars_of_term sigma concl) in
273 let allowed evk = not (Evar.Set.mem evk (Lazy.force undefined)) in
274 Evarsolve.AllowedEvars.from_pred allowed
275 else all
276 | None -> all
277 end
278 | _ -> all
279 in
280 let tac_of_hint (flags,h) =
281 let name = FullHint.name h in
282 let tac = function
283 | Res_pf h ->
284 let tac =
285 with_prods nprods h (unify_resolve ~with_evars:false flags h) in
286 Proofview.tclBIND (Proofview.with_shelf tac)
287 (fun (gls, ()) -> shelve_dependencies gls)
288 | ERes_pf h ->
289 let tac =
290 with_prods nprods h (unify_resolve ~with_evars:true flags h) in
291 Proofview.tclBIND (Proofview.with_shelf tac)
292 (fun (gls, ()) -> shelve_dependencies gls)
293 | Give_exact h ->
294 e_give_exact flags h
295 | Res_pf_THEN_trivial_fail h ->
296 let fst = with_prods nprods h (unify_resolve ~with_evars:true flags h) in
297 let snd = if complete then Tacticals.tclIDTAC
298 else e_trivial_fail_db db_list local_db secvars in
299 Tacticals.tclTHEN fst snd
300 | Unfold_nth c ->
301 Proofview.tclPROGRESS (unfold_in_concl [AllOccurrences,c])
302 | Extern (p, tacast) -> conclPattern concl0 p tacast
303 in
304 let tac = FullHint.run h tac in
305 let tac = if complete then Tacticals.tclCOMPLETE tac else tac in
306 let extern = match FullHint.repr h with
307 | Extern _ -> true
308 | _ -> false
309 in
310 { hint_tac = tac;
311 hint_prio = FullHint.priority h;
312 hint_extern = extern;
313 hint_name = name;
314 hint_pp = lazy (FullHint.print env sigma h);
315 }
316 in
317 let hint_of_db = hintmap_of env sigma hdc secvars concl in
318 let hintl = List.map_filter (fun db -> match hint_of_db db with
319 | ModeMatch (m, l) -> Some (db, m, l)
320 | ModeMismatch -> None)
321 (local_db :: db_list)
322 in
323 (* In case there is a mode mismatch in all the databases we get stuck.
324 Otherwise we consider the hints that match.
325 Recall the local database uses the union of all the modes in the other databases. *)
326 if List.is_empty hintl then None
327 else
328 let hintl =
329 CList.map
330 (fun (db, m, tacs) ->
331 let flags = auto_unif_flags ~allowed_evars (Hint_db.transparent_state db) in
332 m, List.map (fun x -> tac_of_hint (flags, x)) tacs)
333 hintl
334 in
335 let modes, hintl = List.split hintl in
336 let all_mode_match = List.for_all (fun m -> m != NoMode) modes in
337 let hintl = match hintl with
338 (* Optim: only sort if multiple hint sources were involved *)
339 | [hintl] -> hintl
340 | _ ->
341 let hintl = List.flatten hintl in
342 let hintl = List.stable_sort
343 (fun h1 h2 -> Int.compare h1.hint_prio h2.hint_prio)
344 hintl
345 in
346 hintl
347 in
348 Some (all_mode_match, hintl)
349
350 and e_trivial_resolve db_list local_db secvars env sigma concl : hint_v list =
351 let hd = try Some (decompose_app_bound sigma concl) with Bound -> None in
352 try
353 (match e_my_find_search db_list local_db secvars hd true env sigma concl with
354 | Some (_,l) -> l
355 | None -> [])
356 with Not_found -> []
357
358 let e_possible_resolve db_list local_db secvars env sigma concl =
359 let hd = try Some (decompose_app_bound sigma concl) with Bound -> None in
360 try
361 e_my_find_search db_list local_db secvars hd false env sigma concl
362 with Not_found -> Some (true, [])
363
364 let cut_of_hints h =
365 List.fold_left (fun cut db -> PathOr (Hint_db.cut db, cut)) PathEmpty h
366
367 let pr_depth l =
368 let rec fmt elts =
369 match elts with
370 | [] -> []
371 | [n] -> [string_of_int n]
372 | n1::n2::rest ->
373 (string_of_int n1 ^ "." ^ string_of_int n2) :: fmt rest
374 in
375 prlist_with_sep (fun () -> str "-") str (fmt (List.rev l))
376
377 let is_Prop env sigma concl =
378 let ty = Retyping.get_type_of env sigma concl in
379 match EConstr.kind sigma ty with
380 | Sort s ->
381 begin match ESorts.kind sigma s with
382 | Prop -> true
383 | _ -> false
384 end
385 | _ -> false
386
387 let is_unique env sigma concl =
388 try
389 let (cl,u), args = dest_class_app env sigma concl in
390 cl.cl_unique
391 with e when CErrors.noncritical e -> false
392
393 (** Sort the undefined variables from the least-dependent to most dependent. *)
394 let top_sort evm undefs =
395 let l' = ref [] in
396 let tosee = ref undefs in
397 let cache = Evarutil.create_undefined_evars_cache () in
398 let rec visit ev evi =
399 let evs = Evarutil.filtered_undefined_evars_of_evar_info ~cache evm evi in
400 tosee := Evar.Set.remove ev !tosee;
401 Evar.Set.iter (fun ev ->
402 if Evar.Set.mem ev !tosee then
403 visit ev (Evd.find_undefined evm ev)) evs;
404 l' := ev :: !l';
405 in
406 while not (Evar.Set.is_empty !tosee) do
407 let ev = Evar.Set.choose !tosee in
408 visit ev (Evd.find_undefined evm ev)
409 done;
410 List.rev !l'
411
412 (** We transform the evars that are concerned by this resolution
413 (according to predicate p) into goals.
414 Invariant: function p only manipulates and returns undefined evars
415 *)
416
417 let evars_to_goals p evm =
418 let goals, nongoals = Evar.Set.partition (p evm) (Evd.get_typeclass_evars evm) in
419 if Evar.Set.is_empty goals then None
420 else Some (goals, nongoals)
421
422 (** Making local hints *)
423 let make_resolve_hyp env sigma st only_classes decl db =
424 let id = NamedDecl.get_id decl in
425 let cty = NamedDecl.get_type decl in
426 let is_class =
427 let ctx, ar = decompose_prod_decls sigma cty in
428 match EConstr.kind sigma (fst (decompose_app sigma ar)) with
429 | Const (c,_) -> is_class env (GlobRef.ConstRef c)
430 | Ind (i,_) -> is_class env (GlobRef.IndRef i)
431 | _ -> false
432 in
433 let keep = not only_classes || is_class in
434 if keep then
435 let id = GlobRef.VarRef id in
436 push_resolves env sigma id db
437 else db
438
439 let make_hints env sigma (modes,st) only_classes sign =
440 let db = Hint_db.add_modes modes @@ Hint_db.empty st true in
441 List.fold_right
442 (fun hyp hints ->
443 let consider =
444 not only_classes ||
445 try let t = hyp |> NamedDecl.get_id |> Global.lookup_named |> NamedDecl.get_type in
446 (* Section variable, reindex only if the type changed *)
447 not (EConstr.eq_constr sigma (EConstr.of_constr t) (NamedDecl.get_type hyp))
448 with Not_found -> true
449 in
450 if consider then
451 make_resolve_hyp env sigma st only_classes hyp hints
452 else hints)
453 sign db
454
455 module Intpart = Unionfind.Make(Evar.Set)(Evar.Map)
456
457 type solver = { solver :
458 ?db:hint_db ->
459 Environ.env ->
460 Evd.evar_map ->
461 depth:int option ->
462 unique:bool ->
463 best_effort:bool ->
464 goals:Evar.t list ->
465 (bool * Evd.evar_map)
466 }
467
468 module Search = struct
469 type autoinfo =
470 { search_depth : int list;
471 last_tac : Pp.t Lazy.t;
472 search_dep : bool;
473 search_only_classes : bool;
474 search_cut : hints_path;
475 search_hints : hint_db;
476 search_best_effort : bool;
477 }
478
479 (** Local hints *)
480 let autogoal_cache = Summary.ref ~name:"autogoal_cache"
481 (Libnames.dummy_full_path, true, Context.Named.empty, Hints.Modes.empty,
482 Hint_db.empty TransparentState.full true, QGraph.initial_graph)
483
484 let make_autogoal_hints env sigma only_classes (modes,st as mst) =
485 let sign = EConstr.named_context env in
486 let qvars = Evd.elim_graph sigma in
487 let (dir, onlyc, sign', cached_modes, cached_hints, qvars') = !autogoal_cache in
488 let cwd = Lib.cwd () in
489 let eq c1 c2 = EConstr.eq_constr sigma c1 c2 in
490 if Libnames.eq_full_path cwd dir &&
491 (onlyc == only_classes) && qvars == qvars' &&
492 Context.Named.equal (ERelevance.equal sigma) eq sign sign' &&
493 cached_modes == modes
494 then cached_hints
495 else
496 let hints = make_hints env sigma mst only_classes sign in
497 autogoal_cache := (cwd, only_classes, sign, modes, hints, qvars); hints
498
499 let make_autogoal env sigma mst only_classes dep cut best_effort i =
500 let hints = make_autogoal_hints env sigma only_classes mst in
501 { search_hints = hints;
502 search_depth = [i]; last_tac = lazy (str"none");
503 search_dep = dep;
504 search_only_classes = only_classes;
505 search_cut = cut;
506 search_best_effort = best_effort }
507
508 (** In the proof engine failures are represented as exceptions *)
509 exception ReachedLimit
510 exception NoApplicableHint
511 exception StuckGoal
512
513 (** ReachedLimit has priority over NoApplicableHint to handle
514 iterative deepening: it should fail when no hints are applicable,
515 but go to a deeper depth otherwise. *)
516 let merge_exceptions e e' =
517 match fst e, fst e' with
518 | ReachedLimit, _ -> e
519 | _, ReachedLimit -> e'
520 | _, _ -> e
521
522 (** Determine if backtracking is needed for this goal.
523 We generally backtrack except in the following (possibly
524 overlapping) cases:
525 - [unique_instances] is [true].
526 This is the case when the goal's class has [Unique Instances].
527 - [indep] is [true] and the current goal has no evars.
528 [indep] is generally [true] and only gets set to [false] if the
529 current goal's evar is mentioned in other goals.
530 ([indep] is the negation of [search_dep].)
531 - The current goal is a [Prop] and has no evars. *)
532 let needs_backtrack env evd ~unique_instances ~indep concl =
533 if unique_instances then false else
534 if indep || is_Prop env evd concl then
535 occur_existential evd concl
536 else true
537
538 exception NonStuckFailure
539 (* exception Backtrack *)
540
541 let pr_goals s =
542 let open Proofview in
543 if get_debug() > 1 then
544 tclEVARMAP >>= fun sigma ->
545 Unsafe.tclGETGOALS >>= fun gls ->
546 let gls = CList.map Proofview.drop_state gls in
547 let j = List.length gls in
548 let pr_goal gl = pr_ev_with_id sigma gl in
549 Feedback.msg_debug
550 (s ++ int j ++ str" goals:" ++ spc () ++
551 prlist_with_sep Pp.fnl pr_goal gls);
552 tclUNIT ()
553 else
554 tclUNIT ()
555
556 let pr_internal_exception ie =
557 match fst ie with
558 | ReachedLimit -> str "Proof-search reached its limit."
559 | NoApplicableHint -> str "Proof-search failed."
560 | StuckGoal | NonStuckFailure -> str "Proof-search got stuck."
561 | e -> CErrors.iprint ie
562
563 (* XXX Is this handler needed for something? *)
564 let () = CErrors.register_handler begin function
565 | NonStuckFailure -> Some (str "NonStuckFailure")
566 | NoApplicableHint -> Some (str "NoApplicableHint")
567 | _ -> None
568 end
569
570 (**
571 For each success of tac1 try tac2.
572 If tac2 raises NonStuckFailure, try the next success of tac1 until depleted.
573 If tac1 finally fails, returns the result of the first tac1 success, if any.
574 *)
575
576 type goal_status =
577 | IsInitial
578 | IsStuckGoal
579 | IsNonStuckFailure
580
581 let pr_goal_status = function
582 | IsInitial -> str "initial"
583 | IsStuckGoal -> str "stuck"
584 | IsNonStuckFailure -> str "stuck failure"
585
586
587 let pr_search_goal sigma (glid, ev, status, _) =
588 str"Goal " ++ int glid ++ str" evar: " ++ Evar.print ev ++ str " status: " ++ pr_goal_status status
589
590 let pr_search_goals sigma =
591 prlist_with_sep fnl (pr_search_goal sigma)
592
593 let search_fixpoint ~best_effort ~allow_out_of_order tacs =
594 let open Pp in
595 let open Proofview in
596 let open Proofview.Notations in
597 let rec fixpoint progress tacs stuck fk =
598 let next (glid, ev, status, tac) tacs stuck =
599 let () = ppdebug 1 (fun () ->
600 str "considering goal " ++ int glid ++
601 str " of status " ++ pr_goal_status status)
602 in
603 let rec kont = function
604 | Fail ((NonStuckFailure | StuckGoal as exn), info) when allow_out_of_order ->
605 let () = ppdebug 1 (fun () ->
606 str "Goal " ++ int glid ++
607 str" is stuck or failed without being stuck, trying other tactics.")
608 in
609 let status =
610 match exn with
611 | NonStuckFailure -> IsNonStuckFailure
612 | StuckGoal -> IsStuckGoal
613 | _ -> assert false
614 in
615 cycle 1 (* Puts the first goal last *) <*>
616 fixpoint progress tacs ((glid, ev, status, tac) :: stuck) fk (* Launches the search on the rest of the goals *)
617 | Fail ie ->
618 let () = ppdebug 1 (fun () ->
619 str "Goal " ++ int glid ++ str" has no more solutions, returning exception: "
620 ++ pr_internal_exception ie)
621 in
622 fk ie
623 | Next (res, fk') ->
624 let () = ppdebug 1 (fun () ->
625 str "Goal " ++ int glid ++ str" has a success, continuing resolution")
626 in
627 (* We try to solve the rest of the constraints, and if that fails
628 we backtrack to the next result of tac, etc.... Ultimately if none of the solutions
629 for tac work, we will come back to the failure continuation fk in one of
630 the above cases *)
631 fixpoint true tacs stuck (fun e -> tclCASE (fk' e) >>= kont)
632 in tclCASE tac >>= kont
633 in
634 tclEVARMAP >>= fun sigma ->
635 let () = ppdebug 1 (fun () ->
636 let stuck, failed = List.partition (fun (_, _, status, _) -> status = IsStuckGoal) stuck in
637 str"Calling fixpoint on : " ++
638 int (List.length tacs) ++ str" initial goals" ++
639 str", " ++ int (List.length stuck) ++ str" stuck goals" ++
640 str" and " ++ int (List.length failed) ++ str" non-stuck failures kept" ++
641 str" with " ++ str(if progress then "" else "no ") ++
642 str"progress made in this run." ++ fnl () ++
643 str "Stuck: " ++ pr_search_goals sigma stuck ++ fnl () ++
644 str "Failed: " ++ pr_search_goals sigma failed ++ fnl () ++
645 str "Initial: " ++ pr_search_goals sigma tacs)
646 in
647 tclCHECKINTERRUPT <*>
648 match tacs with
649 | tac :: tacs -> next tac tacs stuck
650 | [] -> (* All remaining goals are stuck *)
651 match stuck with
652 | [] ->
653 (* We found a solution! Great, but in case it's not good for the rest of the proof search,
654 we might have other solutions available through fk. *)
655 tclOR (tclUNIT ()) fk
656 | stuck ->
657 if progress then fixpoint false stuck [] fk
658 else (* No progress can be made on the stuck goals arising from this resolution,
659 try a different solution on the non-stuck goals, if any. *)
660 begin
661 tclORELSE (fk (NoApplicableHint, Exninfo.null))
662 (fun (e, info) ->
663 let () = ppdebug 1 (fun () -> int (List.length stuck) ++ str " remaining goals left, no progress, calling continuation failed")
664 in
665 (* We keep the stuck goals to display to the user *)
666 if best_effort then
667 let stuckgls, failedgls = List.partition (fun (_, _, status, _) ->
668 match status with
669 | IsStuckGoal -> true
670 | IsNonStuckFailure -> false
671 (* There should remain no initial goals at this point *)
672 | IsInitial -> assert false)
673 stuck
674 in
675 pr_goals (str "best_effort is on and remaining goals are: ") <*>
676 (* We shelve the stuck goals but we keep the non-stuck failures in the goal list.
677 This is for compat with Coq 8.12 but might not be the wisest choice in the long run.
678 *)
679 let to_shelve = List.map (fun (glid, ev, _, _) -> ev) stuckgls in
680 let () = ppdebug 1 (fun () ->
681 str "Shelving subgoals: " ++
682 prlist_with_sep spc Evar.print to_shelve)
683 in
684 Unsafe.tclNEWSHELVED to_shelve
685 else tclZERO ~info e)
686 end
687 in
688 pr_goals (str"Launching resolution fixpoint on ") <*>
689 Unsafe.tclGETGOALS >>= fun gls ->
690 (* We wrap all goals with their associated tactic.
691 It might happen that an initial goal is solved during the resolution of another goal,
692 hence the `tclUNIT` in case there is no goal for the tactic to apply anymore. *)
693 let tacs = List.map2_i
694 (fun i gls tac -> (succ i, Proofview.drop_state gls, IsInitial, tclFOCUS ~nosuchgoal:(tclUNIT ()) 1 1 tac))
695 0 gls tacs
696 in
697 fixpoint false tacs [] (fun (e, info) -> tclZERO ~info e) <*>
698 pr_goals (str "Result goals after fixpoint: ")
699
700
701 (** The general hint application tactic.
702 tac1 + tac2 .... The choice of OR or ORELSE is determined
703 depending on the dependencies of the goal and the unique/Prop
704 status *)
705 let hints_tac hints info kont =
706 Proofview.Goal.enter begin fun gl ->
707 let open Proofview in
708 let open Proofview.Notations in
709 let env = Goal.env gl in
710 let concl = Goal.concl gl in
711 let sigma = Goal.sigma gl in
712 let unique_instances = is_unique env sigma concl in
713 let indep = not info.search_dep in
714 let backtrack = needs_backtrack env sigma ~unique_instances ~indep concl in
715 let () = ppdebug 0 (fun () ->
716 pr_depth info.search_depth ++ str": looking for " ++
717 Printer.pr_econstr_env (Goal.env gl) sigma concl ++
718 (if backtrack then str" with backtracking"
719 else str" without backtracking"))
720 in
721 let secvars = compute_secvars gl in
722 match e_possible_resolve hints info.search_hints secvars
723 env sigma concl with
724 | None ->
725 Proofview.tclZERO StuckGoal
726 | Some (all_mode_match, poss) ->
727 (* If no goal depends on the solution of this one or the
728 instances are irrelevant/assumed to be unique, then
729 we don't need to backtrack, as long as no evar appears in the goal
730 This is an overapproximation. Evars could appear in this goal only
731 and not any other *)
732 let ortac = if backtrack then Proofview.tclOR else Proofview.tclORELSE in
733 let idx = ref 1 in
734 let foundone = ref false in
735 let rec onetac e { hint_tac = tac; hint_extern; hint_name = name; hint_pp = pp } tl =
736 let derivs = path_derivate env info.search_cut name in
737 let pr_error ie =
738 ppdebug 1 (fun () ->
739 let idx = if fst ie == NoApplicableHint then pred !idx else !idx in
740 let header =
741 pr_depth (idx :: info.search_depth) ++ str": " ++
742 Lazy.force pp ++
743 (if !foundone != true then
744 str" on" ++ spc () ++ pr_ev sigma (Proofview.Goal.goal gl)
745 else mt ())
746 in
747 (header ++ spc() ++ str "failed with: " ++ pr_internal_exception ie))
748 in
749 let tac_of gls i j = Goal.enter begin fun gl' ->
750 let env = Proofview.Goal.env gl' in
751 let sigma' = Goal.sigma gl' in
752 let () = ppdebug 0 (fun () ->
753 pr_depth (succ j :: i :: info.search_depth) ++ str" : " ++
754 pr_ev sigma' (Proofview.Goal.goal gl'))
755 in
756 let eq c1 c2 = EConstr.eq_constr sigma' c1 c2 in
757 let hints' =
758 if hint_extern && not (Context.Named.equal (ERelevance.equal sigma) eq (Goal.hyps gl') (Goal.hyps gl))
759 then
760 let st = Hint_db.transparent_state info.search_hints in
761 let modes = Hint_db.modes info.search_hints in
762 make_autogoal_hints env sigma' info.search_only_classes (modes,st)
763 else info.search_hints
764 in
765 let dep' = info.search_dep || Proofview.unifiable sigma' (Goal.goal gl') gls in
766 let info' =
767 { search_depth = succ j :: i :: info.search_depth;
768 last_tac = pp;
769 search_dep = dep';
770 search_only_classes = info.search_only_classes;
771 search_hints = hints';
772 search_cut = derivs;
773 search_best_effort = info.search_best_effort }
774 in kont info' end
775 in
776 let rec result (shelf, ()) i k =
777 foundone := true;
778 Proofview.Unsafe.tclGETGOALS >>= fun gls ->
779 let gls = CList.map Proofview.drop_state gls in
780 let j = List.length gls in
781 let () = ppdebug 0 (fun () ->
782 pr_depth (i :: info.search_depth) ++ str": " ++ Lazy.force pp
783 ++ str" on" ++ spc () ++ pr_ev sigma (Proofview.Goal.goal gl)
784 ++ str", " ++ int j ++ str" subgoal(s)" ++
785 (Option.cata (fun k -> str " in addition to the first " ++ int k)
786 (mt()) k))
787 in
788 let res =
789 if j = 0 then tclUNIT ()
790 else search_fixpoint ~best_effort:false ~allow_out_of_order:false
791 (List.init j (fun j' -> (tac_of gls i (Option.default 0 k + j'))))
792 in
793 let finish nestedshelf sigma =
794 let filter ev =
795 try
796 let evi = Evd.find_undefined sigma ev in
797 if info.search_only_classes then
798 Some (ev, not (is_class_evar env sigma evi))
799 else Some (ev, true)
800 with Not_found -> None
801 in
802 let remaining = CList.map_filter filter shelf in
803 let () = ppdebug 1 (fun () ->
804 let prunsolved (ev, _) = int (Evar.repr ev) ++ spc () ++ pr_ev sigma ev in
805 let unsolved = prlist_with_sep spc prunsolved remaining in
806 pr_depth (i :: info.search_depth) ++
807 str": after " ++ Lazy.force pp ++ str" finished, " ++
808 int (List.length remaining) ++
809 str " goals are shelved and unsolved ( " ++
810 unsolved ++ str")")
811 in
812 begin
813 (* Some existentials produced by the original tactic were not solved
814 in the subgoals, turn them into subgoals now. *)
815 let shelved, goals = List.partition (fun (ev, s) -> s) remaining in
816 let shelved = List.map fst shelved @ nestedshelf and goals = List.map fst goals in
817 let () = if not (List.is_empty shelved && List.is_empty goals) then
818 ppdebug 1 (fun () ->
819 str"Adding shelved subgoals to the search: " ++
820 prlist_with_sep spc (pr_ev sigma) goals ++
821 str" while shelving " ++
822 prlist_with_sep spc (pr_ev sigma) shelved)
823 in
824 shelve_goals shelved <*>
825 if List.is_empty goals then tclUNIT ()
826 else
827 let make_unresolvables = tclEVARMAP >>= fun sigma ->
828 let sigma = make_unresolvables (fun x -> List.mem_f Evar.equal x goals) sigma in
829 Unsafe.tclEVARS sigma
830 in
831 let goals = CList.map Proofview.with_empty_state goals in
832 with_shelf (make_unresolvables <*> Unsafe.tclNEWGOALS goals) >>= fun s ->
833 result s i (Some (Option.default 0 k + j))
834 end
835 in
836 with_shelf res >>= fun (sh, ()) ->
837 tclEVARMAP >>= finish sh
838 in
839 if path_matches_epsilon derivs then aux e tl
840 else
841 ortac
842 (with_shelf tac >>= fun s ->
843 let i = !idx in incr idx; result s i None)
844 (fun e' ->
845 (pr_error e'; aux (merge_exceptions e e') tl))
846 and aux e = function
847 | tac :: tacs -> onetac e tac tacs
848 | [] ->
849 let () = if !foundone == false then
850 ppdebug 0 (fun () ->
851 pr_depth info.search_depth ++ str": no match for " ++
852 Printer.pr_econstr_env (Goal.env gl) sigma concl ++
853 str ", " ++ int (List.length poss) ++
854 str" possibilities")
855 in
856 match e with
857 | (ReachedLimit,ie) -> Proofview.tclZERO ~info:ie ReachedLimit
858 | (StuckGoal,ie) -> Proofview.tclZERO ~info:ie StuckGoal
859 | (NoApplicableHint,ie) ->
860 (* If the constraint abides by the (non-trivial) modes but no
861 solution could be found, we consider it a failed goal, and let
862 proof search proceed on the rest of the
863 constraints, thus giving a more precise error message. *)
864 if all_mode_match &&
865 info.search_best_effort then
866 Proofview.tclZERO ~info:ie NonStuckFailure
867 else Proofview.tclZERO ~info:ie NoApplicableHint
868 | (_,ie) -> Proofview.tclZERO ~info:ie NoApplicableHint
869 in
870 if backtrack then aux (NoApplicableHint,Exninfo.null) poss
871 else tclONCE (aux (NoApplicableHint,Exninfo.null) poss)
872 end
873
874 let intro_tac info kont =
875 Proofview.Goal.enter begin fun gl ->
876 let open Proofview in
877 let env = Goal.env gl in
878 let sigma = Goal.sigma gl in
879 let decl = match EConstr.named_context env with
880 | [] -> assert false
881 | decl :: _ -> decl
882 in
883 let ldb =
884 make_resolve_hyp env sigma (Hint_db.transparent_state info.search_hints)
885 info.search_only_classes decl info.search_hints in
886 let info' =
887 { info with search_hints = ldb; last_tac = lazy (str"intro");
888 search_depth = 1 :: 1 :: info.search_depth }
889 in
890 kont info'
891 end
892
893 let intro info kont =
894 Tactics.intro <*> intro_tac info kont
895
896 let rec search_tac hints limit depth =
897 let kont info =
898 Proofview.numgoals >>= fun i ->
899 let () = ppdebug 1 (fun () ->
900 str "calling eauto recursively at depth " ++ int (succ depth) ++
901 str " on " ++ int i ++ str " subgoals")
902 in
903 search_tac hints limit (succ depth) info
904 in
905 fun info ->
906 if Int.equal depth (succ limit) then
907 let info = Exninfo.reify () in
908 Proofview.tclZERO ~info ReachedLimit
909 else
910 Proofview.tclOR (hints_tac hints info kont)
911 (fun e -> Proofview.tclOR (intro info kont)
912 (fun e' -> let (e, info) = merge_exceptions e e' in
913 Proofview.tclZERO ~info e))
914
915 let search_tac mst only_classes best_effort dep hints depth =
916 let tac gls i =
917 Proofview.Goal.enter begin fun gl ->
918 let env = Proofview.Goal.env gl in
919 let sigma = Proofview.Goal.sigma gl in
920 let i = succ i in
921 let dep = dep || Proofview.unifiable sigma (Proofview.Goal.goal gl) gls in
922 let info = make_autogoal env sigma mst only_classes dep (cut_of_hints hints) best_effort i in
923 search_tac hints depth 1 info
924 end
925 in
926 Proofview.Unsafe.tclGETGOALS >>= fun gls ->
927 let gls = CList.map Proofview.drop_state gls in
928 let j = List.length gls in
929 search_fixpoint ~best_effort ~allow_out_of_order:true (List.init j (fun i -> tac gls i))
930
931 let fix_iterative t =
932 let rec aux depth =
933 Proofview.tclOR
934 (t depth)
935 (function
936 | (ReachedLimit,_) -> aux (succ depth)
937 | (e,ie) -> Proofview.tclZERO ~info:ie e)
938 in aux 1
939
940 let fix_iterative_limit limit t =
941 let open Proofview in
942 let rec aux depth =
943 if Int.equal depth (succ limit)
944 then
945 let info = Exninfo.reify () in
946 tclZERO ~info ReachedLimit
947 else tclOR (t depth) (function
948 | (ReachedLimit, _) -> aux (succ depth)
949 | (e,ie) -> Proofview.tclZERO ~info:ie e)
950 in aux 1
951
952 let eauto_tac_stuck mst ?(unique=false)
953 ~only_classes
954 ~best_effort
955 ?strategy ~depth ~dep hints =
956 let open Proofview in
957 let tac =
958 let search = search_tac mst only_classes best_effort dep hints in
959 let dfs =
960 match strategy with
961 | None -> not (get_typeclasses_iterative_deepening ())
962 | Some Dfs -> true
963 | Some Bfs -> false
964 in
965 if dfs then
966 let depth = match depth with None -> -1 | Some d -> d in
967 search depth
968 else
969 match depth with
970 | None -> fix_iterative search
971 | Some l -> fix_iterative_limit l search
972 in
973 let error (e, info) =
974 match e with
975 | ReachedLimit ->
976 Tacticals.tclFAIL ~info (str"Proof search reached its limit")
977 | NoApplicableHint ->
978 Tacticals.tclFAIL ~info (str"Proof search failed" ++
979 (if Option.is_empty depth then mt()
980 else str" without reaching its limit"))
981 | Proofview.MoreThanOneSuccess ->
982 Tacticals.tclFAIL ~info (str"Proof search failed: " ++
983 str"more than one success found")
984 | e -> Proofview.tclZERO ~info e
985 in
986 let tac = Proofview.tclOR tac error in
987 let tac =
988 if unique then
989 Proofview.tclEXACTLY_ONCE Proofview.MoreThanOneSuccess tac
990 else tac
991 in
992 with_shelf numgoals >>= fun (initshelf, i) ->
993 let () = ppdebug 1 (fun () ->
994 str"Starting resolution with " ++ int i ++
995 str" goal(s) under focus and " ++
996 int (List.length initshelf) ++ str " shelved goal(s)" ++
997 (if only_classes then str " in only_classes mode" else str " in regular mode") ++
998 match depth with
999 | None -> str ", unbounded"
1000 | Some i -> str ", with depth limit " ++ int i)
1001 in
1002 tac <*> pr_goals (str "after eauto_tac_stuck: ")
1003
1004 let eauto_tac mst ?unique ~only_classes ~best_effort ?strategy ~depth ~dep hints =
1005 eauto_tac_stuck mst ?unique ~only_classes
1006 ~best_effort ?strategy ~depth ~dep hints
1007
1008 let preprocess_goals evm goals =
1009 let sorted_goals =
1010 if get_typeclasses_dependency_order () then
1011 top_sort evm goals
1012 else Evar.Set.elements goals
1013 in
1014 let evm = Evd.set_typeclass_evars evm Evar.Set.empty in
1015 let evm = Evd.push_future_goals evm in
1016 evm, sorted_goals
1017
1018
1019 let run_on_goals env evm tac ~goals =
1020 let goalsl = List.map Proofview.with_empty_state goals in
1021 let tac = Proofview.Unsafe.tclNEWGOALS goalsl <*> tac in
1022 let _, pv = Proofview.init evm [] in
1023 (* Instance may try to call this before a proof is set up!
1024 Thus, give_me_the_proof will fail. Beware! *)
1025 let name, poly =
1026 (* try
1027 * let Proof.{ name; poly } = Proof.data Proof_global.(give_me_the_proof ()) in
1028 * name, poly
1029 * with | Proof_global.NoCurrentProof -> *)
1030 Id.of_string "instance", PolyFlags.default
1031 in
1032 let tac =
1033 if get_debug () > 1 then Proofview.Trace.record_info_trace tac
1034 else tac
1035 in
1036 let (), pv', _, unsafe, info =
1037 try Proofview.apply ~name ~poly env tac pv
1038 with Logic_monad.TacticFailure _ -> raise Not_found
1039 in
1040 let () =
1041 ppdebug 1 (fun () ->
1042 str"The tactic trace is: " ++ hov 0 (Proofview.Trace.pr_info env evm ~lvl:1 info))
1043 in
1044 let finished = Proofview.finished pv' in
1045 let evm' = Proofview.return pv' in
1046 (finished, evm')
1047
1048 let post_process_goals ~goals ~nongoals ~sigma ~finished =
1049 let _, sigma = Evd.pop_future_goals sigma in
1050 let tc_evars = Evd.get_typeclass_evars sigma in
1051 let () = ppdebug 1 (fun () ->
1052 str"Finished resolution with " ++ str(if finished then "a complete" else "an incomplete") ++
1053 str" solution." ++ fnl() ++
1054 str"Old typeclass evars not concerned by this resolution = " ++
1055 hov 0 (prlist_with_sep spc (pr_ev_with_id sigma)
1056 (Evar.Set.elements tc_evars)) ++ fnl() ++
1057 str"Shelf = " ++
1058 hov 0 (prlist_with_sep spc (pr_ev_with_id sigma)
1059 (Evar.Set.elements tc_evars)))
1060 in
1061 let nongoals =
1062 Evar.Set.fold (fun ev acc -> match Evarutil.advance sigma ev with
1063 | Some ev -> Evar.Set.add ev acc
1064 | None -> acc) (Evar.Set.union goals nongoals) tc_evars
1065 in
1066 let sigma = Evd.set_typeclass_evars sigma nongoals in
1067 let () = ppdebug 1 (fun () ->
1068 str"New typeclass evars are: " ++
1069 hov 0 (prlist_with_sep spc (pr_ev_with_id sigma) (Evar.Set.elements nongoals)))
1070 in
1071 sigma
1072
1073
1074 (** Typeclasses eauto is an eauto which tries to resolve only
1075 goals of typeclass type, and assumes that the initially selected
1076 evars in evd are independent of the rest of the evars *)
1077 let typeclasses_eauto env evd ~goals ?depth ~unique ~best_effort st hints =
1078 let only_classes = true in
1079 let dep = unique in
1080 NewProfile.profile "typeclass search" (fun () ->
1081 run_on_goals env evd (eauto_tac_stuck st ~unique ~only_classes ~best_effort ~depth ~dep hints) ~goals) ()
1082
1083 let typeclasses_resolve : solver = { solver = fun ?db env evd ~depth ~unique ~best_effort ~goals ->
1084 let db = match db with
1085 | None -> searchtable_map typeclasses_db
1086 | Some db -> db
1087 in
1088 let st = Hint_db.transparent_state db in
1089 let modes = Hint_db.modes db in
1090 typeclasses_eauto env evd ~goals ?depth ~best_effort ~unique (modes,st) [db]
1091 }
1092 end
1093
1094 let typeclasses_eauto ?(only_classes=false)
1095 ?(best_effort=false)
1096 ?(st=TransparentState.full)
1097 ?strategy ~depth dbs =
1098 let dbs = List.map_filter
1099 (fun db -> try Some (searchtable_map db)
1100 with e when CErrors.noncritical e -> None)
1101 dbs
1102 in
1103 let st = match dbs with x :: _ -> Hint_db.transparent_state x | _ -> st in
1104 let modes = List.map Hint_db.modes dbs in
1105 let modes = List.fold_left Modes.union Modes.empty modes in
1106 let depth = match depth with None -> get_typeclasses_depth () | Some l -> Some l in
1107 Proofview.tclIGNORE
1108 (Search.eauto_tac (modes,st) ~only_classes ?strategy
1109 ~best_effort ~depth ~dep:true dbs)
1110 (* Stuck goals can remain here, we could shelve them, but this way
1111 the user can use `solve [typeclasses eauto]` to check there are
1112 no stuck goals remaining, or use [typeclasses eauto; shelve] himself. *)
1113
1114 (** We compute dependencies via a union-find algorithm.
1115 Beware of the imperative effects on the partition structure,
1116 it should not be shared, but only used locally. *)
1117
1118 let deps_of_constraints cstrs evm p =
1119 List.iter (fun (_, _, x, y) ->
1120 let evx = Evarutil.undefined_evars_of_term evm x in
1121 let evy = Evarutil.undefined_evars_of_term evm y in
1122 Intpart.union_set (Evar.Set.union evx evy) p)
1123 cstrs
1124
1125 let evar_dependencies pred evm p =
1126 let cache = Evarutil.create_undefined_evars_cache () in
1127 Evd.fold_undefined
1128 (fun ev evi _ ->
1129 if Evd.is_typeclass_evar evm ev && pred evm ev evi then
1130 let evars = Evar.Set.add ev (Evarutil.filtered_undefined_evars_of_evar_info ~cache evm evi)
1131 in Intpart.union_set evars p
1132 else ())
1133 evm ()
1134
1135 (** [split_evars] returns groups of undefined evars according to dependencies *)
1136
1137 let split_evars pred env evm =
1138 let p = Intpart.create () in
1139 evar_dependencies pred evm p;
1140 deps_of_constraints (snd (extract_all_conv_pbs evm)) evm p;
1141 let part = Intpart.partition p in
1142 let is_strictly_unique ev =
1143 let evi = Evd.find_undefined evm ev in
1144 let concl = Evd.evar_concl evi in
1145 match Typeclasses.class_of_constr env evm concl with
1146 | None -> false
1147 | Some (_, ((cl, _), _)) ->
1148 cl.cl_strict && cl.cl_unique
1149 in
1150 let fn evs =
1151 let (strictly_uniques, rest) = Evar.Set.partition is_strictly_unique evs in
1152 List.rev_append (List.rev_map Evar.Set.singleton (Evar.Set.elements strictly_uniques)) [rest]
1153 in
1154 List.concat_map fn part
1155
1156 let is_inference_forced p evd ev =
1157 try
1158 if Evar.Set.mem ev (Evd.get_typeclass_evars evd) && p ev
1159 then
1160 let (loc, k) = evar_source (Evd.find_undefined evd ev) in
1161 match k with
1162 | Evar_kinds.ImplicitArg (_, _, b) -> b
1163 | Evar_kinds.QuestionMark _ -> false
1164 | _ -> true
1165 else true
1166 with Not_found -> assert false
1167
1168 let is_mandatory p comp evd =
1169 Evar.Set.exists (is_inference_forced p evd) comp
1170
1171 (** Check if an evar is concerned by the current resolution attempt,
1172 (and in particular is in the current component).
1173 Invariant : this should only be applied to undefined evars. *)
1174
1175 let select_and_update_evars p oevd in_comp evd ev =
1176 try
1177 if Evd.is_typeclass_evar oevd ev then
1178 (in_comp ev && p evd ev (Evd.find_undefined evd ev))
1179 else false
1180 with Not_found -> false
1181
1182 (** Do we still have unresolved evars that should be resolved ? *)
1183
1184 let has_undefined p oevd evd =
1185 let check ev evi = p oevd ev in
1186 Evar.Map.exists check (Evd.undefined_map evd)
1187 let find_undefined p oevd evd =
1188 let check ev evi = p oevd ev in
1189 Evar.Map.domain (Evar.Map.filter check (Evd.undefined_map evd))
1190
1191 exception Unresolved of evar_map
1192
1193 type condition = Environ.env -> evar_map -> Evar.Set.t -> bool
1194
1195 type tc_solver = solver * condition
1196
1197 let class_solvers = ref (CString.Map.empty : tc_solver CString.Map.t)
1198
1199 let register_solver ~name ?(override=false) h =
1200 if not override && CString.Map.mem name !class_solvers then
1201 CErrors.anomaly ~label:"Class_tactics.register_solver"
1202 Pp.(str (Printf.sprintf {|Solver "%s" is already registered|} name));
1203 class_solvers := CString.Map.add name h !class_solvers
1204
1205 let active_solvers = Summary.ref ~name:"typeclass_solvers" ([] : string list)
1206
1207 let deactivate_solver ~name =
1208 active_solvers := List.filter (fun s -> not (String.equal s name)) !active_solvers
1209
1210 let activate_solver ~name =
1211 assert (CString.Map.mem name !class_solvers);
1212 deactivate_solver ~name;
1213 active_solvers := name :: !active_solvers
1214
1215 let find_solver env evd (s : Intpart.set) =
1216 let rec find_solver = function
1217 | [] -> Search.typeclasses_resolve
1218 | hd :: tl ->
1219 try
1220 let (solver,cond) = CString.Map.find hd !class_solvers in
1221 if cond env evd s then solver else find_solver tl
1222 with Not_found -> find_solver tl in
1223 find_solver !active_solvers
1224
1225 (** If [do_split] is [true], we try to separate the problem in
1226 several components and then solve them separately *)
1227 let resolve_all_evars depth unique env p oevd fail =
1228 let () =
1229 ppdebug 0 (fun () ->
1230 str"Calling typeclass resolution with flags: "++
1231 str"depth = " ++ (match depth with None -> str "∞" | Some d -> int d) ++ str"," ++
1232 str"unique = " ++ bool unique ++ str"," ++
1233 str"fail = " ++ bool fail);
1234 ppdebug 2 (fun () ->
1235 str"Initial evar map: " ++
1236 Termops.pr_evar_map ~with_univs:!PrintingFlags.print_universes None env oevd)
1237 in
1238 let split = split_evars p env oevd in
1239 let in_comp comp ev = Evar.Set.mem ev comp in
1240 let rec docomp evd = function
1241 | [] ->
1242 let () = ppdebug 2 (fun () ->
1243 str"Final evar map: " ++
1244 Termops.pr_evar_map ~with_univs:!PrintingFlags.print_universes None env evd)
1245 in
1246 evd
1247 | comp :: comps ->
1248 let p = select_and_update_evars p oevd (in_comp comp) in
1249 try
1250 (try
1251 (* evars_to_goals p evd gives none when there's no evar having p *)
1252 match evars_to_goals p evd with
1253 | Some (goals, nongoals) ->
1254 let solver = find_solver env evd comp in
1255 let evd, sorted_goals = Search.preprocess_goals evd goals in
1256 let finished, evd = solver.solver env evd ~goals:sorted_goals ~best_effort:true ~depth ~unique in
1257 let evd = Search.post_process_goals ~goals ~nongoals ~sigma:evd ~finished in
1258 if has_undefined p oevd evd then
1259 let () = if finished then ppdebug 1 (fun () ->
1260 str"Proof is finished but there remain undefined evars: " ++
1261 prlist_with_sep spc (pr_ev evd)
1262 (Evar.Set.elements (find_undefined p oevd evd)))
1263 in
1264 raise (Unresolved evd)
1265 else docomp evd comps
1266 | None -> docomp evd comps (* No typeclass evars left in this component *)
1267 with Not_found ->
1268 (* Typeclass resolution failed *)
1269 raise (Unresolved evd))
1270 with Unresolved evd' ->
1271 if fail && is_mandatory (p evd') comp evd'
1272 then (* Unable to satisfy the constraints. *)
1273 error_unresolvable env evd' comp
1274 else (* Best effort: use the best found solution on this component *)
1275 docomp evd' comps
1276 in docomp oevd split
1277
1278 let initial_select_evars env filter =
1279 fun evd ev evi ->
1280 filter ev (Lazy.from_val (snd (Evd.evar_source evi))) &&
1281 (* Typeclass evars can contain evars whose conclusion is not
1282 yet determined to be a class or not. *)
1283 Typeclasses.is_class_evar env evd evi
1284
1285
1286 let classes_transparent_state db () =
1287 let db = match db with
1288 | None -> searchtable_map typeclasses_db
1289 | Some db -> db
1290 in
1291 try Hint_db.transparent_state db
1292 with Not_found -> TransparentState.empty
1293
1294 let resolve_typeclass_evars depth unique env evd filter fail =
1295 let evd =
1296 try Evarconv.solve_unif_constraints_with_heuristics
1297 ~flags:(Evarconv.default_flags_of (classes_transparent_state None ())) env evd
1298 with e when CErrors.noncritical e -> evd
1299 in
1300 resolve_all_evars depth unique env
1301 (initial_select_evars env filter) evd fail
1302
1303 let solve_inst env evd filter unique fail =
1304 resolve_typeclass_evars (get_typeclasses_depth ()) unique env evd filter fail
1305
1306 let () =
1307 Typeclasses.set_solve_all_instances solve_inst
1308
1309 let resolve_one_typeclass ?db env sigma concl =
1310 let db = match db with
1311 | None -> searchtable_map typeclasses_db
1312 | Some db -> db
1313 in
1314 let st = Hint_db.transparent_state db in
1315 let modes = Hint_db.modes db in
1316 let depth = get_typeclasses_depth () in
1317 let tac = Tacticals.tclCOMPLETE (Search.eauto_tac (modes,st)
1318 ~only_classes:true ~best_effort:false
1319 ~depth [db] ~dep:true)
1320 in
1321 let entry, pv = Proofview.init sigma [env, concl] in
1322 let pv =
1323 let name = Names.Id.of_string "legacy_pe" in
1324 match Proofview.apply ~name ~poly:PolyFlags.default (Global.env ()) tac pv with
1325 | (_, final, _, _, _) -> final
1326 | exception (Logic_monad.TacticFailure (Tacticals.FailError _)) ->
1327 raise Not_found
1328 in
1329 let evd = Proofview.return pv in
1330 let term = match Proofview.partial_proof entry pv with [t] -> t | _ -> assert false in
1331 evd, term
1332
1333 let () = (Typeclasses.set_solve_one_instance[@warning "-3"]) resolve_one_typeclass
1334
1335 (** Take the head of the arity of a constr.
1336 Used in the partial application tactic. *)
1337
1338 let rec head_of_constr sigma t =
1339 let t = strip_outer_cast sigma t in
1340 match EConstr.kind sigma t with
1341 | Prod (_,_,c2) -> head_of_constr sigma c2
1342 | LetIn (_,_,_,c2) -> head_of_constr sigma c2
1343 | App (f,args) -> head_of_constr sigma f
1344 | _ -> t
1345
1346 let head_of_constr h c =
1347 Proofview.tclEVARMAP >>= fun sigma ->
1348 let c = head_of_constr sigma c in
1349 letin_tac None (Name h) c None Locusops.allHyps
1350
1351 let not_evar c =
1352 Proofview.tclEVARMAP >>= fun sigma ->
1353 match EConstr.kind sigma c with
1354 | Evar _ -> Tacticals.tclFAIL (str"Evar")
1355 | _ -> Proofview.tclUNIT ()
1356
1357 let is_ground c =
1358 let open Tacticals in
1359 Proofview.tclEVARMAP >>= fun sigma ->
1360 if Evarutil.is_ground_term sigma c then tclIDTAC
1361 else tclFAIL (str"Not ground")
1362
1363 let autoapply c i =
1364 let open Proofview.Notations in
1365 Proofview.Goal.enter begin fun gl ->
1366 let hintdb = try Hints.searchtable_map i with Not_found ->
1367 CErrors.user_err (Pp.str ("Unknown hint database " ^ i ^ "."))
1368 in
1369 let flags = auto_unif_flags
1370 (Hints.Hint_db.transparent_state hintdb) in
1371 let env = Proofview.Goal.env gl in
1372 let sigma = Proofview.Goal.sigma gl in
1373 let cty = Retyping.get_type_of env sigma c in
1374 let ce = Clenv.mk_clenv_from env sigma (c,cty) in
1375 Clenv.res_pf ~with_evars:true ~with_classes:false ~flags ce <*>
1376 Proofview.tclEVARMAP >>= (fun sigma ->
1377 let sigma = Typeclasses.make_unresolvables
1378 (fun ev -> Typeclasses.all_goals ev (Lazy.from_val (snd (Evd.evar_source (Evd.find_undefined sigma ev))))) sigma in
1379 Proofview.Unsafe.tclEVARS sigma) end
1380
1381 let resolve_tc c =
1382 let open Proofview.Notations in
1383 Proofview.tclENV >>= fun env ->
1384 Proofview.tclEVARMAP >>= fun sigma ->
1385 let depth = get_typeclasses_depth () in
1386 let unique = get_typeclasses_unique_solutions () in
1387 let evars = Evarutil.undefined_evars_of_term sigma c in
1388 let filter = (fun ev _ -> Evar.Set.mem ev evars) in
1389 let fail = true in
1390 let sigma = resolve_all_evars depth unique env (initial_select_evars env filter) sigma fail in
1391 Proofview.Unsafe.tclEVARS sigma