Debian Codegraph @

kernel/vars.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 Names
12
13 module RelDecl = Context.Rel.Declaration
14
15 (*********************)
16 (* Occurring *)
17 (*********************)
18
19 exception LocalOccur
20
21 (* (closedn n M) is true iff M is a (de Brujin) closed term under n binders *)
22
23 let closedn n c =
24 let rec closed_rec n c = match Constr.kind c with
25 | Constr.Rel m -> if m>n then raise_notrace LocalOccur
26 | _ -> Constr.iter_with_binders succ closed_rec n c
27 in
28 try closed_rec n c; true with LocalOccur -> false
29
30 (* [closed0 M] is true iff [M] is a (de Bruijn) closed term *)
31
32 let closed0 c = closedn 0 c
33
34 (* (noccurn n M) returns true iff (Rel n) does NOT occur in term M *)
35
36 let noccurn n term =
37 let rec occur_rec n c = match Constr.kind c with
38 | Constr.Rel m -> if Int.equal m n then raise_notrace LocalOccur
39 | _ -> Constr.iter_with_binders succ occur_rec n c
40 in
41 try occur_rec n term; true with LocalOccur -> false
42
43 (* (noccur_between n m M) returns true iff (Rel p) does NOT occur in term M
44 for n <= p < n+m *)
45
46 let noccur_between n m term =
47 let rec occur_rec n c = match Constr.kind c with
48 | Constr.Rel p -> if n<=p && p<n+m then raise_notrace LocalOccur
49 | _ -> Constr.iter_with_binders succ occur_rec n c
50 in
51 try occur_rec n term; true with LocalOccur -> false
52
53 (* Checking function for terms containing existential variables.
54 The function [noccur_with_meta] considers the fact that
55 each existential variable (as well as each isevar)
56 in the term appears applied to its local context,
57 which may contain the CoFix variables. These occurrences of CoFix variables
58 are not considered *)
59
60 let isMeta c = match Constr.kind c with
61 | Constr.Meta _ -> true
62 | _ -> false
63
64 let noccur_with_meta n m term =
65 let rec occur_rec n c = match Constr.kind c with
66 | Constr.Rel p -> if n<=p && p<n+m then raise_notrace LocalOccur
67 | Constr.App(f,_cl) ->
68 (match Constr.kind f with
69 | Constr.Cast (c,_,_) when isMeta c -> ()
70 | Constr.Meta _ -> ()
71 | _ -> Constr.iter_with_binders succ occur_rec n c)
72 | Constr.Evar (_, _) -> ()
73 | _ -> Constr.iter_with_binders succ occur_rec n c
74 in
75 try (occur_rec n term; true) with LocalOccur -> false
76
77 (*********************)
78 (* Lifting *)
79 (*********************)
80
81 let exliftn = Constr.exliftn
82 let liftn = Constr.liftn
83 let lift = Constr.lift
84
85 let liftn_rel_context n k =
86 Context.Rel.map_with_binders (fun i -> liftn n (i+k-1))
87
88 let lift_rel_context n =
89 Context.Rel.map_with_binders (liftn n)
90
91 (*********************)
92 (* Substituting *)
93 (*********************)
94
95 (* (subst1 M c) substitutes M for Rel(1) in c
96 we generalise it to (substl [M1,...,Mn] c) which substitutes in parallel
97 M1,...,Mn for respectively Rel(1),...,Rel(n) in c *)
98
99 (* 1st : general case *)
100
101 module IntTbl = Hashtbl.Make(Int)
102
103 type info = Closed | Open of Constr.t IntTbl.t | Unknown
104 type substituend = { mutable sinfo: info; sit: Constr.t }
105
106 let lift_substituend depth s =
107 match s.sinfo with
108 | Closed -> s.sit
109 | Open cache ->
110 begin match IntTbl.find_opt cache depth with
111 | Some v -> v
112 | None ->
113 let v = lift depth s.sit in
114 let () = IntTbl.add cache depth v in
115 v
116 end
117 | Unknown ->
118 let sit = s.sit in
119 if closed0 sit then
120 let () = s.sinfo <- Closed in
121 sit
122 else
123 let v = lift depth sit in
124 let cache = IntTbl.create 13 in
125 let () = IntTbl.add cache depth v in
126 let () = s.sinfo <- Open cache in
127 v
128
129 let lift_substituend depth s = if Int.equal depth 0 then s.sit else lift_substituend depth s
130
131 let make_substituend c = { sinfo=Unknown; sit=c }
132
133 let substn_many lamv n c =
134 let lv = Array.length lamv in
135 if Int.equal lv 0 then c
136 else
137 let rec substrec depth c = match Constr.kind c with
138 | Constr.Rel k ->
139 if k<=depth then c
140 else if k-depth <= lv then lift_substituend depth (Array.unsafe_get lamv (k-depth-1))
141 else Constr.mkRel (k-lv)
142 | _ -> Constr.map_with_binders succ substrec depth c in
143 substrec n c
144
145 let make_subst = function
146 | [] -> [||]
147 | hd :: tl ->
148 let len = List.length tl in
149 let subst = Array.make (1 + len) (make_substituend hd) in
150 let s = ref tl in
151 for i = 1 to len do
152 match !s with
153 | [] -> assert false
154 | x :: tl ->
155 Array.unsafe_set subst i (make_substituend x);
156 s := tl
157 done;
158 subst
159
160 (* The type of substitutions, with term substituting most recent
161 binder at the head *)
162
163 type substl = Constr.t list
164
165 let substnl laml n c = substn_many (make_subst laml) n c
166 let substl laml c = substn_many (make_subst laml) 0 c
167 let subst1 lam c = substn_many [|make_substituend lam|] 0 c
168
169 let substnl_decl laml k r = RelDecl.map_constr (fun c -> substnl laml k c) r
170 let substl_decl laml r = RelDecl.map_constr (fun c -> substnl laml 0 c) r
171 let subst1_decl lam r = RelDecl.map_constr (fun c -> subst1 lam c) r
172
173 let substnl_rel_context laml k r =
174 Context.Rel.map_with_binders (fun i -> substnl laml (i+k-1)) r
175
176 let substl_rel_context laml r = substnl_rel_context laml 0 r
177 let subst1_rel_context lam r = substnl_rel_context [lam] 0 r
178
179 let esubst mk subst c =
180 let rec esubst subst c = match Constr.kind c with
181 | Constr.Rel i ->
182 let open Esubst in
183 begin match expand_rel i subst with
184 | Util.Inl (k, v) -> mk k v
185 | Util.Inr (m, _) -> Constr.mkRel m
186 end
187 | _ ->
188 Constr.map_with_binders Esubst.subs_lift esubst subst c
189 in
190 if Esubst.is_subs_id subst then c else esubst subst c
191
192 (* Instance of contexts *)
193
194 type instance = Constr.t array
195 type instance_list = Constr.t list
196
197 (* Build a substitution from an instance, inserting missing let-ins *)
198
199 let subst_of_rel_context_instance_list sign l =
200 let rec aux subst sign l =
201 let open RelDecl in
202 match sign, l with
203 | LocalAssum _ :: sign', a::args' -> aux (a::subst) sign' args'
204 | LocalDef (_,c,_)::sign', args' ->
205 aux (substl subst c :: subst) sign' args'
206 | [], [] -> subst
207 | _ -> CErrors.anomaly (Pp.str "Instance and signature do not match.")
208 in aux [] (List.rev sign) l
209
210 let subst_of_rel_context_instance sign v =
211 subst_of_rel_context_instance_list sign (Array.to_list v)
212
213 let adjust_rel_to_rel_context sign n =
214 let rec aux sign =
215 let open RelDecl in
216 match sign with
217 | LocalAssum _ :: sign' -> let (n',p) = aux sign' in (n'+1,p)
218 | LocalDef (_,_c,_)::sign' -> let (n',p) = aux sign' in (n'+1,if n'<n then p+1 else p)
219 | [] -> (0,n)
220 in snd (aux sign)
221
222 (* (thin_val sigma) removes identity substitutions from sigma *)
223
224 let rec thin_val = function
225 | [] -> []
226 | (id, c) :: tl ->
227 match Constr.kind c with
228 | Constr.Var v ->
229 if Id.equal id v then thin_val tl
230 else (id, make_substituend c) :: (thin_val tl)
231 | _ -> (id, make_substituend c) :: (thin_val tl)
232
233 let find_var id vars = CList.assoc_f Id.equal id vars
234
235 (* (replace_vars sigma M) applies substitution sigma to term M *)
236 let replace_vars var_alist x =
237 let var_alist = thin_val var_alist in
238 match var_alist with
239 | [] -> x
240 | _ ->
241 let rec substrec n c = match Constr.kind c with
242 | Constr.Var x ->
243 begin match find_var x var_alist with
244 | var -> lift_substituend n var
245 | exception Not_found -> c
246 end
247 | Constr.Evar _ ->
248 CErrors.anomaly (Pp.str "Substituting an evar in the kernel")
249 | _ -> Constr.map_with_binders succ substrec n c
250 in
251 substrec 0 x
252
253 (* (subst_var str t) substitute (Var str) by (Rel 1) in t *)
254 let subst_var str t = replace_vars [(str, Constr.mkRel 1)] t
255
256 (* (subst_vars [id1;...;idn] t) substitute (Var idj) by (Rel j) in t *)
257 let substn_vars p vars c =
258 let _,subst =
259 List.fold_left (fun (n,l) var -> ((n+1),(var,Constr.mkRel n)::l)) (p,[]) vars
260 in replace_vars (List.rev subst) c
261
262 let subst_vars subst c = substn_vars 1 subst c
263
264 let smash_rel_context sign =
265 let open Context.Rel.Declaration in
266 let open Esubst in
267 snd (List.fold_right
268 (fun decl (subst, sign) ->
269 match get_value decl with
270 | Some b -> (subs_cons (make_substituend (esubst lift_substituend subst b)) subst, sign)
271 | None -> (subs_lift subst, map_constr (esubst lift_substituend subst) decl :: sign))
272 sign (subs_id 0, []))
273
274 (** Universe substitutions *)
275 open Constr
276
277 let map_annot_relevance f na =
278 let open Context in
279 let r = na.binder_relevance in
280 let r' = f r in
281 if r' == r then na else { na with binder_relevance = r' }
282
283 let map_case_under_context_relevance f (nas,x as v) =
284 let nas' = CArray.Smart.map (map_annot_relevance f) nas in
285 if nas' == nas then v else (nas',x)
286
287 let map_rec_declaration_relevance f (i,(nas,x,y) as v) =
288 let nas' = CArray.Smart.map (map_annot_relevance f) nas in
289 if nas' == nas then v else (i,(nas',x,y))
290
291 let map_constr_relevance f c =
292 match kind c with
293 | Rel _ | Var _ | Meta _ | Evar _
294 | Sort _ | Cast _ | App _
295 | Const _ | Ind _ | Construct _
296 | Int _ | Float _ | String _ | Array _ -> c
297
298 | Prod (na,x,y) ->
299 let na' = map_annot_relevance f na in
300 if na' == na then c else mkProd (na',x,y)
301
302 | Lambda (na,x,y) ->
303 let na' = map_annot_relevance f na in
304 if na' == na then c else mkLambda (na',x,y)
305
306 | LetIn (na,x,y,z) ->
307 let na' = map_annot_relevance f na in
308 if na' == na then c else mkLetIn (na',x,y,z)
309
310 | Case (ci,u,params,(ret,r),iv,v,brs) ->
311 let r' = f r in
312 let ret' = map_case_under_context_relevance f ret in
313 let brs' = CArray.Smart.map (map_case_under_context_relevance f) brs in
314 if r' == r && ret' == ret && brs' == brs then c
315 else mkCase (ci,u,params,(ret',r'),iv,v,brs')
316
317 | Fix data ->
318 let data' = map_rec_declaration_relevance f data in
319 if data' == data then c else mkFix data'
320
321 | CoFix data ->
322 let data' = map_rec_declaration_relevance f data in
323 if data' == data then c else mkCoFix data'
324
325 | Proj (p, r, v) ->
326 let r' = f r in
327 if r' == r then c else mkProj (p, r', v)
328
329 let fold_annot_relevance f acc na =
330 f acc na.Context.binder_relevance
331
332 let fold_case_under_context_relevance f acc (nas,_) =
333 Array.fold_left (fold_annot_relevance f) acc nas
334
335 let fold_rec_declaration_relevance f acc (nas,_,_) =
336 Array.fold_left (fold_annot_relevance f) acc nas
337
338 let fold_kind_relevance f acc c =
339 match c with
340 | Rel _ | Var _ | Meta _ | Evar _
341 | Sort _ | Cast _ | App _
342 | Const _ | Ind _ | Construct _
343 | Int _ | Float _ | String _ | Array _ -> acc
344
345 | Prod (na,_,_) | Lambda (na,_,_) | LetIn (na,_,_,_) ->
346 fold_annot_relevance f acc na
347
348 | Case (_,_u,_params,(ret,r),_iv,_v,brs) ->
349 let acc = f acc r in
350 let acc = fold_case_under_context_relevance f acc ret in
351 let acc = CArray.fold_left (fold_case_under_context_relevance f) acc brs in
352 acc
353
354 | Proj (_, r, _) -> f acc r
355
356 | Fix (_,data)
357 | CoFix (_,data) ->
358 fold_rec_declaration_relevance f acc data
359
360 let subst_univs_level_constr subst c =
361 if UVars.is_empty_sort_subst subst then c
362 else
363 let f = UVars.subst_sort_level_instance subst in
364 (* XXX shouldn't Constr.map return the pointer equal term when unchanged instead? *)
365 let changed = ref false in
366 let rec aux t =
367 let t' = map_constr_relevance (UVars.subst_sort_level_relevance subst) t in
368 let t = if t' == t then t else (changed := true; t') in
369 match kind t with
370 | Const (c, u) ->
371 if UVars.Instance.is_empty u then t
372 else
373 let u' = f u in
374 if u' == u then t
375 else (changed := true; mkConstU (c, u'))
376 | Ind (i, u) ->
377 if UVars.Instance.is_empty u then t
378 else
379 let u' = f u in
380 if u' == u then t
381 else (changed := true; mkIndU (i, u'))
382 | Construct (c, u) ->
383 if UVars.Instance.is_empty u then t
384 else
385 let u' = f u in
386 if u' == u then t
387 else (changed := true; mkConstructU (c, u'))
388 | Sort s ->
389 let s' = UVars.subst_sort_level_sort subst s in
390 if s' == s then t
391 else
392 (changed := true; mkSort s')
393
394 | Case (ci, u, pms, p, iv, c, br) ->
395 if UVars.Instance.is_empty u then Constr.map aux t
396 else
397 let u' = f u in
398 if u' == u then Constr.map aux t
399 else (changed:=true; Constr.map aux (mkCase (ci,u',pms,p,iv,c,br)))
400
401 | Array (u,elems,def,ty) ->
402 let u' = f u in
403 let elems' = CArray.Smart.map aux elems in
404 let def' = aux def in
405 let ty' = aux ty in
406 if u == u' && elems == elems' && def == def' && ty == ty' then t
407 else (changed := true; mkArray (u',elems',def',ty'))
408
409 | _ -> Constr.map aux t
410 in
411 let c' = aux c in
412 if !changed then c' else c
413
414 let subst_univs_level_context s ctx =
415 CList.Smart.map (fun d ->
416 let d = RelDecl.map_relevance (UVars.subst_sort_level_relevance s) d in
417 RelDecl.map_constr (subst_univs_level_constr s) d)
418 ctx
419
420 let subst_instance_constr subst c =
421 if UVars.Instance.is_empty subst then c
422 else
423 let f u = UVars.subst_instance_instance subst u in
424 let rec aux t =
425 let t = if CArray.is_empty (fst (UVars.Instance.to_array subst)) then t
426 else map_constr_relevance (UVars.subst_instance_relevance subst) t
427 in
428 match kind t with
429 | Const (c, u) ->
430 if UVars.Instance.is_empty u then t
431 else
432 let u' = f u in
433 if u' == u then t
434 else (mkConstU (c, u'))
435 | Ind (i, u) ->
436 if UVars.Instance.is_empty u then t
437 else
438 let u' = f u in
439 if u' == u then t
440 else (mkIndU (i, u'))
441 | Construct (c, u) ->
442 if UVars.Instance.is_empty u then t
443 else
444 let u' = f u in
445 if u' == u then t
446 else (mkConstructU (c, u'))
447 | Sort s ->
448 let s' = UVars.subst_instance_sort subst s in
449 if s' == s then t else mkSort s'
450
451 | Case (ci, u, pms, p, iv, c, br) ->
452 let u' = f u in
453 if u' == u then Constr.map aux t
454 else Constr.map aux (mkCase (ci,u',pms,p,iv,c,br))
455
456 | Array (u,elems,def,ty) ->
457 let u' = f u in
458 let elems' = CArray.Smart.map aux elems in
459 let def' = aux def in
460 let ty' = aux ty in
461 if u == u' && elems == elems' && def == def' && ty == ty' then t
462 else mkArray (u',elems',def',ty')
463
464 | _ -> Constr.map aux t
465 in
466 aux c
467
468 let univ_instantiate_constr u c =
469 let open UVars in
470 assert (UVars.eq_sizes (Instance.length u) (AbstractContext.size c.univ_abstracted_binder));
471 subst_instance_constr u c.univ_abstracted_value
472
473 let subst_instance_context s ctx =
474 if UVars.Instance.is_empty s then ctx
475 else
476 CList.Smart.map (fun d ->
477 let d = RelDecl.map_relevance (UVars.subst_instance_relevance s) d in
478 RelDecl.map_constr (subst_instance_constr s) d)
479 ctx
480
481 type ('a,'s,'u,'r) univ_visitor = {
482 visit_sort : 'a -> 's -> 'a;
483 visit_instance : 'a -> 'u -> 'a;
484 visit_relevance : 'a -> 'r -> 'a;
485 }
486
487 let univs_and_qvars_visitor =
488 let open Univ in
489 let visit_sort (qs,us as acc) = function
490 | Sorts.Type u ->
491 qs, Universe.levels ~init:us u
492 | Sorts.QSort (q,u) ->
493 Sorts.QVar.Set.add q qs, Universe.levels ~init:us u
494 | Sorts.(SProp | Prop | Set) -> acc
495 in
496 let visit_instance (qs,us) u =
497 let qs', us' = UVars.Instance.to_array u in
498 let qs = Array.fold_left (fun qs q ->
499 let open Sorts.Quality in
500 match q with
501 | QVar q -> Sorts.QVar.Set.add q qs
502 | QConstant _ -> qs)
503 qs qs'
504 in
505 let us = Array.fold_left (fun acc x -> Univ.Level.Set.add x acc) us us' in
506 qs, us
507 in
508 let visit_relevance (qs,us as acc) = let open Sorts in function
509 | Irrelevant | Relevant -> acc
510 | RelevanceVar q -> QVar.Set.add q qs, us
511 in
512 {
513 visit_sort = visit_sort;
514 visit_instance = visit_instance;
515 visit_relevance = visit_relevance;
516 }
517
518 let visit_kind_univs visit acc c =
519 let acc = fold_kind_relevance visit.visit_relevance acc c in
520 match c with
521 | Const (_, u) | Ind (_, u) | Construct (_,u) -> visit.visit_instance acc u
522 | Sort s -> visit.visit_sort acc s
523 | Array (u,_,_,_) ->
524 let acc = visit.visit_instance acc u in
525 acc
526 | Case (_, u, _, _, _,_ ,_) ->
527 let acc = visit.visit_instance acc u in
528 acc
529 | _ -> acc
530
531 let sort_and_universes_of_constr ?(init=Sorts.QVar.Set.empty,Univ.Level.Set.empty) c =
532 let rec aux s c =
533 let s = visit_kind_univs univs_and_qvars_visitor s (kind c) in
534 Constr.fold aux s c
535 in
536 aux init c
537
538 let sort_and_universes_of_constr ?init c =
539 NewProfile.profile "sort_and_universes_of_constr" (fun () ->
540 sort_and_universes_of_constr ?init c)
541 ()
542
543 let universes_of_constr ?(init=Univ.Level.Set.empty) c =
544 snd (sort_and_universes_of_constr ~init:(Sorts.QVar.Set.empty,init) c)