Debian Codegraph @

pretyping/combinators.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 Rocqlib
12 open CErrors
13 open Util
14 open Termops
15 open EConstr
16 open Retyping
17 open Typing
18 open Inductiveops
19
20 module RelDecl = Context.Rel.Declaration
21
22 (**************)
23 (** Telescope *)
24
25 let get_sigmatypes sigma ~sort ~predsort =
26 let open EConstr in
27 let open Sorts.Quality in
28 let which, sigsort = match predsort, sort with
29 | QConstant QSProp, _ | _, QConstant QSProp ->
30 user_err Pp.(str "SProp arguments not supported by Program Fixpoint yet.")
31 | QConstant QProp, QConstant QProp -> "ex", qprop
32 | QConstant QProp, QConstant QType -> "sig", qtype
33 | QConstant QType, QConstant (QProp|QType) -> "sigT", qtype
34 | _ -> assert false
35 in
36 let sigma, ty = Evd.fresh_global (Global.env ()) sigma (lib_ref ("core."^which^".type")) in
37 let uinstance = snd (destRef sigma ty) in
38 let intro = mkRef (lib_ref ("core."^which^".intro"), uinstance) in
39 let p1 = mkRef (lib_ref ("core."^which^".proj1"), uinstance) in
40 let p2 = mkRef (lib_ref ("core."^which^".proj2"), uinstance) in
41 sigma, ty, intro, p1, p2, sigsort
42
43 let rec telescope sigma l =
44 let open EConstr in
45 let open Vars in
46 match l with
47 | [] -> assert false
48 | [RelDecl.LocalAssum (n, t), _] ->
49 sigma, t, [RelDecl.LocalDef (n, mkRel 1, t)], mkRel 1
50 | (LocalAssum (n, t), tsort) :: tl ->
51 let sigma, ty, _tysort, tys, (k, constr) =
52 List.fold_left
53 (fun (sigma, ty, tysort, tys, (k, constr)) (decl,sort) ->
54 let t = RelDecl.get_type decl in
55 let pred = mkLambda (RelDecl.get_annot decl, t, ty) in
56 let sigma, ty, intro, p1, p2, sigsort = get_sigmatypes sigma ~predsort:tysort ~sort in
57 let sigty = mkApp (ty, [|t; pred|]) in
58 let intro = mkApp (intro, [|lift k t; lift k pred; mkRel k; constr|]) in
59 (sigma, sigty, sigsort, (pred, p1, p2) :: tys, (succ k, intro)))
60 (sigma, t, tsort, [], (2, mkRel 1)) tl
61 in
62 let sigma, last, subst = List.fold_right2
63 (fun (pred,p1,p2) (decl,_) (sigma, prev, subst) ->
64 let t = RelDecl.get_type decl in
65 let proj1 = applist (p1, [t; pred; prev]) in
66 let proj2 = applist (p2, [t; pred; prev]) in
67 (sigma, lift 1 proj2, RelDecl.(LocalDef (get_annot decl, proj1, t) :: subst)))
68 (List.rev tys) tl (sigma, mkRel 1, [])
69 in sigma, ty, (LocalDef (n, last, t) :: subst), constr
70
71 | (LocalDef (n, b, t), _) :: tl ->
72 let sigma, ty, subst, term = telescope sigma tl in
73 sigma, ty, (LocalDef (n, b, t) :: subst), lift 1 term
74
75 type telescope = {
76 telescope_type : EConstr.types;
77 telescope_value : EConstr.constr;
78 }
79
80 let telescope env sigma ctx =
81 let ctx, _ = List.fold_right_map (fun d env ->
82 let s = Retyping.get_sort_quality_of env sigma (RelDecl.get_type d) in
83 let env = EConstr.push_rel d env in
84 (d, UnivGen.QualityOrSet.quality s), env) ctx env
85 in
86 let sigma, telescope_type, letcontext, telescope_value = telescope sigma ctx in
87 sigma, letcontext, { telescope_type; telescope_value }
88
89 (****************************************************)
90 (** Closure of a term according to its dependencies *)
91
92 (* [make_tuple env sigma (rterm,rty) lind] assumes [lind] is the lesser
93 index bound in [rty]
94
95 Then it builds the term
96
97 [(existT A P (mkRel lind) rterm)] of type [(sigT A P)]
98
99 where [A] is the type of [mkRel lind] and [P] is [fun na:A => rty{1/lind}]
100 *)
101
102 let make_tuple env sigma (rterm,rty) lind =
103 assert (not (Vars.noccurn sigma lind rty));
104 let sigdata = build_sigma_type () in
105 let sigma, a = type_of ~refresh:true env sigma (mkRel lind) in
106 let a = Tacred.simpl env sigma a in
107 let na = Context.Rel.Declaration.get_annot (lookup_rel lind env) in
108 (* We move [lind] to [1] and lift other rels > [lind] by 1 *)
109 let rty = Vars.lift (1-lind) (Vars.liftn lind (lind+1) rty) in
110 (* Now [lind] is [mkRel 1] and we abstract on (na:a) *)
111 let p = mkLambda (na, a, rty) in
112 let sigma, exist_term = Evd.fresh_global env sigma sigdata.intro in
113 let sigma, sig_term = Evd.fresh_global env sigma sigdata.typ in
114 sigma,
115 (applist(exist_term,[a;p;(mkRel lind);rterm]),
116 applist(sig_term,[a;p]))
117
118 (* check that the free-references of the type of [c] are contained in
119 the free-references of the normal-form of that type. Strictly
120 computing the exact set of free rels would require full
121 normalization but this is not reasonable (e.g. in presence of
122 records that contains proofs). We restrict ourself to a "simpl"
123 normalization *)
124
125 let minimal_free_rels env sigma (c,cty) =
126 let cty_rels = free_rels sigma cty in
127 let cty' = Tacred.simpl env sigma cty in
128 let rels' = free_rels sigma cty' in
129 if Int.Set.subset cty_rels rels' then
130 (cty,cty_rels)
131 else
132 (cty',rels')
133
134 (* Like the above, but recurse over all the rels found until there are
135 no more rels to be found *)
136
137 let minimal_free_rels_rec env sigma =
138 let rec minimalrec_free_rels_rec prev_rels (c,cty) =
139 let (cty,direct_rels) = minimal_free_rels env sigma (c,cty) in
140 let combined_rels = Int.Set.union prev_rels direct_rels in
141 let folder rels i = snd (minimalrec_free_rels_rec rels (c, get_type_of env sigma (mkRel i)))
142 in (cty, List.fold_left folder combined_rels (Int.Set.elements (Int.Set.diff direct_rels prev_rels)))
143 in minimalrec_free_rels_rec Int.Set.empty
144
145 (** [sig_clausal_form siglen ty]
146
147 Will explode [siglen] [sigT ]'s on [ty] (depending on the
148 type of ty), and return:
149
150 (1) a pattern, with meta-variables in it for various arguments,
151 which, when the metavariables are replaced with appropriate
152 terms, will have type [ty]
153
154 (2) an integer, which is the last argument - the one which we just
155 returned.
156
157 (3) a pattern, for the type of that last meta
158
159 (4) a typing for each patvar
160
161 WARNING: No checking is done to make sure that the
162 sigT's are actually there.
163 - Only homogeneous pairs are built i.e. pairs where all the
164 dependencies are of the same sort
165
166 [sig_clausal_form] proceeds as follows: the default tuple is
167 constructed by taking the tuple-type, exploding the first [tuplen]
168 [sigT]'s, and replacing at each step the binder in the
169 right-hand-type by a fresh metavariable. In addition, on the way
170 back out, we will construct the pattern for the tuple which uses
171 these meta-vars.
172
173 This gives us a pattern, which we use to match against the type of
174 [dflt]; if that fails, then against the S(TRONG)NF of that type. If
175 both fail, then we just cannot construct our tuple. If one of
176 those succeed, then we can construct our value easily - we just use
177 the tuple-pattern.
178 *)
179
180 let sig_clausal_form env sigma sort_of_ty siglen ty dflt =
181 let sigdata = build_sigma_type () in
182 let rec sigrec_clausal_form sigma siglen p_i =
183 if Int.equal siglen 0 then
184 (* is the default value typable with the expected type *)
185 let dflt_typ = Retyping.get_type_of env sigma dflt in
186 try
187 let sigma = Evarconv.unify_leq_delay env sigma dflt_typ p_i in
188 let sigma = Evarconv.solve_unif_constraints_with_heuristics env sigma in
189 sigma, dflt
190 with Evarconv.UnableToUnify _ ->
191 user_err Pp.(str "Cannot solve a unification problem.")
192 else
193 let (a,p_i_minus_1) = match Reductionops.whd_beta_stack env sigma p_i with
194 | (_sigT,[a;p]) -> (a, p)
195 | _ -> anomaly ~label:"sig_clausal_form" (Pp.str "should be a sigma type.") in
196 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma a in
197 let sigma, ev = Evarutil.new_evar ~typeclass_candidate env sigma a in
198 let rty = Reductionops.beta_applist sigma (p_i_minus_1,[ev]) in
199 let sigma, tuple_tail = sigrec_clausal_form sigma (siglen-1) rty in
200 if EConstr.isEvar sigma ev then
201 (* This at least happens if what has been detected as a
202 dependency is not one; use an evasive error message;
203 even if the problem is upwards: unification should be
204 tried in the first place in make_iterated_tuple instead
205 of approximatively computing the free rels; then
206 unsolved evars would mean not binding rel *)
207 user_err Pp.(str "Cannot solve a unification problem.")
208 else
209 let sigma, exist_term = Evd.fresh_global env sigma sigdata.intro in
210 sigma, applist(exist_term,[a;p_i_minus_1;ev;tuple_tail])
211 in
212 let sigma, scf = sigrec_clausal_form sigma siglen ty in
213 sigma, Evarutil.nf_evar sigma scf
214
215 (** [make_iterated_tuple env sigma default c ctype] retruns
216
217 To do this, we find the free (relative) references of the strong NF
218 of [c]'s type, gather them together in left-to-right order
219 (i.e. highest-numbered is farthest-left), and construct a big
220 iterated pair out of it. This only works when the references are
221 all themselves to members of [Set]s, because we use [sigT] to
222 construct the tuple.
223
224 Suppose now that our constructed tuple is of length [tuplen]. We
225 need also to construct a default value for the other branches of
226 the destructor. As default value, we take a tuple of the form
227
228 [existT [xn]Pn ?n (... existT [x2]P2 ?2 (existT [x1]P1 ?1 term))]
229
230 but for this we have to solve the following unification problem:
231
232 typ = cty[i1/?1;...;in/?n]
233
234 This is done by [sig_clausal_form].
235 *)
236
237 let make_iterated_tuple env sigma ~default c cty =
238 let (cty,rels) = minimal_free_rels_rec env sigma (c,cty) in
239 let sort_of_cty = get_sort_of env sigma cty in
240 let sorted_rels = Int.Set.elements rels in
241 let sigma, (telescope_value, telescope_type) =
242 List.fold_left (fun (sigma, t) -> make_tuple env sigma t) (sigma, (c,cty)) sorted_rels
243 in
244 assert (Vars.closed0 sigma telescope_type);
245 let n = List.length sorted_rels in
246 let sigma, dfltval = sig_clausal_form env sigma sort_of_cty n telescope_type default in
247 sigma, { telescope_value; telescope_type }, dfltval
248
249 (** [make_selector env sigma dirn c ind special default]]
250 constructs a case-split on [c] of type [ind], with the [dirn]-th
251 branch giving [special], and all the rest giving [default]. *)
252
253 let make_selector env sigma ~pos ~special ~default c ctype =
254 let IndType(indf,_) as indt =
255 try find_rectype env sigma ctype
256 with Not_found ->
257 (* one can find Rel(k) in case of dependent constructors
258 like T := c : (A:Set)A->T and a discrimination
259 on (c bool true) = (c bool false)
260 CP : changed assert false in a more informative error
261 *)
262 user_err
263 Pp.(str "Cannot discriminate on inductive constructors with \
264 dependent types.") in
265 let (ind, _),_ = dest_ind_family indf in
266 let () = Tacred.check_privacy env ind in
267 let typ = Retyping.get_type_of env sigma default in
268 let (mib,mip) = Inductive.lookup_mind_specif env ind in
269 let deparsign = make_arity_signature env sigma true indf in
270 let p = it_mkLambda_or_LetIn typ deparsign in
271 let cstrs = get_constructors env indf in
272 let build_branch i =
273 let endpt = if Int.equal i pos then special else default in
274 let args = cstrs.(i-1).cs_args in
275 it_mkLambda_or_LetIn endpt args in
276 let brl =
277 List.map build_branch(List.interval 1 (Array.length mip.mind_consnames)) in
278 let rci = ERelevance.relevant in (* TODO relevance *)
279 let ci = make_case_info env ind RegularStyle in
280 Inductiveops.make_case_or_project env sigma indt ci (p, rci) c (Array.of_list brl)