Debian Codegraph @

lib/acyclicGraph.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 type constraint_type = Lt | Le | Eq
12
13 module type Point = sig
14 type t
15
16 module Set : CSig.USetS with type elt = t
17 module Map : CMap.UExtS with type key = t and module Set := Set
18
19 val equal : t -> t -> bool
20 val compare : t -> t -> int
21
22 val raw_pr : t -> Pp.t
23
24 val anomaly_err : t -> Pp.t
25 end
26
27 module Make (Point:Point) = struct
28
29 (* Created in Caml by Gérard Huet for CoC 4.8 [Dec 1988] *)
30 (* Functional code by Jean-Christophe Filliâtre for Coq V7.0 [1999] *)
31 (* Extension with algebraic universes by HH for Coq V7.0 [Sep 2001] *)
32 (* Additional support for sort-polymorphic inductive types by HH [Mar 2006] *)
33 (* Support for universe polymorphism by MS [2014] *)
34
35 (* Revisions by Bruno Barras, Hugo Herbelin, Pierre Letouzey, Matthieu
36 Sozeau, Pierre-Marie Pédrot, Jacques-Henri Jourdan *)
37
38 (* Points are stratified by a partial ordering $\le$.
39 Let $\~{}$ be the associated equivalence. We also have a strict ordering
40 $<$ between equivalence classes, and we maintain that $<$ is acyclic,
41 and contained in $\le$ in the sense that $[U]<[V]$ implies $U\le V$.
42
43 At every moment, we have a finite number of points, and we
44 maintain the ordering in the presence of assertions $U<V$ and $U\le V$.
45
46 The equivalence $\~{}$ is represented by a tree structure, as in the
47 union-find algorithm. The assertions $<$ and $\le$ are represented by
48 adjacency lists.
49
50 We use the algorithm described in the paper:
51
52 Bender, M. A., Fineman, J. T., Gilbert, S., & Tarjan, R. E. (2011). A
53 new approach to incremental cycle detection and related
54 problems. arXiv preprint arXiv:1112.0784.
55
56 *)
57
58 module Index :
59 sig
60 type t
61 val equal : t -> t -> bool
62 module Set : CSig.SetS with type elt = t
63 module Map : CMap.ExtS with type key = t and module Set := Set
64 type table
65 val empty : table
66 val fresh : Point.t -> table -> t * table
67 val mem : Point.t -> table -> bool
68 val find : Point.t -> table -> t
69 val repr : t -> table -> Point.t
70 val hash : t -> int
71 end =
72 struct
73 type t = int
74 let equal = Int.equal
75 module Set = Int.Set
76 module Map = Int.Map
77
78 type table = {
79 tab_len : int;
80 tab_fwd : Point.t Int.Map.t;
81 tab_bwd : int Point.Map.t
82 }
83
84 let empty = {
85 tab_len = 0;
86 tab_fwd = Int.Map.empty;
87 tab_bwd = Point.Map.empty;
88 }
89 let mem x t = Point.Map.mem x t.tab_bwd
90 let find x t = Point.Map.find x t.tab_bwd
91 let repr n t = Int.Map.find n t.tab_fwd
92
93 let fresh x t =
94 let () = assert (not @@ mem x t) in
95 let n = t.tab_len in
96 n, {
97 tab_len = n + 1;
98 tab_fwd = Int.Map.add n x t.tab_fwd;
99 tab_bwd = Point.Map.add x n t.tab_bwd;
100 }
101 let hash x = x
102 end
103
104 module PMap = Index.Map
105 module PSet = Index.Set
106
107 (* Comparison on this type is pointer equality *)
108 type canonical_node =
109 { canon: Index.t;
110 ltle: bool PMap.t; (* true: strict (lt) constraint.
111 false: weak (le) constraint. *)
112 gtge: PSet.t;
113 rank : int;
114 klvl: int;
115 ilvl: int;
116 }
117
118 (* A Point.t is either an alias for another one, or a canonical one,
119 for which we know the points that are above *)
120
121 type entry =
122 | Canonical of canonical_node
123 | Equiv of Index.t
124
125 type t =
126 { entries : entry PMap.t;
127 index : int;
128 n_nodes : int; n_edges : int;
129 table : Index.table }
130
131 module CN = struct
132 type t = canonical_node
133 let equal x y = x.canon == y.canon
134 let hash x = Index.hash x.canon
135 end
136
137 module Status = struct
138 module Internal = Hashtbl.Make(CN)
139
140 (** we could experiment with creation size based on the size of [g] *)
141 let create (g:t) = Internal.create 17
142
143 let mem = Internal.mem
144 let find = Internal.find
145 let replace = Internal.replace
146 let fold = Internal.fold
147 end
148
149 (* Every Point.t has a unique canonical arc representative *)
150
151 (* Low-level function : makes u an alias for v.
152 Does not removes edges from n_edges, but decrements n_nodes.
153 u should be entered as canonical before. *)
154 let enter_equiv g u v =
155 { entries =
156 PMap.modify u (fun _ a ->
157 match a with
158 | Canonical n ->
159 Equiv v
160 | _ -> assert false) g.entries;
161 index = g.index;
162 n_nodes = g.n_nodes - 1;
163 n_edges = g.n_edges;
164 table = g.table }
165
166 (* Low-level function : changes data associated with a canonical node.
167 Resets the mutable fields in the old record, in order to avoid breaking
168 invariants for other users of this record.
169 n.canon should already been inserted as a canonical node. *)
170 let change_node g n =
171 { g with entries =
172 PMap.modify n.canon
173 (fun _ a ->
174 match a with
175 | Canonical _ ->
176 Canonical n
177 | _ -> assert false)
178 g.entries }
179
180 (* canonical representative : we follow the Equiv links *)
181 let rec repr g u =
182 match PMap.find u g.entries with
183 | Equiv v -> repr g v
184 | Canonical arc -> arc
185
186 let repr_node g u =
187 try repr g (Index.find u g.table)
188 with Not_found ->
189 CErrors.anomaly (Point.anomaly_err u)
190
191 exception AlreadyDeclared
192
193 (* Reindexes the given point, using the next available index. *)
194 let use_index g u =
195 let u = repr g u in
196 let g = change_node g { u with ilvl = g.index } in
197 assert (g.index > min_int);
198 { g with index = g.index - 1 }
199
200 (* Returns 1 if u is higher than v in topological order.
201 -1 lower
202 0 if u = v *)
203 let topo_compare u v =
204 if u.klvl > v.klvl then 1
205 else if u.klvl < v.klvl then -1
206 else if u.ilvl > v.ilvl then 1
207 else if u.ilvl < v.ilvl then -1
208 else (assert (u==v); 0)
209
210 (* Checks most of the invariants of the graph. For debugging purposes. *)
211 let check_invariants ~required_canonical g =
212 let required_canonical u = required_canonical (Index.repr u g.table) in
213 let n_edges = ref 0 in
214 let n_nodes = ref 0 in
215 PMap.iter (fun l u ->
216 match u with
217 | Canonical u ->
218 PMap.iter (fun v _strict ->
219 incr n_edges;
220 let v = repr g v in
221 assert (topo_compare u v = -1);
222 if u.klvl = v.klvl then
223 assert (PSet.mem u.canon v.gtge ||
224 PSet.exists (fun l -> u == repr g l) v.gtge))
225 u.ltle;
226 PSet.iter (fun v ->
227 let v = repr g v in
228 assert (v.klvl = u.klvl &&
229 (PMap.mem u.canon v.ltle ||
230 PMap.exists (fun l _ -> u == repr g l) v.ltle))
231 ) u.gtge;
232 assert (Index.equal l u.canon);
233 assert (u.ilvl > g.index);
234 assert (not (PMap.mem u.canon u.ltle));
235 incr n_nodes
236 | Equiv _ -> assert (not (required_canonical l)))
237 g.entries;
238 assert (!n_edges = g.n_edges);
239 assert (!n_nodes = g.n_nodes)
240
241 let clean_ltle g ltle =
242 PMap.fold (fun u strict acc ->
243 let uu = (repr g u).canon in
244 if Index.equal uu u then acc
245 else (
246 let acc = PMap.remove u (fst acc) in
247 if not strict && PMap.mem uu acc then (acc, true)
248 else (PMap.add uu strict acc, true)))
249 ltle (ltle, false)
250
251 let clean_gtge g gtge =
252 PSet.fold (fun u acc ->
253 let uu = (repr g u).canon in
254 if Index.equal uu u then acc
255 else PSet.add uu (PSet.remove u (fst acc)), true)
256 gtge (gtge, false)
257
258 (* [get_ltle] and [get_gtge] return ltle and gtge arcs.
259 Moreover, if one of these lists is dirty (e.g. points to a
260 non-canonical node), these functions clean this node in the
261 graph by removing some duplicate edges *)
262 let get_ltle g u =
263 let ltle, chgt_ltle = clean_ltle g u.ltle in
264 if not chgt_ltle then u.ltle, u, g
265 else
266 let sz = PMap.cardinal u.ltle in
267 let sz2 = PMap.cardinal ltle in
268 let u = { u with ltle } in
269 let g = change_node g u in
270 let g = { g with n_edges = g.n_edges + sz2 - sz } in
271 u.ltle, u, g
272
273 let get_gtge g u =
274 let gtge, chgt_gtge = clean_gtge g u.gtge in
275 if not chgt_gtge then u.gtge, u, g
276 else
277 let u = { u with gtge } in
278 let g = change_node g u in
279 u.gtge, u, g
280
281 exception AbortBackward of t
282 exception CycleDetected
283
284 (* Implementation of the algorithm described in § 5.1 of the following paper:
285
286 Bender, M. A., Fineman, J. T., Gilbert, S., & Tarjan, R. E. (2011). A
287 new approach to incremental cycle detection and related
288 problems. arXiv preprint arXiv:1112.0784.
289
290 The "STEP X" comments contained in this file refers to the
291 corresponding step numbers of the algorithm described in Section
292 5.1 of this paper. *)
293
294 let rec backward_traverse status b_traversed count g x =
295 let count = count - 1 in
296 if count < 0 then begin
297 raise_notrace (AbortBackward g)
298 end;
299 if Status.mem status x then b_traversed, count, g
300 else begin
301 Status.replace status x ();
302 let gtge, x, g = get_gtge g x in
303 let b_traversed, count, g =
304 PSet.fold (fun y (b_traversed, count, g) ->
305 let y = repr g y in
306 backward_traverse status b_traversed count g y)
307 gtge (b_traversed, count, g)
308 in
309 x.canon::b_traversed, count, g
310 end
311
312 let backward_traverse count g x = backward_traverse (Status.create g) [] count g x
313
314 let rec forward_traverse f_traversed g v_klvl x y =
315 let y = repr g y in
316 if y.klvl < v_klvl then begin
317 let y = { y with klvl = v_klvl;
318 gtge = if x == y then PSet.empty
319 else PSet.singleton x.canon }
320 in
321 let g = change_node g y in
322 let ltle, y, g = get_ltle g y in
323 let f_traversed, g =
324 PMap.fold (fun z _ (f_traversed, g) ->
325 forward_traverse f_traversed g v_klvl y z)
326 ltle (f_traversed, g)
327 in
328 y.canon::f_traversed, g
329 end else if y.klvl = v_klvl && x != y then
330 let g = change_node g
331 { y with gtge = PSet.add x.canon y.gtge } in
332 f_traversed, g
333 else f_traversed, g
334
335 let rec find_to_merge status g x v =
336 let x = repr g x in
337 match Status.find status x with
338 | merge -> merge
339 | exception Not_found ->
340 if Index.equal x.canon v then begin
341 Status.replace status x true;
342 true
343 end
344 else
345 begin
346 let merge = PSet.fold
347 (fun y merge ->
348 let merge' = find_to_merge status g y v in
349 merge' || merge) x.gtge false
350 in
351 Status.replace status x merge;
352 merge
353 end
354
355 let find_to_merge g x v =
356 let status = Status.create g in
357 status, find_to_merge status g x v
358
359 let rec find_max_rank cur accu l = match l with
360 | [] -> cur, accu
361 | hd :: tl ->
362 if hd.rank > cur.rank then find_max_rank hd (cur :: accu) tl
363 else find_max_rank cur (hd :: accu) tl
364
365 let get_new_edges g to_merge =
366 (* Computing edge sets. *)
367 let ltle =
368 let fold acc n =
369 let fold u strict acc =
370 match PMap.find u acc with
371 | true -> acc
372 | false -> if strict then PMap.add u true acc else acc
373 | exception Not_found -> PMap.add u strict acc
374 in
375 PMap.fold fold n.ltle acc
376 in
377 let max, rem = match to_merge with
378 | [] -> assert false
379 | hd :: tl -> find_max_rank hd [] tl
380 in
381 List.fold_left fold max.ltle rem
382 in
383 let ltle, _ = clean_ltle g ltle in
384 let fold accu a =
385 match PMap.find a.canon ltle with
386 | true ->
387 (* There is a lt edge inside the new component. This is a
388 "bad cycle". *)
389 raise_notrace CycleDetected
390 | false -> PMap.remove a.canon accu
391 | exception Not_found -> accu
392 in
393 let ltle = List.fold_left fold ltle to_merge in
394 let gtge =
395 List.fold_left (fun acc n -> PSet.union acc n.gtge)
396 PSet.empty to_merge
397 in
398 let gtge, _ = clean_gtge g gtge in
399 let gtge = List.fold_left (fun acc n -> PSet.remove n.canon acc) gtge to_merge in
400 (ltle, gtge)
401
402
403 let reorder g u v =
404 (* STEP 2: backward search in the k-level of u. *)
405
406 (* [v_klvl] is the chosen future level for u, v and all
407 traversed nodes. *)
408 let b_traversed, v_klvl, g =
409 let u = repr g u in
410 try
411 let b_traversed, _, g = backward_traverse (u.klvl + 1) g u in
412 let v_klvl = u.klvl in
413 b_traversed, v_klvl, g
414 with AbortBackward g ->
415 (* Backward search was too long, use the next k-level. *)
416 let v_klvl = u.klvl + 1 in
417 [], v_klvl, g
418 in
419 let f_traversed, g =
420 (* STEP 3: forward search. Contrary to what is described in
421 the paper, we do not test whether v_klvl = u.klvl nor we assign
422 v_klvl to v.klvl. Indeed, the first call to forward_traverse
423 will do all that. *)
424 forward_traverse [] g v_klvl (repr g v) v
425 in
426
427 (* STEP 4: merge nodes if needed. *)
428 let to_merge, b_reindex, f_reindex =
429 if (repr g u).klvl = v_klvl then
430 begin
431 let status, merge = find_to_merge g u v in
432 if merge then
433 let not_merged u = try not (Status.find status (repr g u)) with Not_found -> true in
434 Status.fold (fun u merged acc -> if merged then u::acc else acc) status [],
435 List.filter not_merged b_traversed,
436 List.filter not_merged f_traversed
437 else [], b_traversed, f_traversed
438 end
439 else [], b_traversed, f_traversed
440 in
441 let to_reindex, g =
442 match to_merge with
443 | [] -> List.rev_append f_reindex b_reindex, g
444 | n0::q0 ->
445 (* Computing new root. *)
446 let root, rank_rest =
447 List.fold_left (fun ((best, _rank_rest) as acc) n ->
448 if n.rank >= best.rank then n, best.rank else acc)
449 (n0, min_int) q0
450 in
451 let ltle, gtge = get_new_edges g to_merge in
452 (* Inserting the new root. *)
453 let g = change_node g
454 { root with ltle; gtge;
455 rank = max root.rank (rank_rest + 1); }
456 in
457
458 (* Inserting shortcuts for old nodes. *)
459 let g = List.fold_left (fun g n ->
460 if Index.equal n.canon root.canon then g else enter_equiv g n.canon root.canon)
461 g to_merge
462 in
463
464 (* Updating g.n_edges *)
465 let oldsz =
466 List.fold_left (fun sz u -> sz+PMap.cardinal u.ltle)
467 0 to_merge
468 in
469 let sz = PMap.cardinal ltle in
470 let g = { g with n_edges = g.n_edges + sz - oldsz } in
471
472 (* Not clear in the paper: we have to put the newly
473 created component just between B and F. *)
474 List.rev_append f_reindex (root.canon::b_reindex), g
475
476 in
477
478 (* STEP 5: reindex traversed nodes. *)
479 List.fold_left use_index g to_reindex
480
481 (* Assumes [u] and [v] are already in the graph. *)
482 (* Does NOT assume that ucan != vcan. *)
483 let insert_edge strict ucan vcan g =
484 try
485 let u = ucan.canon and v = vcan.canon in
486 (* STEP 1: do we need to reorder nodes ? *)
487 let g = if topo_compare ucan vcan <= 0 then g else reorder g u v in
488
489 (* STEP 6: insert the new edge in the graph. *)
490 let u = repr g u in
491 let v = repr g v in
492 if u == v then
493 if strict then raise_notrace CycleDetected else g
494 else
495 let g =
496 try let oldstrict = PMap.find v.canon u.ltle in
497 if strict && not oldstrict then
498 change_node g { u with ltle = PMap.add v.canon true u.ltle }
499 else g
500 with Not_found ->
501 { (change_node g { u with ltle = PMap.add v.canon strict u.ltle })
502 with n_edges = g.n_edges + 1 }
503 in
504 if u.klvl <> v.klvl || PSet.mem u.canon v.gtge then g
505 else
506 let v = { v with gtge = PSet.add u.canon v.gtge } in
507 change_node g v
508 with
509 | CycleDetected as e -> raise_notrace e
510
511 let add ?(rank=0) v g =
512 if Index.mem v g.table then raise AlreadyDeclared
513 else
514 let () = assert (g.index > min_int) in
515 let v, table = Index.fresh v g.table in
516 let node = {
517 canon = v;
518 ltle = PMap.empty;
519 gtge = PSet.empty;
520 rank;
521 klvl = 0;
522 ilvl = g.index;
523 }
524 in
525 let entries = PMap.add v (Canonical node) g.entries in
526 { entries; index = g.index - 1; n_nodes = g.n_nodes + 1; n_edges = g.n_edges; table }
527
528 let check_declared g us =
529 let check l = not (Index.mem l g.table) in
530 let undeclared = Point.Set.filter check us in
531 if Point.Set.is_empty undeclared then Ok ()
532 else Error undeclared
533
534 exception Found_explanation of (constraint_type * Point.t) list
535
536 type explanation = Point.t * (constraint_type * Point.t) list
537
538 let get_explanation strict pu pv g =
539 let v = repr_node g pv in
540 let visited_strict = ref PMap.empty in
541 let rec traverse strict u =
542 if u == v then
543 if strict then None else Some []
544 else if topo_compare u v = 1 then None
545 else
546 let visited =
547 try not (PMap.find u.canon !visited_strict) || strict
548 with Not_found -> false
549 in
550 if visited then None
551 else begin
552 visited_strict := PMap.add u.canon strict !visited_strict;
553 try
554 PMap.iter (fun u' strictu' ->
555 match traverse (strict && not strictu') (repr g u') with
556 | None -> ()
557 | Some exp ->
558 let typ = if strictu' then Lt else Le in
559 let exp = if CList.is_empty exp then [typ, pv] else
560 let u' = Index.repr u' g.table in
561 (typ, u') :: exp
562 in
563 raise_notrace (Found_explanation exp))
564 u.ltle;
565 None
566 with Found_explanation exp -> Some exp
567 end
568 in
569 let u = repr_node g pu in
570 if u == v then begin assert (not strict); [(Eq, pv)] end
571 else match traverse strict u with Some exp -> exp | None -> assert false
572
573 let get_explanation strict u v g = u, get_explanation strict u v g
574
575 (* To compare two nodes, we simply do a forward search.
576 We implement two improvements:
577 - we ignore nodes that are higher than the destination;
578 - we do a BFS rather than a DFS because we expect to have a short
579 path (typically, the shortest path has length 1)
580 *)
581 exception Found
582 type visited = WeakVisited | Visited
583 let search_path strict u v g =
584 let rec loop status todo next_todo =
585 match todo, next_todo with
586 | [], [] -> () (* No path found *)
587 | [], _ -> loop status next_todo []
588 | (u, strict)::todo, _ ->
589 let is_visited = match Status.find status u with
590 | Visited -> true
591 | WeakVisited -> strict
592 | exception Not_found -> false
593 in
594 if is_visited
595 then loop status todo next_todo
596 else begin
597 Status.replace status u (if strict then WeakVisited else Visited);
598 if try PMap.find v.canon u.ltle || not strict
599 with Not_found -> false
600 then raise_notrace Found
601 else
602 begin
603 let next_todo =
604 PMap.fold (fun u strictu next_todo ->
605 let strict = not strictu && strict in
606 let u = repr g u in
607 if u == v && not strict then raise_notrace Found
608 else if topo_compare u v = 1 then next_todo
609 else (u, strict)::next_todo)
610 u.ltle next_todo
611 in
612 loop status todo next_todo
613 end
614 end
615 in
616 if u == v then not strict
617 else
618 try loop (Status.create g) [u, strict] []; false
619 with Found -> true
620
621 (** Uncomment to debug the cycle detection algorithm. *)
622 (*let insert_edge strict ucan vcan g =
623 let check_invariants = check_invariants ~required_canonical:(fun _ -> false) in
624 check_invariants g;
625 let g = insert_edge strict ucan vcan g in
626 check_invariants g;
627 let ucan = repr g ucan.canon in
628 let vcan = repr g vcan.canon in
629 assert (search_path strict ucan vcan g);
630 g*)
631
632 (** User interface *)
633
634 type 'a check_function = t -> 'a -> 'a -> bool
635
636 let check_eq g u v =
637 u == v ||
638 let arcu = repr_node g u and arcv = repr_node g v in
639 arcu == arcv
640
641 let check_smaller g strict u v =
642 search_path strict (repr_node g u) (repr_node g v) g
643
644 let check_leq g u v = check_smaller g false u v
645 let check_lt g u v = check_smaller g true u v
646
647 let get_explanation (u, c, v) g = match c with
648 | Eq ->
649 (* Redo the search, not important because this is only used for display. *)
650 if check_lt g u v then get_explanation true u v g else get_explanation true v u g
651 | Le -> get_explanation true v u g
652 | Lt -> get_explanation false v u g
653
654 (* enforce_eq g u v will force u=v if possible, will fail otherwise *)
655
656 let enforce_eq u v g =
657 let ucan = repr_node g u in
658 let vcan = repr_node g v in
659 if ucan == vcan then Some g
660 else if topo_compare ucan vcan = 1 then
661 let ucan = vcan and vcan = ucan in
662 let g = insert_edge false ucan vcan g in (* Cannot fail *)
663 try Some (insert_edge false vcan ucan g)
664 with CycleDetected -> None
665 else
666 let g = insert_edge false ucan vcan g in (* Cannot fail *)
667 try Some (insert_edge false vcan ucan g)
668 with CycleDetected -> None
669
670 (* enforce_leq g u v will force u<=v if possible, will fail otherwise *)
671 let enforce_leq u v g =
672 let ucan = repr_node g u in
673 let vcan = repr_node g v in
674 try Some (insert_edge false ucan vcan g)
675 with CycleDetected -> None
676
677 (* enforce_lt u v will force u<v if possible, will fail otherwise *)
678 let enforce_lt u v g =
679 let ucan = repr_node g u in
680 let vcan = repr_node g v in
681 try Some (insert_edge true ucan vcan g)
682 with CycleDetected -> None
683
684 let empty =
685 { entries = PMap.empty; index = 0; n_nodes = 0; n_edges = 0; table = Index.empty }
686
687 (* Normalization *)
688
689 type 'a constraint_fold = Point.t * constraint_type * Point.t -> 'a -> 'a
690
691 let constraints_of g fold accu =
692 let module UF = Unionfind.Make (Point.Set) (Point.Map) in
693 let uf = UF.create () in
694 let constraints_of u v acc =
695 match v with
696 | Canonical {canon=u; ltle; _} ->
697 PMap.fold (fun v strict acc->
698 let typ = if strict then Lt else Le in
699 let u = Index.repr u g.table in
700 let v = Index.repr v g.table in
701 fold (u,typ,v) acc) ltle acc
702 | Equiv v ->
703 let u = Index.repr u g.table in
704 let v = Index.repr v g.table in
705 UF.union u v uf; acc
706 in
707 let csts = PMap.fold constraints_of g.entries accu in
708 csts, UF.partition uf
709
710 (* domain g.entries = kept + removed *)
711 let constraints_for ~kept g fold accu =
712 (* rmap: partial map from canonical points to kept points *)
713 let add_cst u knd v cst =
714 fold (Index.repr u g.table, knd, Index.repr v g.table) cst
715 in
716 let kept = Point.Set.fold (fun u accu -> PSet.add (Index.find u g.table) accu) kept PSet.empty in
717 let rmap, csts = PSet.fold (fun u (rmap,csts) ->
718 let arcu = repr g u in
719 if PSet.mem arcu.canon kept then
720 let csts = if Index.equal u arcu.canon then csts
721 else add_cst u Eq arcu.canon csts
722 in
723 PMap.add arcu.canon arcu.canon rmap, csts
724 else
725 match PMap.find arcu.canon rmap with
726 | v -> rmap, add_cst u Eq v csts
727 | exception Not_found -> PMap.add arcu.canon u rmap, csts)
728 kept (PMap.empty, accu)
729 in
730 let rec add_from u csts todo = match todo with
731 | [] -> csts
732 | (v,strict)::todo ->
733 let v = repr g v in
734 (match PMap.find v.canon rmap with
735 | v ->
736 let d = if strict then Lt else Le in
737 let csts = add_cst u d v csts in
738 add_from u csts todo
739 | exception Not_found ->
740 (* v is not equal to any kept point *)
741 let todo = PMap.fold (fun v' strict' todo ->
742 (v',strict || strict') :: todo)
743 v.ltle todo
744 in
745 add_from u csts todo)
746 in
747 PSet.fold (fun u csts ->
748 let arc = repr g u in
749 PMap.fold (fun v strict csts -> add_from u csts [v,strict])
750 arc.ltle csts)
751 kept csts
752
753 let domain g =
754 let fold u _ accu = Point.Set.add (Index.repr u g.table) accu in
755 PMap.fold fold g.entries Point.Set.empty
756
757 let choose p g u =
758 let exception Found of Point.t in
759 let ru = (repr_node g u).canon in
760 let ruv = Index.repr ru g.table in
761 if p ruv then Some ruv
762 else
763 try PMap.iter (fun v -> function
764 | Canonical _ -> () (* we already tried [p ru] *)
765 | Equiv v' ->
766 let rv = (repr g v').canon in
767 if rv == ru then
768 let v = Index.repr v g.table in
769 if p v then raise_notrace (Found v)
770 (* NB: we could also try [p v'] but it will come up in the
771 rest of the iteration regardless. *)
772 ) g.entries; None
773 with Found v -> Some v
774
775 type node = Alias of Point.t | Node of bool Point.Map.t
776 type repr = node Point.Map.t
777
778 let repr g =
779 let fold u n accu =
780 let n = match n with
781 | Canonical n ->
782 let fold u lt accu = Point.Map.add (Index.repr u g.table) lt accu in
783 let ltle = PMap.fold fold n.ltle Point.Map.empty in
784 Node ltle
785 | Equiv u -> Alias (Index.repr u g.table)
786 in
787 Point.Map.add (Index.repr u g.table) n accu
788 in
789 PMap.fold fold g.entries Point.Map.empty
790
791 end