Debian Codegraph @

plugins/cc/ccalgo.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 (* This file implements the basic congruence-closure algorithm by *)
12 (* Downey, Sethi and Tarjan. *)
13 (* Plus some e-matching and constructor handling by P. Corbineau *)
14
15 open CErrors
16 open Pp
17 open Names
18 open Sorts
19 open Constr
20 open Context
21 open Vars
22 open Util
23 open Lazy
24
25 let init_size=5
26
27 let debug_congruence = CDebug.create ~name:"congruence" ()
28
29 (* Signature table *)
30
31 module ST=struct
32
33 (* l: sign -> term r: term -> sign *)
34
35 module IntTable = Hashtbl.Make(Int)
36 module IntPair =
37 struct
38 type t = int * int
39 let equal (i1, j1) (i2, j2) = Int.equal i1 i2 && Int.equal j1 j2
40 let hash (i, j) = Hashset.Combine.combine (Int.hash i) (Int.hash j)
41 end
42 module IntPairTable = Hashtbl.Make(IntPair)
43
44 type t = {toterm: int IntPairTable.t;
45 tosign: (int * int) IntTable.t}
46
47 let empty () =
48 {toterm=IntPairTable.create init_size;
49 tosign=IntTable.create init_size}
50
51 let enter t sign st=
52 if IntPairTable.mem st.toterm sign then
53 anomaly ~label:"enter" (Pp.str "signature already entered.")
54 else
55 IntPairTable.replace st.toterm sign t;
56 IntTable.replace st.tosign t sign
57
58 let query sign st=IntPairTable.find st.toterm sign
59
60 let delete st t=
61 try let sign=IntTable.find st.tosign t in
62 IntPairTable.remove st.toterm sign;
63 IntTable.remove st.tosign t
64 with
65 Not_found -> ()
66
67 let delete_set st s = Int.Set.iter (delete st) s
68
69 end
70
71 type pa_constructor=
72 { cnode : int;
73 arity : int;
74 args : int list}
75
76 type pa_fun=
77 {fsym:int;
78 fnargs:int}
79
80 type pa_mark=
81 Fmark of pa_fun
82 | Cmark of pa_constructor
83
84 module PacOrd =
85 struct
86 type t = pa_constructor
87 let compare { cnode = cnode0; arity = arity0; args = args0 }
88 { cnode = cnode1; arity = arity1; args = args1 } =
89 let cmp = Int.compare cnode0 cnode1 in
90 if cmp = 0 then
91 let cmp' = Int.compare arity0 arity1 in
92 if cmp' = 0 then
93 List.compare Int.compare args0 args1
94 else
95 cmp'
96 else
97 cmp
98 end
99
100 module PafOrd =
101 struct
102 type t = pa_fun
103 let compare { fsym = fsym0; fnargs = fnargs0 } { fsym = fsym1; fnargs = fnargs1 } =
104 let cmp = Int.compare fsym0 fsym1 in
105 if cmp = 0 then
106 Int.compare fnargs0 fnargs1
107 else
108 cmp
109 end
110
111 module PacMap=Map.Make(PacOrd)
112 module PafMap=Map.Make(PafOrd)
113
114 type constructor =
115 | Construct of pconstructor
116 | Int of Uint63.t
117 | Float of Float64.t
118 | String of Pstring.t
119
120 type cinfo=
121 {ci_constr: constructor; (* inductive type *)
122 ci_arity: int; (* # args *)
123 ci_nhyps: int} (* # projectable args *)
124
125 let family_eq f1 f2 = match f1, f2 with
126 | Set, Set
127 | Prop, Prop
128 | Type _, Type _ -> true
129 | _ -> false
130
131
132 type 'a term =
133 Symb of constr * (* Hash: *) int
134 | Product of Sorts.t * Sorts.t
135 | Eps of Id.t
136 | Appli of 'a * 'a
137 | Constructor of cinfo (* constructor arity + nhyps *)
138
139 (* terms with eagerly cached constr and hash *)
140 module ATerm :
141 sig
142 type t
143 val proj : t -> t term
144 val mkSymb : constr -> t
145 val mkProduct : (Sorts.t * Sorts.t) -> t
146 val mkEps : Id.t -> t
147 val mkAppli : (t * t) -> t
148 val mkConstructor : Environ.env -> cinfo -> t
149
150 val equal : t -> t -> bool
151 val constr : t -> constr
152 val hash : t -> int
153 val nth_arg : t -> int -> t
154 end =
155 struct
156 type t = {
157 term : t term;
158 constr : constr lazy_t;
159 hash : int }
160
161 let proj t = t.term
162
163 let eq_constructor c1 c2 = match c1, c2 with
164 | Construct (c1, u1), Construct (c2, u2) ->
165 Construct.UserOrd.equal c1 c2
166 | Int i1, Int i2 -> Uint63.equal i1 i2
167 | String s1, String s2 -> Pstring.equal s1 s2
168 | Float f1, Float f2 -> Float64.equal f1 f2
169 | (Construct _ | String _ | Int _ | Float _), _ -> false
170
171 open Hashset.Combine
172
173 let hash_constructor = function
174 | Construct (c, u) -> combine 1 (Construct.UserOrd.hash c)
175 | Int i -> combine 2 (Uint63.hash i)
176 | Float f -> combine 3 (Float64.hash f)
177 | String s -> combine 4 (Pstring.hash s)
178
179 let rec term_equal t1 t2 =
180 match t1, t2 with
181 | Symb (c1,_), Symb (c2,_) -> eq_constr_nounivs c1 c2
182 | Product (s1, t1), Product (s2, t2) -> family_eq s1 s2 && family_eq t1 t2
183 | Eps i1, Eps i2 -> Id.equal i1 i2
184 | Appli (t1', u1'), Appli (t2', u2') -> term_equal t1'.term t2'.term && term_equal u1'.term u2'.term
185 | Constructor {ci_constr=c1; ci_arity=i1; ci_nhyps=j1},
186 Constructor {ci_constr=c2; ci_arity=i2; ci_nhyps=j2} ->
187 Int.equal i1 i2 && Int.equal j1 j2 && eq_constructor c1 c2
188 | _ -> false
189
190 let equal t1 t2 = term_equal t1.term t2.term
191
192 let hash_term t =
193 match t with
194 | Symb (_,hash_c) -> combine 1 hash_c
195 | Product (s1, s2) -> combine3 2 (Sorts.hash s1) (Sorts.hash s2)
196 | Eps i -> combine 3 (Id.hash i)
197 | Appli (t1', t2') -> combine3 4 (t1'.hash) (t2'.hash)
198 | Constructor {ci_constr=c; ci_arity=i; ci_nhyps=j} -> combine4 5 (hash_constructor c) i j
199
200 let hash t = t.hash
201
202 (* rebuild a constr from an applicative term *)
203
204 let _A_ = Name (Id.of_string "A")
205 let _B_ = Name (Id.of_string "A")
206 let _body_ = mkProd(make_annot Anonymous Sorts.Relevant,mkRel 2,mkRel 2)
207
208 let cc_product s1 s2 =
209 mkLambda(make_annot _A_ Sorts.Relevant,mkSort(s1),
210 mkLambda(make_annot _B_ Sorts.Relevant,mkSort(s2),_body_))
211
212 let rec constr_of_term = function
213 Symb (s,_) -> s
214 | Product(s1,s2) -> cc_product s1 s2
215 | Eps id -> mkVar id
216 | Constructor { ci_constr = Construct c } -> mkConstructU c
217 | Constructor { ci_constr = Int i } -> mkInt i
218 | Constructor { ci_constr = Float f } -> mkFloat f
219 | Constructor { ci_constr = String s } -> mkString s
220 | Appli (s1',s2') -> make_app [force s2'.constr] s1'
221 and make_app l t' =
222 match t'.term with
223 Appli (s1',s2')->make_app ((force s2'.constr)::l) s1'
224 | _ -> Term.applist (force t'.constr, l)
225
226 let constr t = force t.constr
227
228 let make t = {
229 term = t;
230 constr = lazy (constr_of_term t);
231 hash = hash_term t }
232
233 let rec drop_univ c =
234 match kind c with
235 | Const (c,_u) -> mkConstU (c,UVars.Instance.empty)
236 | Ind (c,_u) -> mkIndU (c,UVars.Instance.empty)
237 | Construct (c,_u) -> mkConstructU (c,UVars.Instance.empty)
238 | Sort (Type _u) -> mkSort (type1)
239 | _ -> Constr.map drop_univ c
240
241 let mkSymb s = make (Symb (s, Constr.hash (drop_univ s)))
242
243 let mkProduct (s1, s2) = make (Product (s1, s2))
244
245 let mkEps id = make (Eps id)
246
247 let mkAppli (t1', t2') = make (Appli (t1', t2'))
248
249 let mkConstructor env info =
250 let canon i = Environ.QConstruct.canonize env i in
251 let ci_constr = match info.ci_constr with
252 | Construct (c, u) -> Construct (canon c, u)
253 | Int i -> Int i
254 | Float f -> Float f
255 | String s -> String s
256 in
257 let info = { info with ci_constr } in
258 make (Constructor info)
259
260 let rec nth_arg t n =
261 match t.term with
262 Appli (t1',t2')->
263 if n>0 then nth_arg t1' (n-1)
264 else t2'
265 | _ -> anomaly ~label:"nth_arg" (Pp.str "not enough args.")
266 end
267
268 type ccpattern =
269 PApp of ATerm.t * ccpattern list (* arguments are reversed *)
270 | PVar of int * ccpattern list (* arguments are reversed *)
271
272 type axiom = constr
273
274 let constr_of_axiom c = c
275
276 type rule=
277 Congruence
278 | Axiom of axiom * bool
279 | Injection of int * pa_constructor * int * pa_constructor * int
280
281 type from=
282 Goal
283 | Hyp of constr
284 | HeqG of Id.t
285 | HeqnH of Id.t * Id.t
286
287 type 'a eq = {lhs:int;rhs:int;rule:'a}
288
289 type equality = rule eq
290
291 type disequality = from eq
292
293 type patt_kind =
294 Normal
295 | Trivial of types
296 | Creates_variables
297
298 type quant_eq =
299 {
300 qe_hyp_id: Id.t;
301 qe_pol: bool;
302 qe_nvars:int;
303 qe_lhs: ccpattern;
304 qe_lhs_valid:patt_kind;
305 qe_rhs: ccpattern;
306 qe_rhs_valid:patt_kind
307 }
308
309 let swap eq : equality =
310 let swap_rule=match eq.rule with
311 Congruence -> Congruence
312 | Injection (i,pi,j,pj,k) -> Injection (j,pj,i,pi,k)
313 | Axiom (id,reversed) -> Axiom (id,not reversed)
314 in {lhs=eq.rhs;rhs=eq.lhs;rule=swap_rule}
315
316 type inductive_status =
317 Unknown
318 | Partial of pa_constructor
319 | Partial_applied
320 | Total of (int * pa_constructor)
321
322 type representative=
323 {mutable weight:int;
324 mutable lfathers:Int.Set.t;
325 mutable fathers:Int.Set.t;
326 mutable inductive_status: inductive_status;
327 class_type : types;
328 mutable functions: Int.Set.t PafMap.t} (*pac -> term = app(constr,t) *)
329
330 type cl = Rep of representative| Eqto of int*equality
331
332 type vertex = Leaf| Node of (int*int)
333
334 type node =
335 {mutable clas:cl;
336 mutable cpath: int;
337 mutable constructors: int PacMap.t;
338 vertex:vertex;
339 aterm:ATerm.t}
340
341 module Constrhash = Hashtbl.Make
342 (struct type t = constr
343 let equal = eq_constr_nounivs
344 let hash = Constr.hash
345 end)
346 module Typehash = Constrhash
347
348 module Termhash = Hashtbl.Make
349 (struct type t = ATerm.t
350 let equal = ATerm.equal
351 let hash = ATerm.hash
352 end)
353
354 module Identhash = Hashtbl.Make
355 (struct type t = Id.t
356 let equal = Id.equal
357 let hash = Id.hash
358 end)
359
360 type forest=
361 {mutable max_size:int;
362 mutable size:int;
363 mutable map: node array;
364 axioms: (ATerm.t * ATerm.t) Constrhash.t;
365 mutable epsilons: pa_constructor list;
366 syms: int Termhash.t}
367
368 type state =
369 {uf: forest;
370 sigtable:ST.t;
371 mutable terms: Int.Set.t;
372 combine: equality Queue.t;
373 marks: (int * pa_mark) Queue.t;
374 mutable diseq: disequality list;
375 mutable quant: quant_eq list;
376 mutable pa_classes: Int.Set.t;
377 q_history: (int array) Identhash.t;
378 mutable rew_depth:int;
379 mutable changed:bool;
380 by_type: Int.Set.t Typehash.t;
381 mutable env:Environ.env;
382 sigma:Evd.evar_map}
383
384 let dummy_node =
385 {
386 clas=Eqto (min_int,{lhs=min_int;rhs=min_int;rule=Congruence});
387 cpath=min_int;
388 constructors=PacMap.empty;
389 vertex=Leaf;
390 aterm= ATerm.mkSymb (mkRel min_int)
391 }
392
393 let empty_forest() =
394 {
395 max_size=init_size;
396 size=0;
397 map=Array.make init_size dummy_node;
398 epsilons=[];
399 axioms=Constrhash.create init_size;
400 syms=Termhash.create init_size
401 }
402
403 let empty env sigma depth : state =
404 {
405 uf= empty_forest ();
406 terms=Int.Set.empty;
407 combine=Queue.create ();
408 marks=Queue.create ();
409 sigtable=ST.empty ();
410 diseq=[];
411 quant=[];
412 pa_classes=Int.Set.empty;
413 q_history=Identhash.create init_size;
414 rew_depth=depth;
415 by_type=Constrhash.create init_size;
416 changed=false;
417 env;
418 sigma;
419 }
420
421 let forest state = state.uf
422
423 let compress_path uf i j = uf.map.(j).cpath<-i
424
425 let rec find_aux uf visited i=
426 let j = uf.map.(i).cpath in
427 if j<0 then let () = List.iter (compress_path uf i) visited in i else
428 find_aux uf (i::visited) j
429
430 let find uf i= find_aux uf [] i
431
432 let get_representative uf i=
433 match uf.map.(i).clas with
434 Rep r -> r
435 | _ -> anomaly ~label:"get_representative" (Pp.str "not a representative.")
436
437 let get_constructors uf i= uf.map.(i).constructors
438
439 let rec find_oldest_pac uf i pac=
440 try PacMap.find pac (get_constructors uf i) with
441 Not_found ->
442 match uf.map.(i).clas with
443 Eqto (j,_) -> find_oldest_pac uf j pac
444 | Rep _ -> raise Not_found
445
446
447 let get_constructor_info uf i=
448 match ATerm.proj uf.map.(i).aterm with
449 Constructor cinfo->cinfo
450 | _ -> anomaly ~label:"get_constructor" (Pp.str "not a constructor.")
451
452 let size uf i=
453 (get_representative uf i).weight
454
455 let axioms uf c = Constrhash.find uf.axioms c
456
457 let epsilons uf = uf.epsilons
458
459 let add_lfather uf i t=
460 let r=get_representative uf i in
461 r.weight<-r.weight+1;
462 r.lfathers<-Int.Set.add t r.lfathers;
463 r.fathers <-Int.Set.add t r.fathers
464
465 let add_rfather uf i t=
466 let r=get_representative uf i in
467 r.weight<-r.weight+1;
468 r.fathers <-Int.Set.add t r.fathers
469
470 exception Discriminable of int * pa_constructor * int * pa_constructor
471
472 let append_pac t p =
473 {p with arity=pred p.arity;args=t::p.args}
474
475 let tail_pac p=
476 {p with arity=succ p.arity;args=List.tl p.args}
477
478 let fsucc paf =
479 {paf with fnargs=succ paf.fnargs}
480
481 let add_pac node pac t =
482 if not (PacMap.mem pac node.constructors) then
483 node.constructors<-PacMap.add pac t node.constructors
484
485 let add_paf rep paf t =
486 let already =
487 try PafMap.find paf rep.functions with Not_found -> Int.Set.empty in
488 rep.functions<- PafMap.add paf (Int.Set.add t already) rep.functions
489
490 let aterm uf i=uf.map.(i).aterm
491
492 let subterms uf i=
493 match uf.map.(i).vertex with
494 Node(j,k) -> (j,k)
495 | _ -> anomaly ~label:"subterms" (Pp.str "not a node.")
496
497 let signature uf i=
498 let j,k=subterms uf i in (find uf j,find uf k)
499
500 let next uf=
501 let size=uf.size in
502 let nsize= succ size in
503 if Int.equal nsize uf.max_size then
504 let newmax=uf.max_size * 3 / 2 + 1 in
505 let newmap=Array.make newmax dummy_node in
506 begin
507 uf.max_size<-newmax;
508 Array.blit uf.map 0 newmap 0 size;
509 uf.map<-newmap
510 end
511 else ();
512 uf.size<-nsize;
513 size
514
515 let new_representative typ =
516 {weight=0;
517 lfathers=Int.Set.empty;
518 fathers=Int.Set.empty;
519 inductive_status=Unknown;
520 class_type=typ;
521 functions=PafMap.empty}
522
523
524 let rec canonize_name c =
525 let c = EConstr.Unsafe.to_constr c in
526 let func c = canonize_name (EConstr.of_constr c) in
527 match Constr.kind c with
528 | Const (kn,u) ->
529 let canon_const = Constant.make1 (Constant.canonical kn) in
530 (mkConstU (canon_const,u))
531 | Ind ((kn,i),u) ->
532 let canon_mind = MutInd.make1 (MutInd.canonical kn) in
533 (mkIndU ((canon_mind,i),u))
534 | Construct (((kn,i),j),u) ->
535 let canon_mind = MutInd.make1 (MutInd.canonical kn) in
536 mkConstructU (((canon_mind,i),j),u)
537 | Prod (na,t,ct) ->
538 mkProd (na,func t, func ct)
539 | Lambda (na,t,ct) ->
540 mkLambda (na, func t,func ct)
541 | LetIn (na,b,t,ct) ->
542 mkLetIn (na, func b,func t,func ct)
543 | App (ct,l) ->
544 mkApp (func ct,Array.Smart.map func l)
545 | Proj(p,r,c) ->
546 let p' = Projection.map (fun kn ->
547 MutInd.make1 (MutInd.canonical kn)) p in
548 (mkProj (p', r, func c))
549 | _ -> c
550
551 (* rebuild a term from a pattern and a substitution *)
552
553 let build_subst uf subst =
554 Array.map
555 (fun i ->
556 try aterm uf i
557 with e when CErrors.noncritical e ->
558 anomaly (Pp.str "incomplete matching."))
559 subst
560
561 let rec inst_pattern subst = function
562 PVar (i, args) ->
563 List.fold_right
564 (fun spat f -> ATerm.mkAppli (f,inst_pattern subst spat))
565 args subst.(pred i)
566 | PApp (t', args) ->
567 List.fold_right
568 (fun spat f -> ATerm.mkAppli (f,inst_pattern subst spat))
569 args t'
570
571 let pr_idx_term env sigma uf i = str "[" ++ int i ++ str ":=" ++
572 Printer.pr_econstr_env env sigma (EConstr.of_constr (ATerm.constr (aterm uf i))) ++ str "]"
573
574 let pr_term env sigma t' = str "[" ++
575 Printer.pr_econstr_env env sigma (EConstr.of_constr (ATerm.constr t')) ++ str "]"
576
577 let rec add_aterm state t' =
578 let uf=state.uf in
579 try Termhash.find uf.syms t' with
580 Not_found ->
581 let b=next uf in
582 let trm = ATerm.constr t' in
583 let typ = Retyping.get_type_of state.env state.sigma (EConstr.of_constr trm) in
584 let typ = canonize_name typ in
585 let new_node=
586 match ATerm.proj t' with
587 Symb _ | Product (_,_) ->
588 let paf =
589 {fsym=b;
590 fnargs=0} in
591 Queue.add (b,Fmark paf) state.marks;
592 {clas= Rep (new_representative typ);
593 cpath= -1;
594 constructors=PacMap.empty;
595 vertex= Leaf;
596 aterm= t'}
597 | Eps id ->
598 {clas= Rep (new_representative typ);
599 cpath= -1;
600 constructors=PacMap.empty;
601 vertex= Leaf;
602 aterm= t'}
603 | Appli (t1',t2') ->
604 let i1=add_aterm state t1' and i2=add_aterm state t2' in
605 add_lfather uf (find uf i1) b;
606 add_rfather uf (find uf i2) b;
607 state.terms<-Int.Set.add b state.terms;
608 {clas= Rep (new_representative typ);
609 cpath= -1;
610 constructors=PacMap.empty;
611 vertex= Node(i1,i2);
612 aterm= t'}
613 | Constructor cinfo ->
614 let paf =
615 {fsym=b;
616 fnargs=0} in
617 Queue.add (b,Fmark paf) state.marks;
618 let pac =
619 {cnode= b;
620 arity= cinfo.ci_arity;
621 args=[]} in
622 Queue.add (b,Cmark pac) state.marks;
623 {clas=Rep (new_representative typ);
624 cpath= -1;
625 constructors=PacMap.empty;
626 vertex=Leaf;
627 aterm=t'}
628 in
629 uf.map.(b)<-new_node;
630 Termhash.add uf.syms t' b;
631 Typehash.replace state.by_type typ
632 (Int.Set.add b
633 (try Typehash.find state.by_type typ with
634 Not_found -> Int.Set.empty));
635 b
636
637 let add_equality0 state c s' t' =
638 let i = add_aterm state s' in
639 let j = add_aterm state t' in
640 Queue.add {lhs=i;rhs=j;rule=Axiom(c,false)} state.combine;
641 Constrhash.add state.uf.axioms c (s',t')
642
643 let add_equality state id s t =
644 add_equality0 state (mkVar id) s t
645
646 let add_disequality state from s' t' =
647 let i = add_aterm state s' in
648 let j = add_aterm state t' in
649 state.diseq<-{lhs=i;rhs=j;rule=from}::state.diseq
650
651 let add_quant state id pol (nvars,valid1,patt1,valid2,patt2) =
652 state.quant<-
653 {qe_hyp_id= id;
654 qe_pol= pol;
655 qe_nvars=nvars;
656 qe_lhs= patt1;
657 qe_lhs_valid=valid1;
658 qe_rhs= patt2;
659 qe_rhs_valid=valid2}::state.quant
660
661 let is_redundant state id args =
662 try
663 let norm_args = Array.map (find state.uf) args in
664 let prev_args = Identhash.find_all state.q_history id in
665 List.exists
666 (fun old_args ->
667 Util.Array.for_all2 (fun i j -> Int.equal i (find state.uf j))
668 norm_args old_args)
669 prev_args
670 with Not_found -> false
671
672 let add_inst state (inst,int_subst) =
673 Control.check_for_interrupt ();
674 if state.rew_depth > 0 then
675 if is_redundant state inst.qe_hyp_id int_subst then
676 debug_congruence (fun () -> str "discarding redundant (dis)equality")
677 else
678 begin
679 Identhash.add state.q_history inst.qe_hyp_id int_subst;
680 let subst = build_subst (forest state) int_subst in
681 let prfhead= mkVar inst.qe_hyp_id in
682 let args = Array.map ATerm.constr subst in
683 let _ = Array.rev args in (* highest deBruijn index first *)
684 let prf= mkApp(prfhead,args) in
685 let s = inst_pattern subst inst.qe_lhs
686 and t = inst_pattern subst inst.qe_rhs in
687 state.changed<-true;
688 state.rew_depth<-pred state.rew_depth;
689 if inst.qe_pol then
690 begin
691 debug_congruence (fun () ->
692 (str "Adding new equality, depth="++ int state.rew_depth) ++ fnl () ++
693 (str " [" ++ Printer.pr_econstr_env state.env state.sigma (EConstr.of_constr prf) ++ str " : " ++
694 pr_term state.env state.sigma s ++ str " == " ++ pr_term state.env state.sigma t ++ str "]"));
695 add_equality0 state prf s t
696 end
697 else
698 begin
699 debug_congruence (fun () ->
700 (str "Adding new disequality, depth="++ int state.rew_depth) ++ fnl () ++
701 (str " [" ++ Printer.pr_econstr_env state.env state.sigma (EConstr.of_constr prf) ++ str " : " ++
702 pr_term state.env state.sigma s ++ str " <> " ++ pr_term state.env state.sigma t ++ str "]"));
703 add_disequality state (Hyp prf) s t
704 end
705 end
706
707 let link uf i j eq = (* links i -> j *)
708 let node=uf.map.(i) in
709 node.clas<-Eqto (j,eq);
710 node.cpath<-j
711
712 let rec down_path uf i l=
713 match uf.map.(i).clas with
714 Eqto (j,eq) ->down_path uf j (((i,j),eq)::l)
715 | Rep _ ->l
716
717 let eq_pair (i1, j1) (i2, j2) = Int.equal i1 i2 && Int.equal j1 j2
718
719 let rec min_path=function
720 ([],l2)->([],l2)
721 | (l1,[])->(l1,[])
722 | (((c1,t1)::q1),((c2,t2)::q2)) when eq_pair c1 c2 -> min_path (q1,q2)
723 | cpl -> cpl
724
725 let join_path uf i j=
726 assert (Int.equal (find uf i) (find uf j));
727 min_path (down_path uf i [],down_path uf j [])
728
729 let union state i1 i2 eq=
730 debug_congruence (fun () -> str "Linking " ++ pr_idx_term state.env state.sigma state.uf i1 ++
731 str " and " ++ pr_idx_term state.env state.sigma state.uf i2 ++ str ".");
732 let r1= get_representative state.uf i1
733 and r2= get_representative state.uf i2 in
734 link state.uf i1 i2 eq;
735 Constrhash.replace state.by_type r1.class_type
736 (Int.Set.remove i1
737 (try Constrhash.find state.by_type r1.class_type with
738 Not_found -> Int.Set.empty));
739 let f= Int.Set.union r1.fathers r2.fathers in
740 r2.weight<-Int.Set.cardinal f;
741 r2.fathers<-f;
742 r2.lfathers<-Int.Set.union r1.lfathers r2.lfathers;
743 ST.delete_set state.sigtable r1.fathers;
744 state.terms<-Int.Set.union state.terms r1.fathers;
745 PacMap.iter
746 (fun pac b -> Queue.add (b,Cmark pac) state.marks)
747 state.uf.map.(i1).constructors;
748 PafMap.iter
749 (fun paf -> Int.Set.iter
750 (fun b -> Queue.add (b,Fmark paf) state.marks))
751 r1.functions;
752 match r1.inductive_status,r2.inductive_status with
753 Unknown,_ -> ()
754 | Partial pac,Unknown ->
755 r2.inductive_status<-Partial pac;
756 state.pa_classes<-Int.Set.remove i1 state.pa_classes;
757 state.pa_classes<-Int.Set.add i2 state.pa_classes
758 | Partial _ ,(Partial _ |Partial_applied) ->
759 state.pa_classes<-Int.Set.remove i1 state.pa_classes
760 | Partial_applied,Unknown ->
761 r2.inductive_status<-Partial_applied
762 | Partial_applied,Partial _ ->
763 state.pa_classes<-Int.Set.remove i2 state.pa_classes;
764 r2.inductive_status<-Partial_applied
765 | Total cpl,Unknown -> r2.inductive_status<-Total cpl;
766 | Total (i,pac),Total _ -> Queue.add (i,Cmark pac) state.marks
767 | _,_ -> ()
768
769 let merge eq state = (* merge and no-merge *)
770 debug_congruence
771 (fun () -> str "Merging " ++ pr_idx_term state.env state.sigma state.uf eq.lhs ++
772 str " and " ++ pr_idx_term state.env state.sigma state.uf eq.rhs ++ str ".");
773 let uf=state.uf in
774 let i=find uf eq.lhs
775 and j=find uf eq.rhs in
776 if not (Int.equal i j) then
777 if (size uf i)<(size uf j) then
778 union state i j eq
779 else
780 union state j i (swap eq)
781
782 let update t state = (* update 1 and 2 *)
783 debug_congruence
784 (fun () -> str "Updating term " ++ pr_idx_term state.env state.sigma state.uf t ++ str ".");
785 let (i,j) as sign = signature state.uf t in
786 let (u,v) = subterms state.uf t in
787 let rep = get_representative state.uf i in
788 begin
789 match rep.inductive_status with
790 Partial _ ->
791 rep.inductive_status <- Partial_applied;
792 state.pa_classes <- Int.Set.remove i state.pa_classes
793 | _ -> ()
794 end;
795 PacMap.iter
796 (fun pac _ -> Queue.add (t,Cmark (append_pac v pac)) state.marks)
797 (get_constructors state.uf i);
798 PafMap.iter
799 (fun paf _ -> Queue.add (t,Fmark (fsucc paf)) state.marks)
800 rep.functions;
801 try
802 let s = ST.query sign state.sigtable in
803 Queue.add {lhs=t;rhs=s;rule=Congruence} state.combine
804 with
805 Not_found -> ST.enter t sign state.sigtable
806
807 let process_function_mark t rep paf state =
808 add_paf rep paf t;
809 state.terms<-Int.Set.union rep.lfathers state.terms
810
811 let process_constructor_mark t i rep pac state =
812 add_pac state.uf.map.(i) pac t;
813 match rep.inductive_status with
814 Total (s,opac) ->
815 if not (Int.equal pac.cnode opac.cnode) then (* Conflict *)
816 raise (Discriminable (s,opac,t,pac))
817 else (* Match *)
818 let cinfo = get_constructor_info state.uf pac.cnode in
819 let rec f n oargs args=
820 if n > 0 then
821 match (oargs,args) with
822 s1::q1,s2::q2->
823 Queue.add
824 {lhs=s1;rhs=s2;rule=Injection(s,opac,t,pac,n)}
825 state.combine;
826 f (n-1) q1 q2
827 | _-> anomaly ~label:"add_pacs"
828 (Pp.str "weird error in injection subterms merge.")
829 in f cinfo.ci_nhyps opac.args pac.args
830 | Partial_applied | Partial _ ->
831 (* add_pac state.uf.map.(i) pac t; *)
832 state.terms<-Int.Set.union rep.lfathers state.terms
833 | Unknown ->
834 if Int.equal pac.arity 0 then
835 rep.inductive_status <- Total (t,pac)
836 else
837 begin
838 (* add_pac state.uf.map.(i) pac t; *)
839 state.terms<-Int.Set.union rep.lfathers state.terms;
840 rep.inductive_status <- Partial pac;
841 state.pa_classes<- Int.Set.add i state.pa_classes
842 end
843
844 let process_mark t m state =
845 debug_congruence
846 (fun () -> str "Processing mark for term " ++ pr_idx_term state.env state.sigma state.uf t ++ str ".");
847 let i=find state.uf t in
848 let rep=get_representative state.uf i in
849 match m with
850 Fmark paf -> process_function_mark t rep paf state
851 | Cmark pac -> process_constructor_mark t i rep pac state
852
853 type explanation =
854 Discrimination of (int*pa_constructor*int*pa_constructor)
855 | Contradiction of disequality
856 | Incomplete of (EConstr.t * int) list
857
858 let check_disequalities state =
859 let uf=state.uf in
860 let rec check_aux = function
861 | dis::q ->
862 let (info, ans) =
863 if Int.equal (find uf dis.lhs) (find uf dis.rhs) then (str "Yes", Some dis)
864 else (str "No", check_aux q)
865 in
866 let _ = debug_congruence
867 (fun () -> str "Checking if " ++ pr_idx_term state.env state.sigma state.uf dis.lhs ++ str " = " ++
868 pr_idx_term state.env state.sigma state.uf dis.rhs ++ str " ... " ++ info) in
869 ans
870 | [] -> None
871 in
872 check_aux state.diseq
873
874 let one_step state =
875 try
876 let eq = Queue.take state.combine in
877 merge eq state;
878 true
879 with Queue.Empty ->
880 try
881 let (t,m) = Queue.take state.marks in
882 process_mark t m state;
883 true
884 with Queue.Empty ->
885 try
886 let t = Int.Set.choose state.terms in
887 state.terms<-Int.Set.remove t state.terms;
888 update t state;
889 true
890 with Not_found -> false
891
892 let __eps__ = Id.of_string "_eps_"
893
894 let new_state_var typ state =
895 let ids = Environ.ids_of_named_context_val (Environ.named_context_val state.env) in
896 let id = Namegen.next_ident_away __eps__ ids in
897 let r = EConstr.ERelevance.relevant in (* TODO relevance *)
898 state.env<- EConstr.push_named (Context.Named.Declaration.LocalAssum (make_annot id r,typ)) state.env;
899 id
900
901 let complete_one_class state i=
902 match (get_representative state.uf i).inductive_status with
903 | Partial pac ->
904 let rec app t' typ n =
905 if n<=0 then t' else
906 let _,etyp,rest= destProd typ in
907 let id = new_state_var (EConstr.of_constr etyp) state in
908 app (ATerm.mkAppli (t',ATerm.mkEps id)) (substl [mkVar id] rest) (n-1) in
909 let c = Retyping.get_type_of state.env state.sigma
910 (EConstr.of_constr (ATerm.constr (aterm state.uf pac.cnode))) in
911 let c = EConstr.Unsafe.to_constr c in
912 let args =
913 List.map (fun i -> ATerm.constr (aterm state.uf i))
914 pac.args in
915 let typ = Term.prod_applist c (List.rev args) in
916 let ct = app (aterm state.uf i) typ pac.arity in
917 state.uf.epsilons <- pac :: state.uf.epsilons;
918 ignore (add_aterm state ct)
919 | _ -> anomaly (Pp.str "wrong incomplete class.")
920
921 let complete state =
922 Int.Set.iter (complete_one_class state) state.pa_classes
923
924 type matching_problem =
925 {mp_subst : int array;
926 mp_inst : quant_eq;
927 mp_stack : (ccpattern*int) list }
928
929 let make_fun_table state =
930 let uf= state.uf in
931 let funtab=ref PafMap.empty in
932 Array.iteri
933 (fun i inode -> if i < uf.size then
934 match inode.clas with
935 Rep rep ->
936 PafMap.iter
937 (fun paf _ ->
938 let elem =
939 try PafMap.find paf !funtab
940 with Not_found -> Int.Set.empty in
941 funtab:= PafMap.add paf (Int.Set.add i elem) !funtab)
942 rep.functions
943 | _ -> ()) state.uf.map;
944 !funtab
945
946
947 let do_match state res pb_stack =
948 let mp=Stack.pop pb_stack in
949 match mp.mp_stack with
950 [] ->
951 res:= (mp.mp_inst,mp.mp_subst) :: !res
952 | (patt,cl)::remains ->
953 let uf=state.uf in
954 match patt with
955 PVar (i, []) ->
956 if mp.mp_subst.(pred i)<0 then
957 begin
958 mp.mp_subst.(pred i)<- cl; (* no aliasing problem here *)
959 Stack.push {mp with mp_stack=remains} pb_stack
960 end
961 else
962 if Int.equal mp.mp_subst.(pred i) cl then
963 Stack.push {mp with mp_stack=remains} pb_stack
964 else (* mismatch for non-linear variable in pattern *) ()
965 | PVar _ -> () (* do not consider application with variable head *)
966 | PApp (f,[]) ->
967 begin
968 try let j=Termhash.find uf.syms f in
969 if Int.equal (find uf j) cl then
970 Stack.push {mp with mp_stack=remains} pb_stack
971 with Not_found -> ()
972 end
973 | PApp(f, ((last_arg::rem_args) as args)) ->
974 try
975 let j=Termhash.find uf.syms f in
976 let paf={fsym=j;fnargs=List.length args} in
977 let rep=get_representative uf cl in
978 let good_terms = PafMap.find paf rep.functions in
979 let aux i =
980 let (s,t) = signature state.uf i in
981 Stack.push
982 {mp with
983 mp_subst=Array.copy mp.mp_subst;
984 mp_stack=
985 (PApp(f,rem_args),s) ::
986 (last_arg,t) :: remains} pb_stack in
987 Int.Set.iter aux good_terms
988 with Not_found -> ()
989
990 let paf_of_patt syms = function
991 PVar _ -> invalid_arg "paf_of_patt: pattern with variable head"
992 | PApp (f,args) ->
993 {fsym=Termhash.find syms f;
994 fnargs=List.length args}
995
996 let init_pb_stack state =
997 let syms= state.uf.syms in
998 let pb_stack = Stack.create () in
999 let funtab = make_fun_table state in
1000 let aux inst =
1001 begin
1002 let good_classes =
1003 match inst.qe_lhs_valid with
1004 Creates_variables -> Int.Set.empty
1005 | Normal ->
1006 begin
1007 try
1008 let paf= paf_of_patt syms inst.qe_lhs in
1009 PafMap.find paf funtab
1010 with Not_found -> Int.Set.empty
1011 end
1012 | Trivial typ ->
1013 begin
1014 try
1015 Typehash.find state.by_type typ
1016 with Not_found -> Int.Set.empty
1017 end in
1018 Int.Set.iter (fun i ->
1019 Stack.push
1020 {mp_subst = Array.make inst.qe_nvars (-1);
1021 mp_inst=inst;
1022 mp_stack=[inst.qe_lhs,i]} pb_stack) good_classes
1023 end;
1024 begin
1025 let good_classes =
1026 match inst.qe_rhs_valid with
1027 Creates_variables -> Int.Set.empty
1028 | Normal ->
1029 begin
1030 try
1031 let paf= paf_of_patt syms inst.qe_rhs in
1032 PafMap.find paf funtab
1033 with Not_found -> Int.Set.empty
1034 end
1035 | Trivial typ ->
1036 begin
1037 try
1038 Typehash.find state.by_type typ
1039 with Not_found -> Int.Set.empty
1040 end in
1041 Int.Set.iter (fun i ->
1042 Stack.push
1043 {mp_subst = Array.make inst.qe_nvars (-1);
1044 mp_inst=inst;
1045 mp_stack=[inst.qe_rhs,i]} pb_stack) good_classes
1046 end in
1047 List.iter aux state.quant;
1048 pb_stack
1049
1050 let find_instances state =
1051 let pb_stack= init_pb_stack state in
1052 let res =ref [] in
1053 let _ =
1054 debug_congruence (fun () -> str "Running E-matching algorithm ... ");
1055 try
1056 while true do
1057 Control.check_for_interrupt ();
1058 do_match state res pb_stack
1059 done;
1060 anomaly (Pp.str "get out of here!")
1061 with Stack.Empty -> () in
1062 !res
1063
1064 let build_term_to_complete uf pac =
1065 let open EConstr in
1066 let cinfo = get_constructor_info uf pac.cnode in
1067 let real_args = List.rev_map (fun i -> EConstr.of_constr (ATerm.constr (aterm uf i))) pac.args in
1068 match cinfo.ci_constr with
1069 | Construct (kn, u) ->
1070 (applist (mkConstructU (kn, EInstance.make u), real_args), pac.arity)
1071 | Int i ->
1072 let () = assert (List.is_empty real_args) in
1073 let () = assert (Int.equal pac.arity 0) in
1074 mkInt i, 0
1075 | Float f ->
1076 let () = assert (List.is_empty real_args) in
1077 let () = assert (Int.equal pac.arity 0) in
1078 mkFloat f, 0
1079 | String s ->
1080 let () = assert (List.is_empty real_args) in
1081 let () = assert (Int.equal pac.arity 0) in
1082 mkString s, 0
1083
1084 let terms_to_complete state =
1085 let uf = forest state in
1086 List.map (build_term_to_complete uf) (epsilons uf)
1087
1088 let rec execute first_run state =
1089 debug_congruence (fun () -> str "Executing ... ");
1090 try
1091 while
1092 Control.check_for_interrupt ();
1093 one_step state do ()
1094 done;
1095 match check_disequalities state with
1096 None ->
1097 if not(Int.Set.is_empty state.pa_classes) then
1098 begin
1099 debug_congruence (fun () -> str "First run was incomplete, completing ... ");
1100 complete state;
1101 execute false state
1102 end
1103 else
1104 if state.rew_depth>0 then
1105 let l=find_instances state in
1106 List.iter (add_inst state) l;
1107 if state.changed then
1108 begin
1109 state.changed <- false;
1110 execute true state
1111 end
1112 else
1113 begin
1114 debug_congruence (fun () -> str "Out of instances ... ");
1115 None
1116 end
1117 else
1118 begin
1119 debug_congruence (fun () -> str "Out of depth ... ");
1120 None
1121 end
1122 | Some dis -> Some
1123 begin
1124 if first_run then Contradiction dis
1125 else Incomplete (terms_to_complete state)
1126 end
1127 with Discriminable(s,spac,t,tpac) -> Some
1128 begin
1129 if first_run then Discrimination (s,spac,t,tpac)
1130 else Incomplete (terms_to_complete state)
1131 end