Debian Codegraph @

kernel/hConstr.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 Util
12 open Names
13 open Constr
14 open Context
15
16 (** Provide caching and hashconsing dependent on the local context used by a term.
17
18 We want to cache the results of typechecking a term (at constant
19 global environment).
20
21 To do this, we need a map [constr -> result of typechecking], and
22
23 - it must distinguish alpha equal terms (to get the desired names
24 in the result of checking "fun x:nat => eq_refl x" and
25 "fun y:nat => eq_refl y").
26
27 - it must distinguish terms which only differ in "cached" data
28 like relevance marks (if we typecheck "fun x :(*Relevant*) nat => x",
29 cache the result then check "fun x :(*Irrelevant*) nat => x" we must fail).
30
31 - actually the map should be [(rel_context * constr) -> result] as
32 the result of checking a bound variable depends on the context.
33
34 To be more precise we only need to depend on the minimal context
35 needed for the term, ie the context filtered to only the
36 variables which appear in the term and recursively in the types
37 and bodies of needed variables.
38
39 Also note that we don't care about the names of local variables
40 here, they only appear in error messages and since we stop at
41 the first error there is no caching issue.
42
43 (NB we need bodies as while the result of checking [Rel 1] does
44 not depend on the body of rel 1, checking [eq_refl (Rel 1) : Rel 1 = 0]
45 does need the body.)
46
47 - the map should be fast.
48
49 The first 2 points just mean we need a sufficiently precise equality test.
50
51 To distinguish terms according to their context, we annotate each
52 [Rel] subterm with their corresponding (recursively annotated)
53 binder (ignoring the name).
54
55 In practice we have an indirection such that each annotated binder
56 is associated with a unique [int]. It's not clear how useful this
57 is vs annotating with the actual binder data but it does allow
58 handling unknow binders by just generating a fresh int (cf [push_unknown_rel]).
59
60 While annotating [Rel]s we also share identical (for our equality)
61 subterms and annotate each subterm with its hash, ie we hashcons
62 according to our finer-than-[Constr.equal] equality. This means we
63 can lookup by hash, and since identical subterms are shared we can
64 compare them by [(==)] (in practice [hasheq_kind] which does
65 [(==)] on immediate subterms) instead of structural equality
66 (which would be O(size of term)).
67
68 Finally we keep a reference count so that we can avoid caching
69 subterms which aren't repeated.
70 *)
71
72 module Self = struct
73
74 type t = {
75 self : constr;
76 kind : (t,t,Sorts.t,UVars.Instance.t,Sorts.relevance) kind_of_term;
77 isRel : int (* 0 -> not a rel, otherwise unique identifier of that binder *);
78 hash : int;
79 mutable refcount : int;
80 }
81
82 (* XXX possibly should be just physical equality since we use
83 [raw_equal] on not-yet-hashconsed terms *)
84 let equal a b =
85 a.isRel == b.isRel
86 && hasheq_kind a.kind b.kind
87
88 let hash x = x.hash
89
90 end
91
92 include Self
93
94 let raw_equal a ~isRel ~kind =
95 a.isRel == isRel
96 && hasheq_kind a.kind kind
97
98 let self x = x.self
99
100 let refcount x = x.refcount
101
102 module Tbl = struct
103 type key = t
104
105 (* The API looks like Hashtbl but implemented using Int.Map ref.
106
107 We don't use Hashtbl for 2 reasons:
108 - to provide the pre-hashconsing leaf lookup (not sure why it's so fast but it seems to be)
109 (although note we could do this with Hashtbl by using something like
110 [type key = Real of t | Fake of int (* hash *) * (t -> bool)],
111 equality between [Real] and [Fake] uses the predicate in [Fake],
112 wrap [add] so that we only add [Real] keys,
113 then [raw_find] is [Hashtbl.find_opt] using [Fake].)
114
115 - for unclear reasons Int.Map ref is dramatically faster on an artificial example
116 (balanced binary tree whose leaves are all different primitive ints,
117 such that there is no sharing).
118 It is a bit slower in the real world.
119 It seems that hashtbl produces overly large buckets which then need to be linearly scanned.
120 hconsing doesn't seem to have this problem,
121 perhaps because of differences between hashtbl and our hashset implementation. *)
122 type 'a t = (key * 'a) list Int.Map.t ref
123
124 let create () = ref Int.Map.empty
125
126 let add tbl key v =
127 tbl := Int.Map.update key.hash (function
128 | None -> Some [(key,v)]
129 | Some l -> Some ((key,v)::l))
130 !tbl
131
132 let raw_find tbl h p =
133 match Int.Map.find_opt h !tbl with
134 | None -> None
135 | Some l -> List.find_map (fun (k,v) -> if p k then Some v else None) l
136
137 let find_opt tbl key =
138 match Int.Map.find_opt key.hash !tbl with
139 | None -> None
140 | Some l ->
141 List.find_map (fun (k',v) ->
142 if equal key k' then Some v else None)
143 l
144
145 type stats = {
146 hashes : int;
147 bindings : int;
148 most_collisions : int;
149 }
150
151 let empty_stats = {
152 hashes = 0;
153 bindings = 0;
154 most_collisions = 0;
155 }
156
157 let stats tbl =
158 Int.Map.fold (fun _ l acc ->
159 let len = List.length l in
160 {
161 hashes = acc.hashes + 1;
162 bindings = acc.bindings + len;
163 most_collisions = max acc.most_collisions len;
164 }
165 )
166 !tbl
167 empty_stats
168
169 end
170
171 type henv = {
172 (* only used for globals, rel context is not correct *)
173 globals : Environ.env;
174 (* table of reified terms *)
175 tbl : t Tbl.t;
176 (* debug counter *)
177 steps : int ref;
178 (* unique identifiers for each binder crossed *)
179 rels : int Range.t;
180 (* counter to generate uids for binders *)
181 binder_cnt : int ref;
182 (* how many unknown_rel we have seen *)
183 unknown_cnt : int ref;
184 assum_uids : int Tbl.t;
185 (* the surrounding table is for the body, the inner table for the type *)
186 letin_uids : int Tbl.t Tbl.t;
187 }
188
189 let empty_env env = {
190 globals = env;
191 tbl = Tbl.create ();
192 steps = ref 0;
193 rels = Range.empty;
194 binder_cnt = ref 0;
195 unknown_cnt = ref 0;
196 assum_uids = Tbl.create ();
197 letin_uids = Tbl.create ();
198 }
199
200 (* still used in fixpoint *)
201 let push_unknown_rel env =
202 incr env.binder_cnt;
203 incr env.unknown_cnt;
204 { env with rels = Range.cons !(env.binder_cnt) env.rels }
205
206 let push_assum t env =
207 let uid = match Tbl.find_opt env.assum_uids t with
208 | Some uid -> uid
209 | None ->
210 incr env.binder_cnt;
211 let uid = !(env.binder_cnt) in
212 Tbl.add env.assum_uids t uid;
213 uid
214 in
215 { env with rels = Range.cons uid env.rels }
216
217 let push_rec ts env =
218 (* handling the lifting for mutual fixpoints doesn't seem worth the effort *)
219 Array.fold_left_i (fun i env t ->
220 if i = 0 then push_assum t env
221 else push_unknown_rel env)
222 env
223 ts
224
225 let push_letin ~body ~typ env =
226 let uid = match Tbl.find_opt env.letin_uids body with
227 | Some tbl -> begin match Tbl.find_opt tbl typ with
228 | Some uid -> uid
229 | None ->
230 incr env.binder_cnt;
231 let uid = !(env.binder_cnt) in
232 Tbl.add tbl typ uid;
233 uid
234 end
235 | None ->
236 incr env.binder_cnt;
237 let uid = !(env.binder_cnt) in
238 let tbl = Tbl.create () in
239 Tbl.add tbl typ uid;
240 Tbl.add env.letin_uids body tbl;
241 uid
242 in
243 { env with rels = Range.cons uid env.rels }
244
245 module RelDecl = Context.Rel.Declaration
246
247 let push_decl d env = match d with
248 | RelDecl.LocalAssum (_,t) -> push_assum t env
249 | RelDecl.LocalDef (_,body,typ) -> push_letin ~body ~typ env
250
251 let hash_annot = hash_annot Name.hash
252
253 let hash_array hashf a = Array.fold_left (fun hash x -> Hashset.Combine.combine hash (hashf x)) 0 a
254
255 let hash_kind = let open Hashset.Combine in function
256 | Var i -> combinesmall 1 (Id.hash i)
257 | Sort s -> combinesmall 2 (Sorts.hash s)
258 | Cast (c,k,t) -> combinesmall 3 (combine3 c.hash (hash_cast_kind k) t.hash)
259 | Prod (na,t,c) -> combinesmall 4 (combine3 (hash_annot na) t.hash c.hash)
260 | Lambda (na,t,c) -> combinesmall 5 (combine3 (hash_annot na) t.hash c.hash)
261 | LetIn (na,b,t,c) -> combinesmall 6 (combine4 (hash_annot na) b.hash t.hash c.hash)
262 | App (h,args) -> combinesmall 7 (Array.fold_left (fun hash c -> combine hash c.hash) h.hash args)
263 | Evar _ -> assert false
264 | Const (c,u) -> combinesmall 9 (combine (Constant.UserOrd.hash c) (UVars.Instance.hash u))
265 | Ind (ind,u) -> combinesmall 10 (combine (Ind.UserOrd.hash ind) (UVars.Instance.hash u))
266 | Construct (c,u) -> combinesmall 11 (combine (Construct.UserOrd.hash c) (UVars.Instance.hash u))
267 | Case (_,u,pms,(p,_),_,c,bl) ->
268 let hash_ctx (bnd,c) =
269 Array.fold_left (fun hash na -> combine (hash_annot na) hash) c.hash bnd
270 in
271 let hpms = hash_array hash pms in
272 let hbl = hash_array hash_ctx bl in
273 let h = combine5 (UVars.Instance.hash u)
274 c.hash hpms (hash_ctx p) hbl
275 in
276 combinesmall 12 h
277 | Fix (_,(lna,tl,bl)) ->
278 combinesmall 13 (combine3 (hash_array hash_annot lna) (hash_array hash tl) (hash_array hash bl))
279 | CoFix (_,(lna,tl,bl)) ->
280 combinesmall 14 (combine3 (hash_array hash_annot lna) (hash_array hash tl) (hash_array hash bl))
281 | Meta _ -> assert false
282 | Rel n -> combinesmall 16 n
283 | Proj (p,_,c) -> combinesmall 17 (combine (Projection.UserOrd.hash p) c.hash)
284 | Int i -> combinesmall 18 (Uint63.hash i)
285 | Float f -> combinesmall 19 (Float64.hash f)
286 | String s -> combinesmall 20 (Pstring.hash s)
287 | Array (u,t,def,ty) -> combinesmall 21 (combine4 (UVars.Instance.hash u) (hash_array hash t) def.hash ty.hash)
288
289 let kind_to_constr = function
290 | Rel n -> mkRel n
291 | Var i -> mkVar i
292 | Meta _ | Evar _ -> assert false
293 | Sort s -> mkSort s
294 | Cast (c,k,t) -> mkCast (c.self,k,t.self)
295 | Prod (na,t,c) -> mkProd (na,t.self,c.self)
296 | Lambda (na,t,c) -> mkLambda (na,t.self,c.self)
297 | LetIn (na,b,t,c) -> mkLetIn (na,b.self,t.self,c.self)
298 | App (h,args) -> mkApp (h.self, Array.map self args)
299 | Const cu -> mkConstU cu
300 | Ind iu -> mkIndU iu
301 | Construct cu -> mkConstructU cu
302 | Case (ci,u,pms,(p,r),iv,c,bl) ->
303 let to_ctx (bnd,c) = bnd, c.self in
304 let iv = match iv with
305 | NoInvert -> NoInvert
306 | CaseInvert x -> CaseInvert {indices=Array.map self x.indices}
307 in
308 mkCase (ci,u,Array.map self pms,(to_ctx p,r),iv,c.self,Array.map to_ctx bl)
309 | Fix (ln,(lna,tl,bl)) ->
310 mkFix (ln,(lna,Array.map self tl,Array.map self bl))
311 | CoFix (ln,(lna,tl,bl)) ->
312 mkCoFix (ln,(lna,Array.map self tl,Array.map self bl))
313 | Proj (p,r,c) -> mkProj (p,r,c.self)
314 | Int i -> mkInt i
315 | Float f -> mkFloat f
316 | String s -> mkString s
317 | Array (u,t,def,ty) -> mkArray (u,Array.map self t,def.self,ty.self)
318
319 let of_kind_nohashcons = function
320 | App (c, [||]) -> c
321 | kind ->
322 let self = kind_to_constr kind in
323 let hash = hash_kind kind in
324 let () = match kind with
325 | Rel _ -> assert false
326 | _ -> ()
327 in
328 { self; kind; hash; isRel = 0; refcount = 1 }
329
330 let eq_leaf c c' = match kind c, c'.kind with
331 | Var i, Var i' -> Id.equal i i'
332 | Const (c,u), Const (c',u') -> Constant.UserOrd.equal c c' && UVars.Instance.equal u u'
333 | Ind (i,u), Ind (i',u') -> Ind.UserOrd.equal i i' && UVars.Instance.equal u u'
334 | Construct (c,u), Construct (c',u') -> Construct.UserOrd.equal c c' && UVars.Instance.equal u u'
335 | _ -> false
336
337 let nonrel_leaf tbl c = match kind c with
338 | Rel _ -> None
339 | Var _ | Const _ | Ind _ | Construct _ as k ->
340 let h = hash_kind k in
341 Tbl.raw_find tbl h (fun c' -> eq_leaf c c')
342 | _ -> None
343
344 let rec of_constr henv c =
345 incr henv.steps;
346 match nonrel_leaf henv.tbl c with
347 | Some v -> v
348 | None ->
349 let kind = of_constr_aux henv c in
350 let hash = hash_kind kind in
351 let isRel, hash = match kind with
352 | Rel n ->
353 let uid = Range.get henv.rels (n-1) in
354 assert (uid <> 0);
355 uid, Hashset.Combine.combine uid hash
356 | _ -> 0, hash
357 in
358 match Tbl.raw_find henv.tbl hash (fun c' -> raw_equal c' ~isRel ~kind) with
359 | Some c' -> c'.refcount <- c'.refcount + 1; c'
360 | None ->
361 let c =
362 let self = kind_to_constr kind in
363 let self = if hasheq_kind (Constr.kind self) (Constr.kind c) then c else self in
364 { self; kind; hash; isRel; refcount = 1 }
365 in
366 Tbl.add henv.tbl c c; c
367
368 and of_constr_aux henv c =
369 match kind c with
370 | Var i ->
371 let _, i = Id.hcons i in
372 Var i
373 | Rel _ as t -> t
374 | Sort s ->
375 let _, s = Sorts.hcons s in
376 Sort s
377 | Cast (c,k,t) ->
378 let c = of_constr henv c in
379 let t = of_constr henv t in
380 Cast (c, k, t)
381 | Prod (na,t,c) ->
382 let _, na = hcons_annot na in
383 let t = of_constr henv t in
384 let c = of_constr (push_assum t henv) c in
385 Prod (na, t, c)
386 | Lambda (na, t, c) ->
387 let _, na = hcons_annot na in
388 let t = of_constr henv t in
389 let c = of_constr (push_assum t henv) c in
390 Lambda (na,t,c)
391 | LetIn (na,b,t,c) ->
392 let _, na = hcons_annot na in
393 let b = of_constr henv b in
394 let t = of_constr henv t in
395 let c = of_constr (push_letin ~body:b ~typ:t henv) c in
396 LetIn (na,b,t,c)
397 | App (h,args) ->
398 let h = of_constr henv h in
399 let args = Array.map (of_constr henv) args in
400 App (h, args)
401 | Evar _ -> CErrors.anomaly Pp.(str "evar in typeops")
402 | Meta _ -> CErrors.anomaly Pp.(str "meta in typeops")
403 | Const (c,u) ->
404 let _, c = hcons_con c in
405 let _, u = UVars.Instance.hcons u in
406 Const (c,u)
407 | Ind (ind,u) ->
408 let _, ind = hcons_ind ind in
409 let _, u = UVars.Instance.hcons u in
410 Ind (ind,u)
411 | Construct (c,u) ->
412 let _, c = hcons_construct c in
413 let _, u = UVars.Instance.hcons u in
414 Construct (c,u)
415 | Case (ci,u,pms,(p,r),iv,c,bl) ->
416 let pctx, blctx =
417 let specif = Inductive.lookup_mind_specif henv.globals ci.ci_ind in
418 let pctx = Inductive.expand_arity specif (ci.ci_ind,u) pms (fst p) in
419 let blctx = Inductive.expand_branch_contexts specif u pms bl in
420 pctx, blctx
421 in
422 let of_ctx (bnd, c) bnd' =
423 let _, bnd = Hashcons.hashcons_array hcons_annot bnd in
424 let henv = push_rel_context henv bnd' in
425 let c = of_constr henv c in
426 bnd, c
427 in
428 let _, ci = hcons_caseinfo ci in
429 let _, u = UVars.Instance.hcons u in
430 let pms = Array.map (of_constr henv) pms in
431 let p = of_ctx p pctx in
432 let iv = match iv with
433 | NoInvert -> NoInvert
434 | CaseInvert {indices} -> CaseInvert {indices=Array.map (of_constr henv) indices}
435 in
436 let c = of_constr henv c in
437 let bl = Array.map2 of_ctx bl blctx in
438 Case (ci,u,pms,(p,r),iv,c,bl)
439 | Fix (ln,(lna,tl,bl)) ->
440 let _, lna = Hashcons.hashcons_array hcons_annot lna in
441 let tl = Array.map (of_constr henv) tl in
442 let body_env = push_rec tl henv in
443 let bl = Array.map (of_constr body_env) bl in
444 Fix (ln,(lna,tl,bl))
445 | CoFix (ln,(lna,tl,bl)) ->
446 let _, lna = Hashcons.hashcons_array hcons_annot lna in
447 let tl = Array.map (of_constr henv) tl in
448 let body_env = push_rec tl henv in
449 let bl = Array.map (of_constr body_env) bl in
450 CoFix (ln,(lna,tl,bl))
451 | Proj (p,r,c) ->
452 let _, p = Projection.hcons p in
453 let c = of_constr henv c in
454 Proj (p,r,c)
455 | Int _ as t -> t
456 | Float _ as t -> t
457 | String _ as t -> t
458 | Array (u,t,def,ty) ->
459 let _, u = UVars.Instance.hcons u in
460 let t = Array.map (of_constr henv) t in
461 let def = of_constr henv def in
462 let ty = of_constr henv ty in
463 Array (u,t,def,ty)
464
465 and push_rel_context henv ctx =
466 List.fold_right (fun d henv ->
467 let d = RelDecl.map_constr_het (fun r -> r) (of_constr henv) d in
468 push_decl d henv)
469 ctx
470 henv
471
472 let dbg = CDebug.create ~name:"hconstr" ()
473
474 let tree_size c =
475 let rec aux size c =
476 Constr.fold aux (size+1) c
477 in
478 aux 0 c
479
480 let of_constr env c =
481 let henv = empty_env env in
482 let henv = iterate push_unknown_rel (Environ.nb_rel env) henv in
483 let c = NewProfile.profile "HConstr.of_constr" (fun () -> of_constr henv c) () in
484 dbg Pp.(fun () ->
485 let stats = Tbl.stats henv.tbl in
486 let tree_size = tree_size (self c) in
487 v 0 (
488 str "steps = " ++ int !(henv.steps) ++ spc() ++
489 str "rel cnt = " ++ int !(henv.binder_cnt) ++ spc() ++
490 str "unknwown rels = " ++ int !(henv.unknown_cnt) ++ spc() ++
491 str "hashes = " ++ int stats.Tbl.hashes ++ spc() ++
492 str "bindings = " ++ int stats.Tbl.bindings ++ spc() ++
493 str "tree size = " ++ int tree_size ++ spc() ++
494 str "most_collisions = " ++ int stats.Tbl.most_collisions
495 )
496 );
497 c
498
499 let kind x = x.kind
500
501 let hcons x =
502 let tbl = Tbl.create () in
503 let module HCons = GenHCons(struct
504 type nonrec t = t
505 let kind = kind
506 let self = self
507 let refcount = refcount
508 let via_hconstr = true
509 module Tbl = struct
510 let find_opt x = Tbl.find_opt tbl x
511 let add x y = Tbl.add tbl x y
512 end
513 end) in
514 HCons.hcons x