Debian Codegraph @

kernel/qGraph.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 open Sorts
11
12 module ElimTable = struct
13 open Quality
14
15 let const_eliminates_to q q' =
16 match q, q' with
17 | QType, _ -> true
18 | QProp, (QProp | QSProp) -> true
19 | QSProp, QSProp -> true
20 | (QProp | QSProp), _ -> false
21
22 let eliminates_to q q' =
23 match q, q' with
24 | QConstant QType, _ -> true
25 | QConstant q, QConstant q' -> const_eliminates_to q q'
26 | QVar q, QVar q' -> QVar.equal q q'
27 | (QConstant _ | QVar _), _ -> false
28 end
29
30 module G = AcyclicGraph.Make(struct
31 type t = Quality.t
32 module Set = Quality.Set
33 module Map = Quality.Map
34
35 let equal = Quality.equal
36 let compare = Quality.compare
37
38 let raw_pr = Quality.raw_pr
39
40 let anomaly_err q = Pp.(str "Quality " ++ Quality.raw_pr q ++ str " undefined.")
41 end)
42 (** We only use G to track connected components of the eliminability relation.
43 In particular, G |= q1 = q2 does not mean that they are equal, but just
44 equi-eliminable. As a result, one should not use the check_eq / enforce_eq
45 functions in the remainder of this module.
46
47 Note that we also abuse the Lt relation to get some rigidity for free for
48 the built-in sorts, but this is a hack that should go away at some point. *)
49
50 module RigidPaths = struct
51 type t = (Quality.t list) Quality.Map.t
52
53 let add_elim_to q1 q2 g =
54 let upd ls =
55 Some (match ls with
56 | Some ls -> q2 :: ls
57 | None -> [q2])
58 in
59 Quality.Map.update q1 upd g
60
61 let empty : t = Quality.Map.empty
62
63 let dfs q g =
64 let rec aux seen q =
65 if Quality.Set.mem q seen
66 then seen
67 else
68 let seen = Quality.Set.add q seen in
69 match Quality.Map.find_opt q g with
70 | None -> seen
71 | Some ls -> List.fold_left aux seen ls
72 in aux Quality.Set.empty q
73
74 let check_forbidden_path (map : Quality.Set.t Quality.Map.t) g =
75 let fold q s ls =
76 let allowed = dfs q g in
77 let diff = Quality.Set.diff s allowed in
78 if Quality.Set.is_empty diff
79 then ls
80 else List.append (List.map (fun q' -> (q, q')) (List.of_seq @@ Quality.Set.to_seq diff)) ls in
81 let forbidden = Quality.Map.fold fold map [] in
82 match forbidden with
83 | [] -> None
84 | p :: _ -> Some p
85 end
86
87 module QMap = QVar.Map
88 module QSet = QVar.Set
89
90 type t =
91 { graph: G.t;
92 (** Connected components of the eliminability graph *)
93 rigid_paths: RigidPaths.t;
94 ground_and_global_sorts: Quality.Set.t;
95 dominant: Quality.t QMap.t;
96 delayed_check: QSet.t QMap.t;
97 }
98
99 type path_explanation = G.explanation Lazy.t
100
101 type explanation =
102 | Path of path_explanation
103 | Other of Pp.t
104
105 type quality_inconsistency =
106 ((QVar.t -> Pp.t) option) *
107 (ElimConstraint.kind * Quality.t * Quality.t * explanation option)
108
109 (* If s can eliminate to s', we want an edge between s and s'.
110 In the acyclic graph, it means setting s to be lower or equal than s'.
111 This function ensures a uniform behaviour between [check] and [enforce]. *)
112 let to_graph_cstr k =
113 let open ElimConstraint in
114 match k with
115 | ElimTo -> AcyclicGraph.Le
116
117 type elimination_error =
118 | IllegalConstraintFromSProp of Quality.t
119 | IllegalConstantConstraint of Quality.constant * Quality.constant
120 | CreatesForbiddenPath of Quality.t * Quality.t
121 | MultipleDominance of Quality.t * Quality.t * Quality.t
122 | QualityInconsistency of quality_inconsistency
123
124 exception EliminationError of elimination_error
125
126 let non_refl_pairs l =
127 let fold x =
128 List.fold_right (fun y acc -> if x <> y then (x,y) :: acc else acc) l in
129 List.fold_right fold l []
130
131 let get_new_rigid_paths g p dom =
132 let add (q1,_,q2) accu =
133 Quality.Map.update q1
134 (fun ls -> Some (match ls with Some ls -> Quality.Set.add q2 ls | None -> Quality.Set.singleton q2))
135 accu in
136 let all_paths = G.constraints_for ~kept:dom g add Quality.Map.empty in
137 RigidPaths.check_forbidden_path all_paths p
138
139 let set_dominant g qv q =
140 { g with dominant = QMap.add qv q g.dominant }
141
142 (* Set the dominant sort of qv to the minimum between q1 and q2 if they are related.
143 [q1] is the dominant of qv in [g]. *)
144 let update_dominant_if_related g qv q1 q2 =
145 if G.check_leq g.graph q1 q2 then Some (set_dominant g qv q2)
146 else if G.check_leq g.graph q2 q1 then Some g
147 else None
148
149 (* If [qv] is not dominated, set dominance to [q].
150 Otherwise, checks whether the dominant of [qv] and [q] are related.
151 If so, puts the smallest of the two as the dominant of [qv]. *)
152 let rec update_dominance g q qv =
153 let g' = match QMap.find_opt qv g.dominant with
154 | None -> Some (set_dominant g qv q)
155 | Some q' -> update_dominant_if_related g qv q' q in
156 match QMap.find_opt qv g.delayed_check with
157 | None -> g'
158 | Some qs ->
159 let g' = QSet.fold (fun v g -> Option.bind g (fun g -> update_dominance g q v)) qs g' in
160 match g' with
161 | Some graph -> Some { graph with delayed_check = QMap.set qv QSet.empty g.delayed_check }
162 | None -> None
163
164 let update_dominance_if_valid g (q1,k,q2) =
165 match k with
166 | ElimConstraint.ElimTo ->
167 (* if the constraint is s ~> g, dominants are not modified. *)
168 if Quality.is_qconst q2 then Some g
169 else
170 match q1, q2 with
171 | (Quality.QConstant _ | Quality.QVar _), Quality.QConstant _ -> assert false
172 | Quality.QVar qv1, Quality.QVar qv2 ->
173 (* 3 cases:
174 - if [qv1] is a global, treat as constants.
175 - if [qv1] is not dominated, delay the check to when [qv1] gets dominated.
176 - if [qv1] is dominated, try to update the dominance of [qv2]. *)
177 if Quality.is_qglobal q1 then update_dominance g q1 qv2
178 else
179 (match QMap.find_opt qv1 g.dominant with
180 | None ->
181 let add_delayed qs =
182 Some { g with delayed_check = QMap.set qv1 (QSet.add qv2 qs) g.delayed_check }
183 in
184 (match QMap.find_opt qv1 g.delayed_check with
185 | None -> add_delayed QSet.empty
186 | Some qs -> add_delayed qs)
187 | Some q' -> update_dominance g q' qv2)
188 | Quality.QConstant _, Quality.QVar qv -> update_dominance g q1 qv
189
190 let dominance_check g (q1,_,q2 as cstr) =
191 let dom_q1 () = match q1 with
192 | Quality.QConstant _ -> q1
193 | Quality.QVar qv ->
194 if Quality.is_qglobal q1 then q1
195 else QMap.find qv g.dominant in
196 let dom_q2 () = match q2 with
197 | Quality.QConstant _ -> assert false
198 | Quality.QVar qv -> QMap.find qv g.dominant in
199 match update_dominance_if_valid g cstr with
200 | None -> raise (EliminationError (MultipleDominance (dom_q2() , q2, dom_q1())))
201 | Some g -> g
202
203 let check_rigid_paths g =
204 let paths = get_new_rigid_paths g.graph g.rigid_paths g.ground_and_global_sorts in
205 match paths with
206 | None -> ()
207 | Some (q1, q2) -> raise (EliminationError (CreatesForbiddenPath (q1, q2)))
208
209 let add_rigid_path q1 q2 g =
210 let open Quality in
211 match q1, q2 with
212 (* Adding a constraint from SProp -> * is not allowed *)
213 | QConstant QSProp, _ -> raise (EliminationError (IllegalConstraintFromSProp q2))
214 (* Adding constraints between constants is not allowed *)
215 | QConstant qc1, QConstant qc2 -> raise (EliminationError (IllegalConstantConstraint (qc1, qc2)))
216 | _, _ -> { g with rigid_paths = RigidPaths.add_elim_to q1 q2 g.rigid_paths }
217
218 let enforce_func k q1 q2 g = match k with
219 | ElimConstraint.ElimTo ->
220 begin match G.enforce_leq q1 q2 g.graph with
221 | None -> None
222 | Some graph -> Some { g with graph }
223 end
224
225 let enforce_constraint (q1, k, q2) g =
226 match enforce_func k q1 q2 g with
227 | None ->
228 let e = lazy (G.get_explanation (q1,to_graph_cstr k,q2) g.graph) in
229 raise @@ EliminationError (QualityInconsistency (None, (k, q1, q2, Some (Path e))))
230 | Some g ->
231 dominance_check g (q1, k, q2)
232
233 let merge_constraints csts g = ElimConstraints.fold enforce_constraint csts g
234
235 let check_constraint g (q1, k, q2) = match k with
236 | ElimConstraint.ElimTo -> G.check_leq g.graph q1 q2
237
238 let check_constraints csts g = ElimConstraints.for_all (check_constraint g) csts
239
240 exception AlreadyDeclared = G.AlreadyDeclared
241
242 let add_quality q g =
243 let graph = G.add q g.graph in
244 let g = enforce_constraint (Quality.qtype, ElimConstraint.ElimTo, q) { g with graph } in
245 let (paths,ground_and_global_sorts) =
246 if Quality.is_qglobal q
247 then (RigidPaths.add_elim_to Quality.qtype q g.rigid_paths, Quality.Set.add q g.ground_and_global_sorts)
248 else (g.rigid_paths,g.ground_and_global_sorts) in
249 (* As Type ~> s, set Type to be the dominant sort of q if q is a variable. *)
250 let dominant = match q with
251 | Quality.QVar qv -> QMap.add qv Quality.qtype g.dominant
252 | Quality.QConstant _ -> g.dominant in
253 { g with rigid_paths = paths; ground_and_global_sorts; dominant }
254
255 let enforce_eliminates_to s1 s2 g =
256 enforce_constraint (s1, ElimConstraint.ElimTo, s2) g
257
258 let initial_graph =
259 let g = G.empty in
260 let g = List.fold_left (fun g q -> G.add q g) g Quality.all_constants in
261 (* Enforces the constant constraints defined in the table of
262 [Constants.eliminates_to] without reflexivity (should be consistent,
263 otherwise the [Option.get] will fail). *)
264 let fold (g,p) (q,q') =
265 if ElimTable.eliminates_to q q'
266 then (Option.get @@ G.enforce_lt q q' g, RigidPaths.add_elim_to q q' p)
267 else (g,p)
268 in
269 let (g,p) = List.fold_left fold (g,RigidPaths.empty) @@ non_refl_pairs Quality.all_constants in
270 { graph = g;
271 rigid_paths = p;
272 ground_and_global_sorts = Quality.Set.of_list Quality.all_constants;
273 dominant = QMap.empty;
274 delayed_check = QMap.empty; }
275
276 let eliminates_to g q q' =
277 G.check_leq g.graph q q'
278
279 let update_rigids g g' =
280 { g' with rigid_paths = g.rigid_paths }
281
282 let sort_eliminates_to g s1 s2 =
283 eliminates_to g (quality s1) (quality s2)
284
285 let eliminates_to_prop g q = eliminates_to g q Quality.qprop
286
287 let domain g = G.domain g.graph
288
289 let qvar_domain g =
290 Quality.Set.fold
291 (fun q acc -> match q with Quality.QVar q -> QVar.Set.add q acc | _ -> acc)
292 (domain g) QVar.Set.empty
293
294 (* XXX the function below does not handle equivalence classes, but it's only used for printing *)
295 let merge g g' =
296 let qs = domain g' in
297 let g = Quality.Set.fold
298 (fun q acc -> try add_quality q acc with _ -> acc) qs g in
299 Quality.Set.fold
300 (fun q -> Quality.Set.fold
301 (fun q' acc -> if eliminates_to g' q q'
302 then enforce_eliminates_to q q' acc
303 else acc) qs) qs g
304
305 let is_empty g = QVar.Set.is_empty (qvar_domain g)
306
307 (* Pretty printing *)
308
309 let pr_pmap sep pr map =
310 let cmp (q1, _) (q2, _) = Quality.compare q1 q2 in
311 Pp.prlist_with_sep sep pr (List.sort cmp (Quality.Map.bindings map))
312
313 let pr_arc prq =
314 let open Pp in
315 function
316 | q1, G.Node ltle ->
317 if Quality.Map.is_empty ltle then mt ()
318 else
319 prq q1 ++ spc () ++
320 v 0
321 (pr_pmap spc (fun (q2, _) ->
322 str "-> " ++ prq q2)
323 ltle) ++
324 fnl ()
325 | q1, G.Alias q2 ->
326 prq q1 ++ str " <-> " ++ prq q2 ++ fnl ()
327
328 let repr g = G.repr g.graph
329
330 let is_declared q g = match G.check_declared g.graph (Quality.Set.singleton q) with
331 | Result.Ok _ -> true
332 | Result.Error _ -> false
333
334 let pr_qualities prq g = pr_pmap Pp.mt (pr_arc prq) (repr g)
335
336 let explain_quality_inconsistency prv r =
337 let open Pp in
338 let pr_cst = function
339 | AcyclicGraph.Eq -> str"="
340 | AcyclicGraph.Le -> str"->"
341 | AcyclicGraph.Lt -> str"->" (* Yes, it's the same as above. *)
342 in
343 match r with
344 | None -> mt()
345 | Some (Other p) -> p
346 | Some (Path p) ->
347 let pstart, p = Lazy.force p in
348 if p = [] then mt ()
349 else
350 let qualities = pstart :: List.map snd p in
351 let constants = List.filter Quality.is_qconst qualities in
352 str "because it would identify " ++
353 pr_enum (Quality.pr prv) constants ++
354 spc() ++ str"which is inconsistent." ++ spc() ++
355 str"This is introduced by the constraints " ++
356 prlist (fun (r, v) -> Quality.pr prv v ++ spc() ++ pr_cst r ++ spc()) p ++
357 Quality.pr prv pstart
358
359 let explain_elimination_error defprv err =
360 let open Pp in
361 match err with
362 | IllegalConstraintFromSProp q -> str "Enforcing elimination constraints from SProp to any other sort is not allowed. " ++ brk (1, 0) ++
363 str "This expression would enforce that SProp eliminates to " ++ Quality.pr defprv q ++ str "."
364 | IllegalConstantConstraint (q1, q2) -> str "Enforcing elimination constraints between constant sorts (Type, Prop or SProp) is not allowed." ++ brk (1, 0) ++
365 str "Here: " ++ Quality.Constants.pr q1 ++ str" and " ++ Quality.Constants.pr q2 ++ str "."
366 | CreatesForbiddenPath (q1,q2) ->
367 str "This expression would enforce a non-declared elimination constraint between" ++
368 spc() ++ Quality.pr defprv q1 ++ spc() ++ str"and" ++ spc() ++ Quality.pr defprv q2
369 | MultipleDominance (q1,qv,q2) ->
370 let pr_elim q = Quality.pr defprv q ++ spc() ++ str"->" ++ spc() ++ Quality.pr defprv qv in
371 str "This expression enforces" ++ spc() ++ pr_elim q1 ++ spc() ++ str"and" ++ spc() ++
372 pr_elim q2 ++ spc() ++ str"which might make type-checking undecidable"
373 | QualityInconsistency (prv, (k, q1, q2, r)) ->
374 let prv = match prv with Some prv -> prv | None -> defprv in
375 str"The quality constraints are inconsistent: " ++
376 str "cannot enforce" ++ spc() ++ Quality.pr prv q1 ++ spc() ++
377 ElimConstraint.pr_kind k ++ spc() ++ Quality.pr prv q2 ++ spc() ++
378 explain_quality_inconsistency prv r