Debian Codegraph @

plugins/ssr/ssrcommon.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 (* This file is (C) Copyright 2006-2015 Microsoft Corporation and Inria. *)
12
13 open Util
14 open Names
15 open Evd
16 open Constr
17 open Context
18 open Termops
19 open Printer
20 open Locusops
21
22 open Ltac_plugin
23 open Proofview.Notations
24 open Libnames
25 open Ssrmatching_plugin
26 open Ssrmatching
27 open Ssrast
28 open Ssrprinters
29
30 module RelDecl = Context.Rel.Declaration
31 module NamedDecl = Context.Named.Declaration
32
33 let errorstrm x = CErrors.user_err x
34
35 let allocc = Some(false,[])
36
37 (** Bound assumption argument *)
38
39 (* The Ltac API does have a type for assumptions but it is level-dependent *)
40 (* and therefore impractical to use for complex arguments, so we substitute *)
41 (* our own to have a uniform representation. Also, we refuse to intern *)
42 (* idents that match global/section constants, since this would lead to *)
43 (* fragile Ltac scripts. *)
44
45 let hyp_id (SsrHyp (_, id)) = id
46
47 let hyp_err ?loc msg id =
48 CErrors.user_err ?loc Pp.(str msg ++ Id.print id)
49
50 let not_section_id id = not (Termops.is_section_variable (Global.env ()) id)
51
52 let hyps_ids = List.map hyp_id
53
54 let rec check_hyps_uniq ids = function
55 | SsrHyp (loc, id) :: _ when List.mem id ids ->
56 hyp_err ?loc "Duplicate assumption " id
57 | SsrHyp (_, id) :: hyps -> check_hyps_uniq (id :: ids) hyps
58 | [] -> ()
59
60 let rec pf_check_hyps_uniq ids = function
61 | SsrHyp (loc, id) :: _ when List.mem id ids ->
62 Tacticals.tclZEROMSG ?loc Pp.(str "Duplicate assumption " ++ Id.print id)
63 | SsrHyp (_, id) :: hyps -> pf_check_hyps_uniq (id :: ids) hyps
64 | [] -> Proofview.tclUNIT ()
65
66 let check_hyp_exists hyps (SsrHyp(_, id)) =
67 try ignore(Context.Named.lookup id hyps)
68 with Not_found -> errorstrm Pp.(str"No assumption is named " ++ Id.print id)
69
70 let test_hyp_exists hyps (SsrHyp(_, id)) =
71 try ignore(Context.Named.lookup id hyps); true
72 with Not_found -> false
73
74 let hoik f = function Hyp x -> f x | Id x -> f x
75 let hoi_id = hoik hyp_id
76
77 let mk_hint tac = false, [Some tac]
78 let mk_orhint tacs = true, tacs
79 let nullhint = true, []
80 let nohint = false, []
81
82 open Pp
83
84 let errorstrm x = CErrors.user_err x
85 let anomaly s = CErrors.anomaly (str s)
86
87 (* Tentative patch from util.ml *)
88
89 let array_fold_right_from n f v a =
90 let rec fold n =
91 if n >= Array.length v then a else f v.(n) (fold (succ n))
92 in
93 fold n
94
95 let array_app_tl v l =
96 if Array.length v = 0 then invalid_arg "array_app_tl";
97 array_fold_right_from 1 (fun e l -> e::l) v l
98
99 let array_list_of_tl v =
100 if Array.length v = 0 then invalid_arg "array_list_of_tl";
101 array_fold_right_from 1 (fun e l -> e::l) v []
102
103 (* end patch *)
104
105 let option_assert_get o msg =
106 match o with
107 | None -> CErrors.anomaly msg
108 | Some x -> x
109
110
111 (** Constructors for rawconstr *)
112 open Glob_term
113
114 let mkRHole = DAst.make @@ GHole (GInternalHole)
115
116 let rec mkRHoles n = if n > 0 then mkRHole :: mkRHoles (n - 1) else []
117 let rec isRHoles cl = match cl with
118 | [] -> true
119 | c :: l -> match DAst.get c with GHole _ -> isRHoles l | _ -> false
120 let mkRApp f args = if args = [] then f else DAst.make @@ GApp (f, args)
121 let mkRVar id = DAst.make @@ GRef (GlobRef.VarRef id,None)
122 let mkRltacVar id = DAst.make @@ GVar (id)
123 let mkRCast rc rt = DAst.make @@ GCast (rc, Some DEFAULTcast, rt)
124 let mkRType = DAst.make @@ GSort Glob_ops.glob_Type_sort
125 let mkRProp = DAst.make @@ GSort Glob_ops.glob_Prop_sort
126 let mkRArrow rt1 rt2 = DAst.make @@ GProd (Anonymous, None, Explicit, rt1, rt2)
127 let mkRConstruct c = DAst.make @@ GRef (GlobRef.ConstructRef c,None)
128 let mkRInd mind = DAst.make @@ GRef (GlobRef.IndRef mind,None)
129 let mkRLambda n s t = DAst.make @@ GLambda (n, None, Explicit, s, t)
130
131 let rec mkRnat n =
132 if n <= 0 then DAst.make @@ GRef (Rocqlib.lib_ref "num.nat.O", None) else
133 mkRApp (DAst.make @@ GRef (Rocqlib.lib_ref "num.nat.S", None)) [mkRnat (n - 1)]
134
135 let glob_constr ist genv = function
136 | _, Some ce ->
137 let vars = Id.Map.fold (fun x _ accu -> Id.Set.add x accu) ist.Tacinterp.lfun Id.Set.empty in
138 let ltacvars = {
139 Constrintern.empty_ltac_sign with Constrintern.ltac_vars = vars } in
140 Constrintern.intern_gen Pretyping.WithoutTypeConstraint ~ltacvars genv Evd.(from_env genv) ce
141 | rc, None -> rc
142
143 let intern_term ist env (_, c) = glob_constr ist env c
144
145 (* Estimate a bound on the number of arguments of a raw constr. *)
146 (* This is not perfect, because the unifier may fail to *)
147 (* typecheck the partial application, so we use a minimum of 5. *)
148 (* Also, we don't handle delayed or iterated coercions to *)
149 (* FUNCLASS, which is probably just as well since these can *)
150 (* lead to infinite arities. *)
151
152 let splay_open_constr env (sigma, c) =
153 let t = Retyping.get_type_of env sigma c in
154 Reductionops.whd_decompose_prod env sigma t
155
156 let isAppInd env sigma c =
157 let c = Reductionops.clos_whd_flags RedFlags.all env sigma c in
158 let c, _ = EConstr.decompose_app sigma c in
159 EConstr.isInd sigma c
160
161 (** Generic argument-based globbing/typing utilities *)
162
163 let interp_refine env sigma ist ~concl rc =
164 let constrvars = Tacinterp.extract_ltac_constr_values ist env in
165 let vars = { Glob_ops.empty_lvar with
166 Ltac_pretype.ltac_constrs = constrvars; ltac_genargs = ist.Tacinterp.lfun
167 } in
168 let kind = Pretyping.OfType concl in
169 let flags = Pretyping.{
170 use_coercions = true;
171 use_typeclasses = UseTC;
172 solve_unification_constraints = true;
173 fail_evar = false;
174 expand_evars = true;
175 program_mode = false;
176 poly = PolyFlags.default;
177 undeclared_evars_rr = false;
178 unconstrained_sorts = false;
179 }
180 in
181 let sigma, c = Pretyping.understand_ltac flags env sigma vars kind rc in
182 (* ppdebug(lazy(str"sigma@interp_refine=" ++ pr_evar_map None sigma)); *)
183 debug_ssr (fun () -> str"c@interp_refine=" ++ Printer.pr_econstr_env env sigma c);
184 (sigma, c)
185
186
187 let interp_open_constr env sigma ist gc =
188 let (sigma, (c, _)) = Tacinterp.interp_open_constr_with_bindings ist env sigma (gc, Tactypes.NoBindings) in
189 (sigma, c)
190
191 let interp_term env sigma ist (_, c) = interp_open_constr env sigma ist c
192
193 let interp_hyp ist env sigma (SsrHyp (loc, id)) =
194 let id' = Tacinterp.interp_hyp ist env sigma CAst.(make ?loc id) in
195 if not_section_id id' then SsrHyp (loc, id') else
196 hyp_err ?loc "Can't clear section hypothesis " id'
197
198 let interp_hyps ist env sigma ghyps =
199 let hyps = List.map (interp_hyp ist env sigma) ghyps in
200 check_hyps_uniq [] hyps; hyps
201
202 (* Old terms *)
203 let mk_term k c = k, (mkRHole, Some c)
204 let mk_lterm c = mk_term NoFlag c
205
206 (* New terms *)
207
208 let mk_ast_closure_term a t = {
209 annotation = a;
210 body = t;
211 interp_env = None;
212 glob_env = None;
213 }
214
215 let glob_ast_closure_term (ist : Genintern.glob_sign) t =
216 let ist = {
217 ast_ltacvars = ist.Genintern.ltacvars;
218 ast_intern_sign = ist.Genintern.intern_sign;
219 ast_extra = ist.Genintern.extra;
220 } in
221 { t with glob_env = Some ist }
222 let subst_ast_closure_term (_s : Mod_subst.substitution) t =
223 (* _s makes sense only for glob constr *)
224 t
225 let interp_ast_closure_term (ist : Geninterp.interp_sign) env sigma t =
226 (* sigma is only useful if we want to interp *now*, later we have
227 * a potentially different gl.sigma *)
228 { t with interp_env = Some ist }
229
230 let ssrterm_of_ast_closure_term { body; annotation } =
231 let c = match annotation with
232 | `Parens -> InParens
233 | `At -> WithAt
234 | _ -> NoFlag in
235 mk_term c body
236
237 let ssrdgens_of_parsed_dgens = function
238 | [], clr -> { dgens = []; gens = []; clr }
239 | [gens], clr -> { dgens = []; gens; clr }
240 | [dgens;gens], clr -> { dgens; gens; clr }
241 | _ -> assert false
242
243
244 let nbargs_open_constr env oc =
245 let pl, _ = splay_open_constr env oc in List.length pl
246
247 let pf_nbargs env sigma c = nbargs_open_constr env (sigma, c)
248
249 let internal_names = ref []
250 let add_internal_name pt = internal_names := pt :: !internal_names
251 let is_internal_name s = List.exists (fun p -> p s) !internal_names
252
253 let mk_internal_id s =
254 let s' = Printf.sprintf "_%s_" s in
255 let s' = String.map (fun c -> if c = ' ' then '_' else c) s' in
256 add_internal_name ((=) s'); Id.of_string s'
257
258 let same_prefix s t n =
259 let rec loop i = i = n || s.[i] = t.[i] && loop (i + 1) in loop 0
260
261 let skip_digits s =
262 let n = String.length s in
263 let rec loop i = if i < n && is_digit s.[i] then loop (i + 1) else i in loop
264
265 let mk_tagged_id t i = Id.of_string (Printf.sprintf "%s%d_" t i)
266 let is_tagged t s =
267 let n = String.length s - 1 and m = String.length t in
268 m < n && s.[n] = '_' && same_prefix s t m && skip_digits s m = n
269
270 let evar_tag = "_evar_"
271 let _ = add_internal_name (is_tagged evar_tag)
272 let mk_evar_name n = Name (mk_tagged_id evar_tag n)
273
274 let ssr_anon_hyp = "Hyp"
275
276 let wildcard_tag = "_the_"
277 let wildcard_post = "_wildcard_"
278 let has_wildcard_tag s =
279 let n = String.length s in let m = String.length wildcard_tag in
280 let m' = String.length wildcard_post in
281 n < m + m' + 2 && same_prefix s wildcard_tag m &&
282 String.sub s (n - m') m' = wildcard_post &&
283 skip_digits s m = n - m' - 2
284 let _ = add_internal_name has_wildcard_tag
285
286 let discharged_tag = "_discharged_"
287 let mk_discharged_id id =
288 Id.of_string (Printf.sprintf "%s%s_" discharged_tag (Id.to_string id))
289 let has_discharged_tag s =
290 let m = String.length discharged_tag and n = String.length s - 1 in
291 m < n && s.[n] = '_' && same_prefix s discharged_tag m
292 let _ = add_internal_name has_discharged_tag
293 let is_discharged_id id = has_discharged_tag (Id.to_string id)
294
295 let max_suffix m (t, j0 as tj0) id =
296 let s = Id.to_string id in let n = String.length s - 1 in
297 let dn = String.length t - 1 - n in let i0 = j0 - dn in
298 if not (i0 >= m && s.[n] = '_' && same_prefix s t m) then tj0 else
299 let rec loop i =
300 if i < i0 && s.[i] = '0' then loop (i + 1) else
301 if (if i < i0 then skip_digits s i = n else le_s_t i) then s, i else tj0
302 and le_s_t i =
303 let ds = s.[i] and dt = t.[i + dn] in
304 if ds = dt then i = n || le_s_t (i + 1) else
305 dt < ds && skip_digits s i = n in
306 loop m
307
308 (** creates a fresh (w.r.t. `gl_ids` and internal names) inaccessible name of the form _tXX_ *)
309 let mk_anon_id t gl_ids =
310 let gl_ids = List.map NamedDecl.get_id (EConstr.named_context_of_val gl_ids) in
311 let m, si0, id0 =
312 let s = ref (Printf.sprintf "_%s_" t) in
313 if is_internal_name !s then s := "_" ^ !s;
314 let n = String.length !s - 1 in
315 let rec loop i j =
316 let d = !s.[i] in if not (is_digit d) then i + 1, j else
317 loop (i - 1) (if d = '0' then j else i) in
318 let m, j = loop (n - 1) n in m, (!s, j), Id.of_string_soft !s in
319 if not (List.mem id0 gl_ids) then id0 else
320 let s, i = List.fold_left (max_suffix m) si0 gl_ids in
321 let open Bytes in
322 let s = of_string s in
323 let n = length s - 1 in
324 let rec loop i =
325 if get s i = '9' then (set s i '0'; loop (i - 1)) else
326 if i < m then (set s n '0'; set s m '1'; cat s (of_string "_")) else
327 (set s i (Char.chr (Char.code (get s i) + 1)); s) in
328 Id.of_string_soft (Bytes.to_string (loop (n - 1)))
329
330 let convert_concl_no_check t = Tactics.convert_concl ~cast:false ~check:false t DEFAULTcast
331 let convert_concl ~check t = Tactics.convert_concl ~cast:false ~check t DEFAULTcast
332
333 (* Reduction that preserves the Prod/Let spine of the "in" tactical. *)
334
335 let inc_safe n = if n = 0 then n else n + 1
336 let rec safe_depth s c = match EConstr.kind s c with
337 | LetIn ({binder_name=Name x}, _, _, c') when is_discharged_id x -> safe_depth s c' + 1
338 | LetIn (_, _, _, c') | Prod (_, _, c') -> inc_safe (safe_depth s c')
339 | _ -> 0
340
341 let red_safe (r : Reductionops.reduction_function) e s c0 =
342 let rec red_to e c n = match EConstr.kind s c with
343 | Prod (x, t, c') when n > 0 ->
344 let t' = r e s t in let e' = EConstr.push_rel (RelDecl.LocalAssum (x, t')) e in
345 EConstr.mkProd (x, t', red_to e' c' (n - 1))
346 | LetIn (x, b, t, c') when n > 0 ->
347 let t' = r e s t in let e' = EConstr.push_rel (RelDecl.LocalAssum (x, t')) e in
348 EConstr.mkLetIn (x, r e s b, t', red_to e' c' (n - 1))
349 | _ -> r e s c in
350 red_to e c0 (safe_depth s c0)
351
352 let is_id_constr sigma c = match EConstr.kind sigma c with
353 | Lambda(_,_,c) when EConstr.isRel sigma c -> 1 = EConstr.destRel sigma c
354 | _ -> false
355
356 let red_product_skip_id env sigma c = match EConstr.kind sigma c with
357 | App(hd,args) when Array.length args = 1 && is_id_constr sigma hd -> args.(0)
358 | _ -> match Tacred.red_product env sigma c with Some c -> c | None -> c
359
360 let ssrevaltac ist gtac = Tacinterp.tactic_of_value ist gtac
361
362 (** Open term to lambda-term coercion *)(* {{{ ************************************)
363
364 (* This operation takes a goal gl and an open term (sigma, t), and *)
365 (* returns a term t' where all the new evars in sigma are abstracted *)
366 (* with the mkAbs argument, i.e., for mkAbs = mkLambda then there is *)
367 (* some duplicate-free array args of evars of sigma such that the *)
368 (* term mkApp (t', args) is convertible to t. *)
369 (* This makes a useful shorthand for local definitions in proofs, *)
370 (* i.e., pose succ := _ + 1 means pose succ := fun n : nat => n + 1, *)
371 (* and, in context of the 4CT library, pose mid := maps id means *)
372 (* pose mid := fun d : detaSet => @maps d d (@id (datum d)) *)
373 (* Note that this facility does not extend to set, which tries *)
374 (* instead to fill holes by matching a goal subterm. *)
375 (* The argument to "have" et al. uses product abstraction, e.g. *)
376 (* have Hmid: forall s, (maps id s) = s. *)
377 (* stands for *)
378 (* have Hmid: forall (d : dataSet) (s : seq d), (maps id s) = s. *)
379 (* We also use this feature for rewrite rules, so that, e.g., *)
380 (* rewrite: (plus_assoc _ 3). *)
381 (* will execute as *)
382 (* rewrite (fun n => plus_assoc n 3) *)
383 (* i.e., it will rewrite some subterm .. + (3 + ..) to .. + 3 + ... *)
384 (* The convention is also used for the argument of the congr tactic, *)
385 (* e.g., congr (x + _ * 1). *)
386
387 (* Replace new evars with lambda variables, retaining local dependencies *)
388 (* but stripping global ones. We use the variable names to encode the *)
389 (* the number of dependencies, so that the transformation is reversible. *)
390
391 let env_size env = List.length (Environ.named_context env)
392
393 let resolve_typeclasses env sigma ~where ~fail =
394 let filter =
395 let evset = Evarutil.undefined_evars_of_term sigma where in
396 fun k _ -> Evar.Set.mem k evset in
397 Typeclasses.resolve_typeclasses ~filter ~fail env sigma
398
399 let abs_evars env sigma0 ?(rigid = []) (sigma, c0) =
400 let c0 = Evarutil.nf_evar sigma c0 in
401 let sigma0, ucst = sigma0, Evd.ustate sigma in
402 let nenv = env_size env in
403 let abs_evar n k =
404 let open EConstr in
405 let evi = Evd.find_undefined sigma k in
406 let concl = Evd.evar_concl evi in
407 let dc = CList.firstn n (evar_filtered_context evi) in
408 let abs_dc c = function
409 | NamedDecl.LocalDef (x,b,t) -> mkNamedLetIn sigma x b t (mkArrow t x.binder_relevance c)
410 | NamedDecl.LocalAssum (x,t) -> mkNamedProd sigma x t c in
411 let t = Context.Named.fold_inside abs_dc ~init:concl dc in
412 Evarutil.nf_evar sigma t in
413 let rec put evlist c = match EConstr.kind sigma c with
414 | Evar (k, a) ->
415 if List.mem_assoc k evlist || Evd.mem sigma0 k || List.mem k rigid then evlist else
416 let n = max 0 (SList.length a - nenv) in
417 let t = abs_evar n k in (k, (n, t)) :: put evlist t
418 | _ -> EConstr.fold sigma put evlist c in
419 let evlist = put [] c0 in
420 if List.is_empty evlist then
421 c0, [], ucst
422 else
423 let open EConstr in
424 let rec lookup k i = function
425 | [] -> 0, 0
426 | (k', (n, _)) :: evl -> if k = k' then i, n else lookup k (i + 1) evl in
427 let rec get i c = match EConstr.kind sigma c with
428 | Evar (ev, a) ->
429 let j, n = lookup ev i evlist in
430 if j = 0 then EConstr.map sigma (get i) c else if n = 0 then mkRel j else
431 let a = Array.of_list @@ Evd.expand_existential sigma (ev, a) in
432 mkApp (mkRel j, Array.init n (fun k -> get i a.(n - 1 - k)))
433 | _ -> EConstr.map_with_binders sigma ((+) 1) get i c in
434 let rec loop c i = function
435 | (_, (n, t)) :: evl ->
436 loop (mkLambda (make_annot (mk_evar_name n) ERelevance.relevant, get (i - 1) t, c)) (i - 1) evl
437 | [] -> c in
438 loop (get 1 c0) 1 evlist, List.map fst evlist, ucst
439
440 (* As before but if (?i : T(?j)) and (?j : P : Prop), then the lambda for i
441 * looks like (fun evar_i : (forall pi : P. T(pi))) thanks to "loopP" and all
442 * occurrences of evar_i are replaced by (evar_i evar_j) thanks to "app".
443 *
444 * If P can be solved by ssrautoprop (that defaults to trivial), then
445 * the corresponding lambda looks like (fun evar_i : T(c)) where c is
446 * the solution found by ssrautoprop.
447 *)
448 let ssrautoprop_tac = ref (Proofview.Goal.enter (fun gl -> assert false))
449
450 (* Thanks to Arnaud Spiwack for this snippet *)
451 let call_on_evar env sigma tac e =
452 try
453 let tac = Proofview.Unsafe.tclSETGOALS [Proofview.with_empty_state e] <*> tac in
454 let _, init = Proofview.init sigma [] in
455 let name = Names.Id.of_string "legacy_pe" in
456 let (_, final, _, _, _) = Proofview.apply ~name ~poly:PolyFlags.default env tac init in
457 let (gs, final) = Proofview.proofview final in
458 let () = if (gs <> []) then errorstrm (str "Should we tell the user?") in
459 final
460 with Logic_monad.TacticFailure e as src ->
461 let (_, info) = Exninfo.capture src in
462 Exninfo.iraise (e, info)
463
464 open Pp
465 module Intset = Evar.Set
466
467 let abs_evars_pirrel env sigma0 (sigma, c0) =
468 let c0 = Evarutil.nf_evar sigma c0 in
469 let nenv = env_size env in
470 let abs_evar n k =
471 let open EConstr in
472 let evi = Evd.find_undefined sigma k in
473 let concl = Evd.evar_concl evi in
474 let dc = CList.firstn n (evar_filtered_context evi) in
475 let abs_dc c = function
476 | NamedDecl.LocalDef (x,b,t) -> mkNamedLetIn sigma x b t (mkArrow t x.binder_relevance c)
477 | NamedDecl.LocalAssum (x,t) -> mkNamedProd sigma x t c in
478 let t = Context.Named.fold_inside abs_dc ~init:concl dc in
479 Evarutil.nf_evar sigma t
480 in
481 let rec put evlist c = match EConstr.kind sigma c with
482 | Evar (k, a) ->
483 if List.mem_assoc k evlist || Evd.mem sigma0 k then evlist else
484 let n = max 0 (SList.length a - nenv) in
485 let evi = Evd.find_undefined sigma k in
486 (* FIXME? this is not the right environment in general *)
487 let k_ty = Retyping.get_sort_quality_of env sigma (Evd.evar_concl evi) in
488 let is_prop = UnivGen.QualityOrSet.is_prop k_ty in
489 let t = abs_evar n k in
490 (k, (n, t, is_prop, Evd.evar_relevance evi)) :: put evlist t
491 | _ -> EConstr.fold sigma put evlist c in
492 let evlist = put [] c0 in
493 if evlist = [] then 0, c0 else
494 let evplist =
495 let depev = List.fold_left (fun evs (_,(_,t,_,_)) ->
496 Intset.union evs (Evarutil.undefined_evars_of_term sigma t)) Intset.empty evlist in
497 List.filter (fun (i,(_,_,b,_)) -> b && Intset.mem i depev) evlist in
498 let evlist, evplist, sigma =
499 if evplist = [] then evlist, [], sigma else
500 List.fold_left (fun (ev, evp, sigma) (i, (_,t,_,_) as p) ->
501 try
502 let sigma = call_on_evar env sigma !ssrautoprop_tac i in
503 List.filter (fun (j,_) -> j <> i) ev, evp, sigma
504 with e when CErrors.noncritical e -> ev, p::evp, sigma) (evlist, [], sigma) (List.rev evplist) in
505 let c0 = Evarutil.nf_evar sigma c0 in
506 let nf (k, (n, t, p, r)) = (k, (n, Evarutil.nf_evar sigma t, p, r)) in
507 let evlist = List.map nf evlist in
508 let evplist = List.map nf evplist in
509 let rec lookup k i = function
510 | [] -> 0, 0
511 | (k', (n,_,_,_)) :: evl -> if k = k' then i,n else lookup k (i + 1) evl in
512 let open EConstr in
513 let rec get evlist i c = match EConstr.kind sigma c with
514 | Evar (ev, a) ->
515 let j, n = lookup ev i evlist in
516 if j = 0 then EConstr.map sigma (get evlist i) c else if n = 0 then mkRel j else
517 let a = Array.of_list @@ Evd.expand_existential sigma (ev, a) in
518 mkApp (mkRel j, Array.init n (fun k -> get evlist i a.(n - 1 - k)))
519 | _ -> EConstr.map_with_binders sigma ((+) 1) (get evlist) i c in
520 let rec app extra_args i c = match decompose_app_list sigma c with
521 | hd, args when isRel sigma hd && destRel sigma hd = i ->
522 let j = destRel sigma hd in
523 mkApp (mkRel j, Array.of_list (List.map (Vars.lift (i-1)) extra_args @ args))
524 | _ -> EConstr.map_with_binders sigma ((+) 1) (app extra_args) i c in
525 let rec loopP evlist accu i = function
526 | [] -> List.rev accu
527 | (_, (n, t, _, r)) :: evl ->
528 let t = get evlist (i - 1) t in
529 let n = Name (Id.of_string (ssr_anon_hyp ^ string_of_int n)) in
530 loopP evlist (RelDecl.LocalAssum (make_annot n r, t) :: accu) (i - 1) evl
531 in
532 let rec loop c i = function
533 | (_, (n, t, _, r)) :: evl ->
534 let evs = Evarutil.undefined_evars_of_term sigma t in
535 let t_evplist = List.filter (fun (k,_) -> Intset.mem k evs) evplist in
536 let ctx_t = loopP t_evplist [] 1 t_evplist in
537 let t = EConstr.it_mkProd_or_LetIn (get t_evplist 1 t) ctx_t in
538 let t = get evlist (i - 1) t in
539 let extra_args = List.rev_map (fun (k,_) -> mkRel (fst (lookup k i evlist))) t_evplist in
540 let c = if extra_args = [] then c else app extra_args 1 c in
541 loop (mkLambda (make_annot (mk_evar_name n) r, t, c)) (i - 1) evl
542 | [] -> c in
543 let res = loop (get evlist 1 c0) 1 evlist in
544 List.length evlist, res
545
546 (* Strip all non-essential dependencies from an abstracted term, generating *)
547 (* standard names for the abstracted holes. *)
548
549 let nb_evar_deps = function
550 | Name id ->
551 let s = Id.to_string id in
552 if not (is_tagged evar_tag s) then 0 else
553 let m = String.length evar_tag in
554 (try int_of_string (String.sub s m (String.length s - 1 - m)) with e when CErrors.noncritical e -> 0)
555 | _ -> 0
556
557 let type_id env sigma t = Id.of_string (Namegen.hdchar env sigma t)
558 let pfe_type_relevance_of env sigma t =
559 let sigma, ty = Typing.type_of env sigma t in
560 sigma, ty, Retyping.relevance_of_term env sigma t
561
562 let abs_cterm env sigma n c0 =
563 let open EConstr in
564 if n <= 0 then c0 else
565 let noargs = [|0|] in
566 let eva = Array.make n noargs in
567 let rec strip i c = match EConstr.kind sigma c with
568 | App (f, a) when isRel sigma f ->
569 let j = i - destRel sigma f in
570 if j >= n || eva.(j) = noargs then mkApp (f, Array.map (strip i) a) else
571 let dp = eva.(j) in
572 let nd = Array.length dp - 1 in
573 let mkarg k = strip i a.(if k < nd then dp.(k + 1) - j else k + dp.(0)) in
574 mkApp (f, Array.init (Array.length a - dp.(0)) mkarg)
575 | _ -> EConstr.map_with_binders sigma ((+) 1) strip i c in
576 let rec strip_ndeps j i c = match EConstr.kind sigma c with
577 | Prod (x, t, c1) when i < j ->
578 let dl, c2 = strip_ndeps j (i + 1) c1 in
579 if Vars.noccurn sigma 1 c2 then dl, Vars.lift (-1) c2 else
580 i :: dl, mkProd (x, strip i t, c2)
581 | LetIn (x, b, t, c1) when i < j ->
582 let _, _, c1' = destProd sigma c1 in
583 let dl, c2 = strip_ndeps j (i + 1) c1' in
584 if Vars.noccurn sigma 1 c2 then dl, Vars.lift (-1) c2 else
585 i :: dl, mkLetIn (x, strip i b, strip i t, c2)
586 | _ -> [], strip i c in
587 let rec strip_evars i c = match EConstr.kind sigma c with
588 | Lambda (x, t1, c1) when i < n ->
589 let na = nb_evar_deps x.binder_name in
590 let dl, t2 = strip_ndeps (i + na) i t1 in
591 let na' = List.length dl in
592 eva.(i) <- Array.of_list (na - na' :: dl);
593 let x' =
594 if na' = 0 then Name (type_id env sigma t2) else mk_evar_name na' in
595 mkLambda ({x with binder_name=x'}, t2, strip_evars (i + 1) c1)
596 (* if noccurn 1 c2 then lift (-1) c2 else
597 mkLambda (Name (pf_type_id gl t2), t2, c2) *)
598 | _ -> strip i c in
599 strip_evars 0 c0
600
601 (* }}} *)
602
603 let rec constr_name sigma c = match EConstr.kind sigma c with
604 | Var id -> Name id
605 | Cast (c', _, _) -> constr_name sigma c'
606 | Const (cn,_) -> Name (Constant.label cn)
607 | App (c', _) -> constr_name sigma c'
608 | _ -> Anonymous
609
610 let pf_mkprod env sigma c ?(name=constr_name sigma c) cl =
611 let sigma, t, r = pfe_type_relevance_of env sigma c in
612 if name <> Anonymous || EConstr.Vars.noccurn sigma 1 cl then
613 sigma, EConstr.mkProd (make_annot name r, t, cl)
614 else
615 sigma, EConstr.mkProd (make_annot (Name (type_id env sigma t)) r, t, cl)
616
617 (** look up a name in the ssreflect internals module *)
618 let ssrdirpath = DirPath.make [Id.of_string "ssreflect"]
619 let ssrqid name = Libnames.make_qualid ssrdirpath (Id.of_string name)
620 let mkSsrRef name =
621 let qn = Format.sprintf "plugins.ssreflect.%s" name in
622 if Rocqlib.has_ref qn then Rocqlib.lib_ref qn else
623 CErrors.user_err Pp.(str "Small scale reflection library not loaded (" ++ str name ++ str ")")
624 let mkSsrRRef name = (DAst.make @@ GRef (mkSsrRef name,None)), None
625 let mkSsrConst env sigma name =
626 EConstr.fresh_global env sigma (mkSsrRef name)
627
628 let mkProt env sigma t c =
629 let sigma, prot = mkSsrConst env sigma "protect_term" in
630 sigma, EConstr.mkApp (prot, [|t; c|])
631
632 let mkEtaApp c n imin =
633 let open EConstr in
634 if n = 0 then c else
635 let nargs, mkarg =
636 if n < 0 then -n, (fun i -> mkRel (imin + i)) else
637 let imax = imin + n - 1 in n, (fun i -> mkRel (imax - i)) in
638 mkApp (c, Array.init nargs mkarg)
639
640 let mkRefl env sigma t c =
641 let (sigma, refl) = EConstr.fresh_global env sigma Rocqlib.(lib_ref "core.eq.refl") in
642 sigma, EConstr.mkApp (refl, [|t; c|])
643
644 let discharge_hyp (id', (id, mode)) =
645 let open EConstr in
646 Proofview.Goal.enter begin fun gl ->
647 let sigma = Proofview.Goal.sigma gl in
648 let concl = Proofview.Goal.concl gl in
649 let cl' = Vars.subst_var sigma id concl in
650 let decl = Tacmach.pf_get_hyp id gl in
651 match decl, mode with
652 | NamedDecl.LocalAssum _, _ | NamedDecl.LocalDef _, "(" ->
653 let id' = {(NamedDecl.get_annot decl) with binder_name = Name id'} in
654 Tactics.apply_type ~typecheck:true
655 (mkProd (id', NamedDecl.get_type decl, cl')) [mkVar id]
656 | NamedDecl.LocalDef (_, v, t), _ ->
657 let id' = {(NamedDecl.get_annot decl) with binder_name = Name id'} in
658 convert_concl ~check:true (mkLetIn (id', v, t, cl'))
659 end
660
661 let view_error s gv =
662 Tacticals.tclZEROMSG (str ("Cannot " ^ s ^ " view ") ++ pr_term gv)
663
664
665 open Locus
666 (****************************** tactics ***********************************)
667
668 let rewritetac ?(under=false) dir c =
669 (* Due to the new optional arg ?tac, application shouldn't be too partial *)
670 let open Proofview.Notations in
671 Proofview.Goal.enter begin fun _ ->
672 Equality.general_rewrite ~where:None ~l2r:(dir = L2R) AllOccurrences ~freeze:true ~dep:false ~with_evars:false (c, Tactypes.NoBindings) <*>
673 if under then Proofview.cycle 1 else Proofview.tclUNIT ()
674 end
675
676 (**********************`:********* hooks ************************************)
677
678 type name_hint = (int * EConstr.types array) option ref
679
680 let abs_ssrterm ?(resolve_typeclasses=false) ist env sigma t =
681 let sigma0 = sigma in
682 let sigma, ct = interp_term env sigma ist t in
683 let t =
684 if not resolve_typeclasses then (sigma, ct)
685 else
686 let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in
687 sigma, Evarutil.nf_evar sigma ct in
688 let c, abstracted_away, ucst = abs_evars env sigma0 t in
689 let n = List.length abstracted_away in
690 let sigma = Evd.merge_universe_context sigma0 ucst in
691 let t = abs_cterm env sigma n c in
692 sigma, t, n
693
694 let top_id = mk_internal_id "top assumption"
695
696 let ssr_n_tac seed n =
697 Proofview.Goal.enter begin fun gl ->
698 let name = if n = -1 then seed else ("ssr" ^ seed ^ string_of_int n) in
699 let fail msg = CErrors.user_err (Pp.str msg) in
700 let tacname =
701 try Tacenv.locate_tactic (Libnames.qualid_of_ident (Id.of_string name))
702 with Not_found -> try Tacenv.locate_tactic (ssrqid name)
703 with Not_found ->
704 if n = -1 then fail "The ssreflect library was not loaded"
705 else fail ("The tactic "^name^" was not found") in
706 let tacexpr = Tacexpr.Reference (ArgArg (Loc.tag @@ tacname)) in
707 Tacinterp.eval_tactic @@ CAst.make (Tacexpr.TacArg tacexpr)
708 end
709
710 let donetac n = ssr_n_tac "done" n
711
712 open Constrexpr
713 open Util
714
715 (** Constructors for constr_expr *)
716 let mkCProp loc = CAst.make ?loc @@ CSort Constrexpr_ops.expr_Prop_sort
717 let mkCType loc = CAst.make ?loc @@ CSort Constrexpr_ops.expr_Type_sort
718 let mkCVar ?loc id = CAst.make ?loc @@ CRef (qualid_of_ident ?loc id, None)
719 let rec mkCHoles ?loc n =
720 if n <= 0 then [] else (CAst.make ?loc @@ CHole (None)) :: mkCHoles ?loc (n - 1)
721 let mkCHole loc = CAst.make ?loc @@ CHole (None)
722 let mkCLambda ?loc name ty t = CAst.make ?loc @@
723 CLambdaN ([CLocalAssum([CAst.make ?loc name], None, Default Explicit, ty)], t)
724 let mkCArrow ?loc ty t = CAst.make ?loc @@
725 CProdN ([CLocalAssum([CAst.make Anonymous], None, Default Explicit, ty)], t)
726 let mkCCast ?loc t ty = CAst.make ?loc @@ CCast (t, Some DEFAULTcast, ty)
727
728 let rec isCHoles = function { CAst.v = CHole _ } :: cl -> isCHoles cl | cl -> cl = []
729 let rec isCxHoles = function ({ CAst.v = CHole _ }, None) :: ch -> isCxHoles ch | _ -> false
730
731 let pf_interp_ty ?(resolve_typeclasses=false) env sigma0 ist ty =
732 let n_binders = ref 0 in
733 let ty = match ty with
734 | a, (t, None) ->
735 let rec force_type ty = DAst.(map (function
736 | GProd (x, r, k, s, t) -> incr n_binders; GProd (x, r, k, s, force_type t)
737 | GLetIn (x, r, v, oty, t) -> incr n_binders; GLetIn (x, r, v, oty, force_type t)
738 | _ -> DAst.get (mkRCast ty mkRType))) ty in
739 a, (force_type t, None)
740 | _, (_, Some ty) ->
741 let rec force_type ty = CAst.(map (function
742 | CProdN (abs, t) ->
743 n_binders := !n_binders + List.length (List.flatten (List.map (function CLocalAssum (nal,_,_,_) -> nal | CLocalDef (na,_,_,_) -> [na] | CLocalPattern _ -> (* We count a 'pat for 1; TO BE CHECKED *) [CAst.make Name.Anonymous]) abs));
744 CProdN (abs, force_type t)
745 | CLetIn (n, v, oty, t) -> incr n_binders; CLetIn (n, v, oty, force_type t)
746 | _ -> (mkCCast ty (mkCType None)).v)) ty in
747 mk_term NoFlag (force_type ty) in
748 let strip_cast (sigma, t) =
749 let open EConstr in
750 let rec aux t = match kind_of_type sigma t with
751 | CastType (t, ty) when !n_binders = 0 && isSort sigma ty -> t
752 | ProdType(n,s,t) -> decr n_binders; mkProd (n, s, aux t)
753 | LetInType(n,v,ty,t) -> decr n_binders; mkLetIn (n, v, ty, aux t)
754 | _ -> anomaly "pf_interp_ty: ssr Type cast deleted by typecheck" in
755 sigma, aux t in
756 let sigma, cty as ty = strip_cast (interp_term env sigma0 ist ty) in
757 let ty =
758 if not resolve_typeclasses then ty
759 else
760 let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in
761 sigma, Evarutil.nf_evar sigma cty in
762 let c, evs, ucst = abs_evars env sigma0 ty in
763 let n = List.length evs in
764 let sigma0 = Evd.merge_universe_context sigma0 ucst in
765 let lam_c = abs_cterm env sigma0 n c in
766 let ctx, c = EConstr.decompose_lambda_n_assum sigma n lam_c in
767 sigma0, n, EConstr.it_mkProd_or_LetIn c ctx, lam_c
768
769 (* TASSI: given (c : ty), generates (c ??? : ty[???/...]) with m evars *)
770 exception NotEnoughProducts
771 let saturate ?(beta=false) ?(bi_types=false) env sigma c ?ty m =
772 let sigma, ty = match ty with
773 | Some ty -> sigma, ty
774 | None ->
775 if Termops.is_template_polymorphic_ref env sigma c then
776 begin match EConstr.kind sigma c with
777 | Ind (ind,_) ->
778 let sigma, univs = Typing.get_template_parameters env sigma ind ~refresh_all:true [||] in
779 let specif = Inductive.lookup_mind_specif env ind in
780 let typ, csts = Inductive.type_of_inductive_knowing_parameters
781 (specif,UVars.Instance.empty)
782 univs
783 in
784 let sigma = Evd.add_poly_constraints ~src:UState.Internal sigma csts in
785 sigma, EConstr.of_constr typ
786 | Construct ((ind,_ as ctor),_) ->
787 let sigma, univs = Typing.get_template_parameters env sigma ind ~refresh_all:true [||] in
788 let specif = Inductive.lookup_mind_specif env ind in
789 let typ, csts = Inductive.type_of_constructor_knowing_parameters
790 (ctor,UVars.Instance.empty)
791 specif
792 univs
793 in
794 let sigma = Evd.add_poly_constraints ~src:UState.Internal sigma csts in
795 sigma, EConstr.of_constr typ
796 | _ -> assert false
797 end
798 else sigma, Retyping.get_type_of env sigma c
799 in
800 let rec loop ty args sigma n =
801 let open EConstr in
802 if n = 0 then
803 let args = List.rev args in
804 (if beta then Reductionops.whd_beta env sigma else fun x -> x)
805 (EConstr.mkApp (c, Array.of_list (List.map pi2 args))), ty, args, sigma
806 else match kind_of_type sigma ty with
807 | ProdType (_, src, tgt) ->
808 let sigma = create_evar_defs sigma in
809 let argty = if bi_types then Reductionops.nf_betaiota env sigma src else src in
810 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma argty in
811 let (sigma, x) = Evarutil.new_evar ~typeclass_candidate env sigma argty in
812 loop (EConstr.Vars.subst1 x tgt) ((m - n,x,argty) :: args) sigma (n-1)
813 | CastType (t, _) -> loop t args sigma n
814 | LetInType (_, v, _, t) -> loop (EConstr.Vars.subst1 v t) args sigma n
815 | SortType _ -> raise NotEnoughProducts
816 | AtomicType _ ->
817 let ty = (* FIXME *)
818 (Reductionops.whd_all env sigma) ty in
819 match kind_of_type sigma ty with
820 | ProdType _ -> loop ty args sigma n
821 | _ -> raise NotEnoughProducts
822 in
823 loop ty [] sigma m
824
825 let dependent_apply_error =
826 CErrors.UserError (Pp.str "Could not fill dependent hole in \"apply\"")
827
828 (* TASSI: Sometimes Rocq's apply fails. According to my experience it may be
829 * related to goals that are products and with beta redexes. In that case it
830 * guesses the wrong number of implicit arguments for your lemma. What follows
831 * is just like apply, but with a user-provided number n of implicits.
832 *
833 * Refine.refine function that handles type classes and evars but fails to
834 * handle "dependently typed higher order evars".
835 *
836 * Assumes that the type of [t] is a telescope with [n] leading product types.
837 * This is always the case as the only caller of applyn uses it with the output
838 * of abs_evars_pirrel which starts with n lambdas generated by abstraction.
839 * It also assumes [t] starts with [n] Lambda nodes.
840 *
841 * Refiner.refiner that does not handle metas with a non ground type but works
842 * with dependently typed higher order metas. *)
843 let applyn ?(beta=false) ~with_evars ?(first_goes_last=false) n t =
844 Proofview.Goal.enter begin fun gl ->
845 let sigma = Proofview.Goal.sigma gl in
846 let env = Proofview.Goal.env gl in
847 let concl = Proofview.Goal.concl gl in
848 if with_evars then
849 let refine =
850 Refine.refine ~typecheck:false begin fun sigma ->
851 let rec saturate c args sigma n =
852 if n = 0 then args, sigma
853 else match EConstr.kind sigma c with
854 | Lambda (_, argty, c) ->
855 let argty = Reductionops.nf_betaiota env sigma (EConstr.Vars.substl args argty) in
856 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma argty in
857 let (sigma, x) = Evarutil.new_evar ~typeclass_candidate env sigma argty in
858 saturate c (x :: args) sigma (n-1)
859 | _ -> assert false
860 in
861 let _, ty = EConstr.decompose_prod_n_decls sigma n (Retyping.get_type_of env sigma t) in
862 let args, sigma = saturate t [] sigma n in
863 let ty = EConstr.Vars.substl args ty in
864 let args = Array.rev_of_list args in
865 let t = EConstr.mkApp (t, args) in
866 let t = if beta then Reductionops.whd_beta env sigma t else t in
867 let sigma = unify_HO env sigma ty concl in
868 (* Set our own set of goals. In theory saturate generates them in the
869 right order, so we could just return sigma directly, but explicit is
870 better than implicit. *)
871 let sigma = Evd.push_future_goals (snd @@ Evd.pop_future_goals sigma) in
872 let fold sigma e = match EConstr.kind sigma e with
873 | Evar (evk, _) -> Evd.declare_future_goal evk sigma
874 | _ -> sigma
875 in
876 let sigma = Array.fold_left fold sigma args in
877 (sigma, t)
878 end
879 in
880 Tacticals.tclTHENLIST [
881 refine;
882 Proofview.shelve_unifiable;
883 Proofview.(if first_goes_last then cycle 1 else tclUNIT ())
884 ]
885 else
886 let sigma = Evd.push_future_goals sigma in
887 let hyps = Environ.named_context_val env in
888 let inst = EConstr.identity_subst_val hyps in
889 let t, args, sigma =
890 let rec loop sigma bo args = function (* saturate with metas *)
891 | 0 -> (t, args, sigma)
892 | n ->
893 match EConstr.kind sigma bo with
894 | Lambda (na, ty, bo) ->
895 let () = if not (EConstr.Vars.closed0 sigma ty) then raise dependent_apply_error in
896 let ty = Reductionops.nf_betaiota env sigma ty in
897 let relevance = na.binder_relevance in
898 let (sigma, evk) = Evarutil.new_pure_evar ~typeclass_candidate:false hyps sigma ~relevance ty in
899 loop sigma bo (evk :: args) (n - 1)
900 | _ -> assert false
901 in
902 loop sigma t [] n
903 in
904 let _, sigma = Evd.pop_future_goals sigma in
905
906 let map evk = Proofview.goal_with_state evk (Proofview.Goal.state gl) in
907 let sgl = List.rev_map map args in
908 let ans = EConstr.applist (t, List.rev_map (fun evk -> EConstr.mkEvar (evk, inst)) args) in
909 let evk = Proofview.Goal.goal gl in
910 let _ =
911 if not (Evarutil.occur_evar_upto sigma evk ans) then ()
912 else Pretype_errors.error_occur_check env sigma evk ans
913 in
914 let sigma = Evd.define evk ans sigma in
915 Tacticals.tclTHENLIST [
916 Proofview.Unsafe.tclEVARS sigma;
917 Proofview.Unsafe.tclSETGOALS sgl;
918 Proofview.(if first_goes_last then cycle 1 else tclUNIT ())
919 ]
920 end
921
922 let refine_with ?(first_goes_last=false) ?beta ?(with_evars=true) oc =
923 let open Proofview.Notations in
924 Proofview.Goal.enter begin fun gl ->
925 let env = Proofview.Goal.env gl in
926 let sigma = Proofview.Goal.sigma gl in
927 let uct = Evd.ustate (fst oc) in
928 let n, oc = abs_evars_pirrel env sigma oc in
929 Proofview.Unsafe.tclEVARS (Evd.set_universe_context sigma uct) <*>
930 Proofview.tclORELSE (applyn ~with_evars ~first_goes_last ?beta n oc)
931 (fun _ -> Proofview.tclZERO dependent_apply_error)
932 end
933
934 (** Basic tactics *)
935
936 let rec fst_prod red tac = Proofview.Goal.enter begin fun gl ->
937 let concl = Proofview.Goal.concl gl in
938 match EConstr.kind (Proofview.Goal.sigma gl) concl with
939 | Prod (id,_,tgt) | LetIn(id,_,_,tgt) -> tac id.binder_name
940 | _ -> if red then Tacticals.tclZEROMSG (str"No product even after head-reduction.")
941 else Tacticals.tclTHEN Tactics.hnf_in_concl (fst_prod true tac)
942 end
943
944 let introid ?(orig=ref Anonymous) name =
945 let open Proofview.Notations in
946 Proofview.Goal.enter begin fun gl ->
947 let env = Proofview.Goal.env gl in
948 let sigma = Proofview.Goal.sigma gl in
949 let g = Proofview.Goal.concl gl in
950 match EConstr.kind sigma g with
951 | App (hd, _) when EConstr.isLambda sigma hd ->
952 convert_concl_no_check (Reductionops.whd_beta env sigma g)
953 | _ -> Tacticals.tclIDTAC
954 end <*>
955 (fst_prod false (fun id -> orig := id; Tactics.intro_mustbe_force name))
956
957 let anontac decl =
958 Proofview.Goal.enter begin fun gl ->
959 let env = Proofview.Goal.env gl in
960 let id = match RelDecl.get_name decl with
961 | Name id ->
962 if is_discharged_id id then id else mk_anon_id (Id.to_string id) (Environ.named_context_val env)
963 | _ -> mk_anon_id ssr_anon_hyp (Environ.named_context_val env) in
964 introid id
965 end
966
967 let rec intro_anon () =
968 let open Proofview.Notations in
969 Proofview.Goal.enter begin fun gl ->
970 let sigma = Proofview.Goal.sigma gl in
971 let concl = Proofview.Goal.concl gl in
972 let d = List.hd (fst (EConstr.decompose_prod_n_decls sigma 1 concl)) in
973 Proofview.tclORELSE (anontac d)
974 (fun (err0, info) -> Proofview.tclORELSE
975 (Tactics.red_in_concl <*> intro_anon ()) (fun _ -> Proofview.tclZERO ~info err0))
976 end
977
978 let intro_anon = intro_anon ()
979
980 let is_pf_var sigma c =
981 EConstr.isVar sigma c && not_section_id (EConstr.destVar sigma c)
982
983 let hyp_of_var sigma v = SsrHyp (Loc.tag @@ EConstr.destVar sigma v)
984
985 let interp_clr sigma = function
986 | Some clr, (k, c)
987 when (k = NoFlag || k = WithAt) && is_pf_var sigma c ->
988 hyp_of_var sigma c :: clr
989 | Some clr, _ -> clr
990 | None, _ -> []
991
992 (** Basic tacticals *)
993
994 (** Multipliers *)(* {{{ ***********************************************************)
995
996 (* tactical *)
997
998 let tclID tac = tac
999
1000 let tclDOTRY n tac =
1001 let open Tacticals in
1002 if n <= 0 then tclIDTAC else
1003 let rec loop i =
1004 if i = n then tclTRY tac else
1005 tclTRY (tclTHEN tac (loop (i + 1))) in
1006 loop 1
1007
1008 let tclDO n tac =
1009 let prefix i = str"At iteration " ++ int i ++ str": " in
1010 let tac_err_at i =
1011 Proofview.Goal.enter begin fun gl ->
1012 Proofview.tclORELSE tac begin function
1013 | (CErrors.UserError s, info) ->
1014 let e' = CErrors.UserError (prefix i ++ s) in
1015 Proofview.tclZERO ~info e'
1016 | (e, info) -> Proofview.tclZERO ~info e
1017 end
1018 end
1019 in
1020 let rec loop i =
1021 Proofview.Goal.enter begin fun gl ->
1022 if i = n then tac_err_at i else
1023 Tacticals.tclTHEN (tac_err_at i) (loop (i + 1))
1024 end in
1025 loop 1
1026
1027 let tclAT_LEAST_ONCE t =
1028 let open Tacticals in
1029 tclTHEN t (tclREPEAT t)
1030
1031 let tclMULT = function
1032 | 0, May -> Tacticals.tclREPEAT
1033 | 1, May -> Tacticals.tclTRY
1034 | n, May -> tclDOTRY n
1035 | 0, Must -> tclAT_LEAST_ONCE
1036 | n, Must when n > 1 -> tclDO n
1037 | _ -> tclID
1038
1039 let cleartac clr = Proofview.tclTHEN (pf_check_hyps_uniq [] clr) (Tactics.clear (hyps_ids clr))
1040
1041 (* }}} *)
1042
1043 let get_hyp env sigma id =
1044 try EConstr.of_named_decl (Environ.lookup_named id env)
1045 with Not_found -> raise (Logic.RefinerError (env, sigma, Logic.NoSuchHyp id))
1046
1047 (** Generalize tactic *)
1048
1049 (* XXX the k of the redex should percolate out *)
1050 let pf_interp_gen_aux env sigma ~concl to_ind ((oclr, occ), t) =
1051 let pat = interp_cpattern env sigma t None in (* UGLY API *)
1052 let sigma = Evd.merge_universe_context sigma (Evd.ustate @@ pat.pat_sigma) in
1053 let sigma, c, cl = fill_rel_occ_pattern env sigma concl pat occ in
1054 let clr = interp_clr sigma (oclr, (tag_of_cpattern t, c)) in
1055 if not(occur_existential sigma c) then
1056 if tag_of_cpattern t = WithAt then
1057 if not (EConstr.isVar sigma c) then
1058 errorstrm (str "@ can be used with variables only")
1059 else match get_hyp env sigma (EConstr.destVar sigma c) with
1060 | NamedDecl.LocalAssum _ -> errorstrm (str "@ can be used with let-ins only")
1061 | NamedDecl.LocalDef (name, b, ty) -> true, pat, EConstr.mkLetIn (map_annot Name.mk_name name,b,ty,cl),c,clr, sigma
1062 else let sigma, ccl = pf_mkprod env sigma c cl in false, pat, ccl, c, clr, sigma
1063 else if to_ind && occ = None then
1064 let p, evs, ucst' = abs_evars env sigma (pat.pat_sigma, c) in
1065 let sigma = Evd.merge_universe_context sigma ucst' in
1066 if List.is_empty evs then anomaly "occur_existential but no evars" else
1067 let sigma, pty, rp = pfe_type_relevance_of env sigma p in
1068 false, pat, EConstr.mkProd (make_annot (constr_name sigma c) rp, pty, concl), p, clr, sigma
1069 else CErrors.user_err ?loc:(loc_of_cpattern t) (str "generalized term didn't match")
1070
1071 let genclrtac cl cs clr =
1072 let open Proofview.Notations in
1073 (* apply_type may give a type error, but the useful message is
1074 * the one of clear. You type "move: x" and you get
1075 * "x is used in hyp H" instead of
1076 * "The term H has type T x but is expected to have type T x0". *)
1077 (Proofview.tclORELSE
1078 (Tactics.apply_type ~typecheck:true cl cs)
1079 (fun (type_err, info) ->
1080 (Tactics.exfalso) <*>
1081 (cleartac clr) <*>
1082 (Proofview.tclZERO ~info type_err)))
1083 <*>
1084 (cleartac clr)
1085
1086 let gentac gen =
1087 Proofview.Goal.enter begin fun gl ->
1088 let env = Proofview.Goal.env gl in
1089 let sigma = Proofview.Goal.sigma gl in
1090 let concl = Proofview.Goal.concl gl in
1091 (* ppdebug(lazy(str"sigma@gentac=" ++ pr_evar_map None (project gl))); *)
1092 let conv, _, cl, c, clr, sigma = pf_interp_gen_aux env sigma ~concl false gen in
1093 debug_ssr (fun () -> str"c@gentac=" ++ pr_econstr_env env sigma c);
1094 Proofview.Unsafe.tclEVARS sigma <*>
1095 if conv
1096 then Tacticals.tclTHEN (convert_concl ~check:true cl) (cleartac clr)
1097 else genclrtac cl [c] clr
1098 end
1099
1100 let genstac (gens, clr) =
1101 Tacticals.tclTHENLIST (cleartac clr :: List.rev_map gentac gens)
1102
1103 let interp_gen env sigma ~concl to_ind gen =
1104 let _, _, a, b, c, sigma = pf_interp_gen_aux env sigma ~concl to_ind gen in
1105 sigma, (a, b ,c)
1106
1107 let is_protect hd env sigma =
1108 let protectC = mkSsrRef "protect_term" in
1109 EConstr.isRefX env sigma protectC hd
1110
1111 let abs_wgen env sigma keep_let f gen (args,c) =
1112 let evar_closed t p =
1113 if occur_existential sigma t then
1114 CErrors.user_err ?loc:(loc_of_cpattern p)
1115 (pr_econstr_pat env sigma t ++
1116 str" contains holes and matches no subterm of the goal.") in
1117 match gen with
1118 | _, Some ((x, mode), None) when mode = "@" || (mode = " " && keep_let) ->
1119 let x = hoi_id x in
1120 let decl = get_hyp env sigma x in
1121 sigma,
1122 (if NamedDecl.is_local_def decl then args else EConstr.mkVar x :: args),
1123 EConstr.mkProd_or_LetIn (decl |> NamedDecl.to_rel_decl |> RelDecl.set_name (Name (f x)))
1124 (EConstr.Vars.subst_var sigma x c)
1125 | _, Some ((x, _), None) ->
1126 let x = hoi_id x in
1127 let hyp = get_hyp env sigma x in
1128 let x' = make_annot (Name (f x)) (NamedDecl.get_relevance hyp) in
1129 let prod = EConstr.mkProd (x', NamedDecl.get_type hyp, EConstr.Vars.subst_var sigma x c) in
1130 sigma, EConstr.mkVar x :: args, prod
1131 | _, Some ((x, "@"), Some p) ->
1132 let x = hoi_id x in
1133 let cp = interp_cpattern env sigma p None in
1134 let sigma = Evd.merge_universe_context sigma (Evd.ustate cp.pat_sigma) in
1135 let sigma, t, c = fill_rel_occ_pattern env sigma c cp None in
1136 evar_closed t p;
1137 let ut = red_product_skip_id env sigma t in
1138 let sigma, ty, r = pfe_type_relevance_of env sigma t in
1139 sigma, args, EConstr.mkLetIn(make_annot (Name (f x)) r, ut, ty, c)
1140 | _, Some ((x, _), Some p) ->
1141 let x = hoi_id x in
1142 let cp = interp_cpattern env sigma p None in
1143 let sigma = Evd.merge_universe_context sigma (Evd.ustate cp.pat_sigma) in
1144 let sigma, t, c = fill_rel_occ_pattern env sigma c cp None in
1145 evar_closed t p;
1146 let sigma, ty, r = pfe_type_relevance_of env sigma t in
1147 sigma, t :: args, EConstr.mkProd(make_annot (Name (f x)) r, ty, c)
1148 | _ -> sigma, args, c
1149
1150 let clr_of_wgen gen clrs = match gen with
1151 | clr, Some ((x, _), None) ->
1152 let x = hoi_id x in
1153 cleartac clr :: cleartac [SsrHyp(Loc.tag x)] :: clrs
1154 | clr, _ -> cleartac clr :: clrs
1155
1156
1157 let reduct_in_concl ~check t = Tactics.reduct_in_concl ~cast:false ~check (t, DEFAULTcast)
1158 let unfold cl =
1159 Proofview.tclEVARMAP >>= fun sigma ->
1160 let module R = Reductionops in let module F = RedFlags in
1161 let flags = F.mkflags [F.fBETA; F.fMATCH; F.fFIX; F.fCOFIX; F.fDELTA] in
1162 let fold accu c = F.red_add accu (F.fCONST (fst (EConstr.destConst sigma c))) in
1163 let flags = List.fold_left fold flags cl in
1164 reduct_in_concl ~check:false (R.clos_norm_flags flags)
1165
1166 open Proofview
1167 open Notations
1168
1169 let pf_apply f = Proofview.Goal.enter_one ~__LOC__ begin fun gl ->
1170 f (Proofview.Goal.env gl) (Proofview.Goal.sigma gl)
1171 end
1172
1173 let tclINTERP_AST_CLOSURE_TERM_AS_CONSTR c =
1174 tclINDEPENDENTL @@ pf_apply begin fun env sigma ->
1175 let old_ssrterm = mkRHole, Some c.Ssrast.body in
1176 let ist =
1177 option_assert_get c.Ssrast.interp_env
1178 Pp.(str "tclINTERP_AST_CLOSURE_TERM_AS_CONSTR: term with no ist") in
1179 let sigma, t = Tacinterp.interp_constr_gen Pretyping.WithoutTypeConstraint ist env sigma old_ssrterm in
1180 Unsafe.tclEVARS sigma <*>
1181 tclUNIT t
1182 end
1183
1184 let tacEVAL_TO_QUANTIFIED_IND ty =
1185 pf_apply begin fun env sigma ->
1186 try tclUNIT (Tacred.eval_to_quantified_ind env sigma ty)
1187 with e when CErrors.noncritical e -> tclZERO e
1188 end
1189
1190 let tacTYPEOF c = Goal.enter_one ~__LOC__ (fun g ->
1191 let sigma, env = Goal.sigma g, Goal.env g in
1192 let sigma, ty = Typing.type_of env sigma c in
1193 Unsafe.tclEVARS sigma <*> tclUNIT ty)
1194
1195 (** This tactic creates a partial proof realizing the introduction rule, but
1196 does not check anything. *)
1197 let unsafe_intro env decl ~relevance b =
1198 let open Context.Named.Declaration in
1199 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
1200 let ctx = Environ.named_context_val env in
1201 let nctx = EConstr.push_named_context_val decl ctx in
1202 let inst = EConstr.identity_subst_val (Environ.named_context_val env) in
1203 let ninst = SList.cons (EConstr.mkRel 1) inst in
1204 let nb = EConstr.Vars.subst1 (EConstr.mkVar (get_id decl)) b in
1205 let sigma, ev = Evarutil.new_pure_evar nctx sigma ~relevance nb in
1206 sigma, EConstr.mkNamedLambda_or_LetIn sigma decl (EConstr.mkEvar (ev, ninst)), Some ev
1207 end
1208
1209 let set_decl_id id = let open Context in function
1210 | Rel.Declaration.LocalAssum(name,ty) -> Named.Declaration.LocalAssum({name with binder_name=id},ty)
1211 | Rel.Declaration.LocalDef(name,ty,t) -> Named.Declaration.LocalDef({name with binder_name=id},ty,t)
1212
1213 let rec decompose_assum env sigma orig_goal =
1214 let open Context in
1215 match EConstr.kind sigma orig_goal with
1216 | Prod(name,ty,t) ->
1217 Rel.Declaration.LocalAssum(name,ty), t, true
1218 | LetIn(name,ty,t1,t2) -> Rel.Declaration.LocalDef(name, ty, t1), t2, true
1219 | _ ->
1220 let goal = Reductionops.whd_allnolet env sigma orig_goal in
1221 match EConstr.kind sigma goal with
1222 | Prod(name,ty,t) -> Rel.Declaration.LocalAssum(name,ty), t, false
1223 | LetIn(name,ty,t1,t2) -> Rel.Declaration.LocalDef(name,ty,t1), t2, false
1224 | App(hd,args) when EConstr.isLetIn sigma hd -> (* hack *)
1225 let _,v,_,b = EConstr.destLetIn sigma hd in
1226 let ctx, t, _ =
1227 decompose_assum env sigma
1228 (EConstr.mkApp (EConstr.Vars.subst1 v b, args)) in
1229 ctx, t, false
1230 | _ -> CErrors.user_err
1231 Pp.(str "No assumption in " ++ Printer.pr_econstr_env env sigma goal)
1232
1233 let tclFULL_BETAIOTA = Goal.enter begin fun gl ->
1234 let r, _ = Redexpr.reduction_of_red_expr (Goal.env gl)
1235 Genredexpr.(Lazy {
1236 rBeta=true; rMatch=true; rFix=true; rCofix=true;
1237 rZeta=false; rDelta=false; rConst=[]; rStrength=Norm}) in
1238 Tactics.e_reduct_in_concl ~cast:false ~check:false (r,Constr.DEFAULTcast)
1239 end
1240
1241 type intro_id =
1242 | Anon
1243 | Id of Id.t
1244 | Seed of string
1245
1246 (** [intro id k] introduces the first premise (product or let-in) of the goal
1247 under the name [id], reducing the head of the goal (using beta, iota, delta
1248 but not zeta) if necessary. If [id] is None, a name is generated, that will
1249 not be user accessible. If the goal does not start with a product or a
1250 let-in even after reduction, it fails. In case of success, the original name
1251 and final id are passed to the continuation [k] which gets evaluated. *)
1252 let tclINTRO ~id ~conclusion:k = Goal.enter begin fun gl ->
1253 let open Context in
1254 let env, sigma, g, relevance = Goal.(env gl, sigma gl, concl gl, relevance gl) in
1255 let decl, t, no_red = decompose_assum env sigma g in
1256 let original_name = Rel.Declaration.get_name decl in
1257 let already_used = Environ.named_context_val env in
1258 let id = match id, original_name with
1259 | Id id, _ -> id
1260 | Seed id, _ -> mk_anon_id id already_used
1261 | Anon, Name id ->
1262 if is_discharged_id id then id
1263 else mk_anon_id (Id.to_string id) already_used
1264 | Anon, Anonymous ->
1265 let ids = Environ.named_context_val env in
1266 mk_anon_id ssr_anon_hyp ids
1267 in
1268 if Id.Map.mem id already_used.Environ.env_named_map then
1269 errorstrm Pp.(Id.print id ++ str" already used");
1270 unsafe_intro env (set_decl_id id decl) ~relevance t <*>
1271 (if no_red then tclUNIT () else tclFULL_BETAIOTA) <*>
1272 k ~orig_name:original_name ~new_name:id
1273 end
1274
1275 let return ~orig_name:_ ~new_name:_ = tclUNIT ()
1276
1277 let tclINTRO_ID id = tclINTRO ~id:(Id id) ~conclusion:return
1278 let tclINTRO_ANON ?seed () =
1279 match seed with
1280 | None -> tclINTRO ~id:Anon ~conclusion:return
1281 | Some seed -> tclINTRO ~id:(Seed seed) ~conclusion:return
1282
1283 let tclRENAME_HD_PROD name = Goal.enter begin fun gl ->
1284 let concl = Goal.concl gl in
1285 let sigma = Goal.sigma gl in
1286 match EConstr.kind sigma concl with
1287 | Prod(x,src,tgt) ->
1288 convert_concl_no_check EConstr.(mkProd ({x with binder_name = name},src,tgt))
1289 | _ -> CErrors.anomaly (Pp.str "rename_hd_prod: no head product")
1290 end
1291
1292 let tcl0G ~default tac =
1293 numgoals >>= fun ng -> if ng = 0 then tclUNIT default else tac
1294
1295 let rec tclFIRSTa = function
1296 | [] -> Tacticals.tclZEROMSG Pp.(str"No applicable tactic.")
1297 | tac :: rest -> tclORELSE tac (fun _ -> tclFIRSTa rest)
1298
1299 let rec tclFIRSTi tac n =
1300 if n < 0 then Tacticals.tclZEROMSG Pp.(str "tclFIRSTi")
1301 else tclORELSE (tclFIRSTi tac (n-1)) (fun _ -> tac n)
1302
1303 let tacCONSTR_NAME ?name c =
1304 match name with
1305 | Some n -> tclUNIT n
1306 | None ->
1307 Goal.enter_one ~__LOC__ (fun g ->
1308 let sigma = Goal.sigma g in
1309 tclUNIT (constr_name sigma c))
1310
1311 let tacMKPROD c ?name cl =
1312 tacTYPEOF c >>= fun t ->
1313 tacCONSTR_NAME ?name c >>= fun name ->
1314 Goal.enter_one ~__LOC__ begin fun g ->
1315 let sigma, env = Goal.sigma g, Goal.env g in
1316 let r = Retyping.relevance_of_term env sigma c in
1317 if name <> Names.Name.Anonymous || EConstr.Vars.noccurn sigma 1 cl
1318 then tclUNIT (EConstr.mkProd (make_annot name r, t, cl))
1319 else
1320 let name = Names.Id.of_string (Namegen.hdchar env sigma t) in
1321 tclUNIT (EConstr.mkProd (make_annot (Name.Name name) r, t, cl))
1322 end
1323
1324 let tacINTERP_CPATTERN cp =
1325 pf_apply begin fun env sigma ->
1326 tclUNIT (Ssrmatching.interp_cpattern env sigma cp None)
1327 end
1328
1329 let tacUNIFY a b =
1330 pf_apply begin fun env sigma ->
1331 let sigma = Ssrmatching.unify_HO env sigma a b in
1332 Unsafe.tclEVARS sigma
1333 end
1334
1335 let tclOPTION o d =
1336 match o with
1337 | None -> d >>= tclUNIT
1338 | Some x -> tclUNIT x
1339
1340 let tacIS_INJECTION_CASE ?ty t = begin
1341 tclOPTION ty (tacTYPEOF t) >>= fun ty ->
1342 tacEVAL_TO_QUANTIFIED_IND ty >>= fun (mind,_) ->
1343 tclUNIT (Rocqlib.check_ref "core.eq.type" (GlobRef.IndRef mind))
1344 end
1345
1346 let tclWITHTOP tac = Goal.enter begin fun gl ->
1347 let env = Proofview.Goal.env gl in
1348 let top = mk_anon_id "top_assumption" (Environ.named_context_val env) in
1349 tclINTRO_ID top <*>
1350 tac (EConstr.mkVar top) <*>
1351 Tactics.clear [top]
1352 end
1353
1354 let tacMK_SSR_CONST name =
1355 Proofview.tclENV >>= fun env ->
1356 Proofview.tclEVARMAP >>= fun sigma ->
1357 match mkSsrConst env sigma name with
1358 | sigma, c -> Unsafe.tclEVARS sigma <*> tclUNIT c
1359 | exception e when CErrors.noncritical e ->
1360 tclLIFT (Proofview.NonLogical.raise (e, Exninfo.null))
1361
1362 let tacDEST_CONST c =
1363 Proofview.tclEVARMAP >>= fun sigma ->
1364 match EConstr.destConst sigma c with
1365 | c, _ -> tclUNIT c
1366 | exception e when CErrors.noncritical e ->
1367 tclLIFT (Proofview.NonLogical.raise (e, Exninfo.null))
1368
1369 (* TASSI: This version of unprotects inlines the unfold tactic definition,
1370 * since we don't want to wipe out let-ins, and it seems there is no flag
1371 * to change that behaviour in the standard unfold code *)
1372 let unprotecttac =
1373 tacMK_SSR_CONST "protect_term" >>= tacDEST_CONST >>= fun prot ->
1374 let open RedFlags in
1375 let flags = red_add_transparent allnolet TransparentState.empty in
1376 let flags = red_add flags (fCONST prot) in
1377 Tacticals.onClause (fun idopt ->
1378 let hyploc = Option.map (fun id -> id, InHyp) idopt in
1379 Tactics.reduct_option ~check:false
1380 (Reductionops.clos_norm_flags flags, DEFAULTcast) hyploc)
1381 allHypsAndConcl
1382
1383
1384 module type StateType = sig
1385 type state
1386 val init : state
1387 val name : string
1388 end
1389
1390 module MakeState(S : StateType) = struct
1391
1392 let state_field : S.state Proofview_monad.StateStore.field =
1393 Proofview_monad.StateStore.field S.name
1394
1395 (* FIXME: should not inject fresh_state, but initialize it at the beginning *)
1396 let lift_upd_state upd s =
1397 let open Proofview_monad.StateStore in
1398 let old_state = Option.default S.init (get s state_field) in
1399 upd old_state >>= fun new_state ->
1400 tclUNIT (set s state_field new_state)
1401
1402 let tacUPDATE upd = Goal.enter begin fun gl ->
1403 let s0 = Goal.state gl in
1404 Goal.enter_one ~__LOC__ (fun _ -> lift_upd_state upd s0) >>= fun s ->
1405 Unsafe.tclGETGOALS >>= fun gls ->
1406 let gls = List.map (fun gs ->
1407 let g = Proofview_monad.drop_state gs in
1408 Proofview_monad.goal_with_state g s) gls in
1409 Unsafe.tclSETGOALS gls
1410 end
1411
1412 let tclGET k = Goal.enter begin fun gl ->
1413 let open Proofview_monad.StateStore in
1414 k (Option.default S.init (get (Goal.state gl) state_field))
1415 end
1416
1417 let tclGET1 k = Goal.enter_one begin fun gl ->
1418 let open Proofview_monad.StateStore in
1419 k (Option.default S.init (get (Goal.state gl) state_field))
1420 end
1421
1422
1423 let tclSET new_s =
1424 let open Proofview_monad.StateStore in
1425 Unsafe.tclGETGOALS >>= fun gls ->
1426 let gls = List.map (fun gs ->
1427 let g = Proofview_monad.drop_state gs in
1428 let s = Proofview_monad.get_state gs in
1429 Proofview_monad.goal_with_state g (set s state_field new_s)) gls in
1430 Unsafe.tclSETGOALS gls
1431
1432 let get g =
1433 Option.default S.init
1434 (Proofview_monad.StateStore.get (Goal.state g) state_field)
1435
1436 end
1437
1438 let is_construct_ref env sigma c r =
1439 EConstr.isConstruct sigma c && Environ.QGlobRef.equal env (GlobRef.ConstructRef (fst(EConstr.destConstruct sigma c))) r
1440 let is_ind_ref env sigma c r = EConstr.isInd sigma c && Environ.QGlobRef.equal env (GlobRef.IndRef (fst(EConstr.destInd sigma c))) r
1441 let is_const_ref env sigma c r =
1442 EConstr.isConst sigma c && Environ.QGlobRef.equal env (GlobRef.ConstRef (fst(EConstr.destConst sigma c))) r
1443
1444 (* vim: set filetype=ocaml foldmethod=marker: *)