]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/utils.ml
70a77c8e8c8c1292af5ce3b745be47846a7299aa
[helm.git] / helm / ocaml / paramodulation / utils.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 let debug = true;;
29
30 let debug_print s = if debug then prerr_endline (Lazy.force s);;
31
32 let print_metasenv metasenv =
33   String.concat "\n--------------------------\n"
34     (List.map (fun (i, context, term) ->
35                  (string_of_int i) ^ " [\n" ^ (CicPp.ppcontext context) ^
36                    "\n] " ^  (CicPp.ppterm term))
37        metasenv)
38 ;;
39
40
41 let print_subst ?(prefix="\n") subst =
42   String.concat prefix
43     (List.map
44        (fun (i, (c, t, ty)) ->
45           Printf.sprintf "?%d -> %s : %s" i
46             (CicPp.ppterm t) (CicPp.ppterm ty))
47        subst)
48 ;;  
49
50 (* (weight of constants, [(meta, weight_of_meta)]) *)
51 type weight = int * (int * int) list;;
52
53 let string_of_weight (cw, mw) =
54   let s =
55     String.concat ", "
56       (List.map (function (m, w) -> Printf.sprintf "(%d,%d)" m w) mw)
57   in
58   Printf.sprintf "[%d; %s]" cw s
59
60
61 let weight_of_term ?(consider_metas=true) term =
62   let module C = Cic in
63   let vars_dict = Hashtbl.create 5 in
64   let rec aux = function
65     | C.Meta (metano, _) when consider_metas ->
66         (try
67            let oldw = Hashtbl.find vars_dict metano in
68            Hashtbl.replace vars_dict metano (oldw+1)
69          with Not_found ->
70            Hashtbl.add vars_dict metano 1);
71         0
72     | C.Meta _ -> 0 (* "variables" are lighter than constants and functions...*)
73                   
74     | C.Var (_, ens)
75     | C.Const (_, ens)
76     | C.MutInd (_, _, ens)
77     | C.MutConstruct (_, _, _, ens) ->
78         List.fold_left (fun w (u, t) -> (aux t) + w) 1 ens
79           
80     | C.Cast (t1, t2)
81     | C.Lambda (_, t1, t2)
82     | C.Prod (_, t1, t2)
83     | C.LetIn (_, t1, t2) ->
84         let w1 = aux t1 in
85         let w2 = aux t2 in
86         w1 + w2 + 1
87           
88     | C.Appl l -> List.fold_left (+) 0 (List.map aux l)
89         
90     | C.MutCase (_, _, outt, t, pl) ->
91         let w1 = aux outt in
92         let w2 = aux t in
93         let w3 = List.fold_left (+) 0 (List.map aux pl) in
94         w1 + w2 + w3 + 1
95           
96     | C.Fix (_, fl) ->
97         List.fold_left (fun w (n, i, t1, t2) -> (aux t1) + (aux t2) + w) 1 fl
98           
99     | C.CoFix (_, fl) ->
100         List.fold_left (fun w (n, t1, t2) -> (aux t1) + (aux t2) + w) 1 fl
101           
102     | _ -> 1
103   in
104   let w = aux term in
105   let l =
106     Hashtbl.fold (fun meta metaw resw -> (meta, metaw)::resw) vars_dict [] in
107   let compare w1 w2 = 
108     match w1, w2 with
109     | (m1, _), (m2, _) -> m2 - m1 
110   in
111   (w, List.sort compare l) (* from the biggest meta to the smallest (0) *)
112 ;;
113
114
115 module OrderedInt = struct
116   type t = int
117
118   let compare = Pervasives.compare
119 end
120
121 module IntSet = Set.Make(OrderedInt)
122
123 let compute_equality_weight ty left right =
124   let metasw = ref 0 in
125   let weight_of t =
126     let w, m = (weight_of_term ~consider_metas:true t) in
127     metasw := !metasw + (2 * (List.length m));
128     w
129   in
130   (* Warning: the following let cannot be expanded since it forces the
131      right evaluation order!!!! *)
132   let w = (weight_of ty) + (weight_of left) + (weight_of right) in
133   w + !metasw
134 ;;
135
136
137 (* returns a "normalized" version of the polynomial weight wl (with type
138  * weight list), i.e. a list sorted ascending by meta number,
139  * from 0 to maxmeta. wl must be sorted descending by meta number. Example:
140  * normalize_weight 5 (3, [(3, 2); (1, 1)]) ->
141  *      (3, [(1, 1); (2, 0); (3, 2); (4, 0); (5, 0)]) *)
142 let normalize_weight maxmeta (cw, wl) =
143   let rec aux = function
144     | 0 -> []
145     | m -> (m, 0)::(aux (m-1))
146   in
147   let tmpl = aux maxmeta in
148   let wl =
149     List.sort
150       (fun (m, _) (n, _) -> Pervasives.compare m n)
151       (List.fold_left
152          (fun res (m, w) -> (m, w)::(List.remove_assoc m res)) tmpl wl)
153   in
154   (cw, wl)
155 ;;
156
157
158 let normalize_weights (cw1, wl1) (cw2, wl2) =
159   let rec aux wl1 wl2 =
160     match wl1, wl2 with
161     | [], [] -> [], []
162     | (m, w)::tl1, (n, w')::tl2 when m = n ->
163         let res1, res2 = aux tl1 tl2 in
164         (m, w)::res1, (n, w')::res2
165     | (m, w)::tl1, ((n, w')::_ as wl2) when m < n ->
166         let res1, res2 = aux tl1 wl2 in
167         (m, w)::res1, (m, 0)::res2
168     | ((m, w)::_ as wl1), (n, w')::tl2 when m > n ->
169         let res1, res2 = aux wl1 tl2 in
170         (n, 0)::res1, (n, w')::res2
171     | [], (n, w)::tl2 ->
172         let res1, res2 = aux [] tl2 in
173         (n, 0)::res1, (n, w)::res2
174     | (m, w)::tl1, [] ->
175         let res1, res2 = aux tl1 [] in
176         (m, w)::res1, (m, 0)::res2
177     | _, _ -> assert false
178   in
179   let cmp (m, _) (n, _) = compare m n in
180   let wl1, wl2 = aux (List.sort cmp wl1) (List.sort cmp wl2) in
181   (cw1, wl1), (cw2, wl2)
182 ;;
183
184         
185 type comparison = Lt | Le | Eq | Ge | Gt | Incomparable;;
186     
187 let string_of_comparison = function
188   | Lt -> "<"
189   | Le -> "<="
190   | Gt -> ">"
191   | Ge -> ">="
192   | Eq -> "="
193   | Incomparable -> "I"
194
195
196 let compare_weights ?(normalize=false)
197     ((h1, w1) as weight1) ((h2, w2) as weight2)=
198   let (h1, w1), (h2, w2) =
199     if normalize then
200       normalize_weights weight1 weight2
201     else
202       (h1, w1), (h2, w2)
203   in
204   let res, diffs =
205     try
206       List.fold_left2
207         (fun ((lt, eq, gt), diffs) w1 w2 ->
208            match w1, w2 with
209            | (meta1, w1), (meta2, w2) when meta1 = meta2 ->
210                let diffs = (w1 - w2) + diffs in 
211                let r = compare w1 w2 in
212                if r < 0 then (lt+1, eq, gt), diffs
213                else if r = 0 then (lt, eq+1, gt), diffs
214                else (lt, eq, gt+1), diffs
215            | (meta1, w1), (meta2, w2) ->
216                debug_print
217                  (lazy
218                     (Printf.sprintf "HMMM!!!! %s, %s\n"
219                        (string_of_weight weight1) (string_of_weight weight2)));
220                assert false)
221         ((0, 0, 0), 0) w1 w2
222     with Invalid_argument _ ->
223       debug_print
224         (lazy
225            (Printf.sprintf "Invalid_argument: %s{%s}, %s{%s}, normalize = %s\n"
226               (string_of_weight (h1, w1)) (string_of_weight weight1)
227               (string_of_weight (h2, w2)) (string_of_weight weight2)
228               (string_of_bool normalize)));
229       assert false
230   in
231   let hdiff = h1 - h2 in
232   match res with
233   | (0, _, 0) ->
234       if hdiff < 0 then Lt
235       else if hdiff > 0 then Gt
236       else Eq (* Incomparable *)
237   | (m, _, 0) ->
238       if hdiff <= 0 then 
239         if m > 0 || hdiff < 0 then Lt
240         else if diffs >= (- hdiff) then Le else Incomparable
241       else 
242         if diffs >= (- hdiff) then Le else Incomparable
243   | (0, _, m) ->
244       if hdiff >= 0 then 
245         if m > 0 || hdiff > 0 then Gt
246         else if (- diffs) >= hdiff then Ge else Incomparable
247       else
248         if (- diffs) >= hdiff then Ge else Incomparable
249   | (m, _, n) when m > 0 && n > 0 ->
250       Incomparable
251   | _ -> assert false
252 ;;
253
254
255 let rec aux_ordering ?(recursion=true) t1 t2 =
256   let module C = Cic in
257   let compare_uris u1 u2 =
258     let res =
259       compare (UriManager.string_of_uri u1) (UriManager.string_of_uri u2) in
260     if res < 0 then Lt
261     else if res = 0 then Eq
262     else Gt
263   in
264   match t1, t2 with
265   | C.Meta _, _
266   | _, C.Meta _ -> Incomparable
267
268   | t1, t2 when t1 = t2 -> Eq
269
270   | C.Rel n, C.Rel m -> if n > m then Lt else Gt
271   | C.Rel _, _ -> Lt
272   | _, C.Rel _ -> Gt
273
274   | C.Const (u1, _), C.Const (u2, _) -> compare_uris u1 u2
275   | C.Const _, _ -> Lt
276   | _, C.Const _ -> Gt
277
278   | C.MutInd (u1, _, _), C.MutInd (u2, _, _) -> compare_uris u1 u2
279   | C.MutInd _, _ -> Lt
280   | _, C.MutInd _ -> Gt
281
282   | C.MutConstruct (u1, _, _, _), C.MutConstruct (u2, _, _, _) ->
283       compare_uris u1 u2
284   | C.MutConstruct _, _ -> Lt
285   | _, C.MutConstruct _ -> Gt
286
287   | C.Appl l1, C.Appl l2 when recursion ->
288       let rec cmp t1 t2 =
289         match t1, t2 with
290         | [], [] -> Eq
291         | _, [] -> Gt
292         | [], _ -> Lt
293         | hd1::tl1, hd2::tl2 ->
294             let o = aux_ordering hd1 hd2 in
295             if o = Eq then cmp tl1 tl2
296             else o
297       in
298       cmp l1 l2
299   | C.Appl (h1::t1), C.Appl (h2::t2) when not recursion ->
300       aux_ordering h1 h2
301         
302   | t1, t2 ->
303       debug_print
304         (lazy
305            (Printf.sprintf "These two terms are not comparable:\n%s\n%s\n\n"
306               (CicPp.ppterm t1) (CicPp.ppterm t2)));
307       Incomparable
308 ;;
309
310
311 (* w1, w2 are the weights, they should already be normalized... *)
312 let nonrec_kbo_w (t1, w1) (t2, w2) =
313   match compare_weights w1 w2 with
314   | Le -> if aux_ordering t1 t2 = Lt then Lt else Incomparable
315   | Ge -> if aux_ordering t1 t2 = Gt then Gt else Incomparable
316   | Eq -> aux_ordering t1 t2
317   | res -> res
318 ;;
319
320     
321 let nonrec_kbo t1 t2 =
322   let w1 = weight_of_term t1 in
323   let w2 = weight_of_term t2 in
324   match compare_weights ~normalize:true w1 w2 with
325   | Le -> if aux_ordering t1 t2 = Lt then Lt else Incomparable
326   | Ge -> if aux_ordering t1 t2 = Gt then Gt else Incomparable
327   | Eq -> aux_ordering t1 t2
328   | res -> res
329 ;;
330
331
332 let rec kbo t1 t2 =
333   let aux = aux_ordering ~recursion:false in
334   let w1 = weight_of_term t1
335   and w2 = weight_of_term t2 in
336   let rec cmp t1 t2 =
337     match t1, t2 with
338     | [], [] -> Eq
339     | _, [] -> Gt
340     | [], _ -> Lt
341     | hd1::tl1, hd2::tl2 ->
342         let o =
343           kbo hd1 hd2
344         in
345         if o = Eq then cmp tl1 tl2
346         else o
347   in
348   let comparison = compare_weights ~normalize:true w1 w2 in
349   match comparison with
350   | Le ->
351       let r = aux t1 t2 in
352       if r = Lt then Lt
353       else if r = Eq then (
354         match t1, t2 with
355         | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
356             if cmp tl1 tl2 = Lt then Lt else Incomparable
357         | _, _ ->  Incomparable
358       ) else Incomparable
359   | Ge ->
360       let r = aux t1 t2 in
361       if r = Gt then Gt
362       else if r = Eq then (
363         match t1, t2 with
364         | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
365             if cmp tl1 tl2 = Gt then Gt else Incomparable
366         | _, _ ->  Incomparable
367       ) else Incomparable
368   | Eq ->
369       let r = aux t1 t2 in
370       if r = Eq then (
371         match t1, t2 with
372         | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
373             cmp tl1 tl2
374         | _, _ ->  Incomparable
375       ) else r 
376   | res -> res
377 ;;
378           
379 let rec ao t1 t2 =
380   let get_hd t =
381     match t with
382         Cic.MutConstruct(uri,tyno,cno,_) -> Some(uri,tyno,cno)
383       | Cic.Appl(Cic.MutConstruct(uri,tyno,cno,_)::_) -> 
384           Some(uri,tyno,cno)
385       | _ -> None in
386   let aux = aux_ordering ~recursion:false in
387   let w1 = weight_of_term t1
388   and w2 = weight_of_term t2 in
389   let rec cmp t1 t2 =
390     match t1, t2 with
391     | [], [] -> Eq
392     | _, [] -> Gt
393     | [], _ -> Lt
394     | hd1::tl1, hd2::tl2 ->
395         let o =
396           ao hd1 hd2
397         in
398         if o = Eq then cmp tl1 tl2
399         else o
400   in
401   match get_hd t1, get_hd t2 with
402       Some(_),None -> Lt
403     | None,Some(_) -> Gt
404     | _ ->
405         let comparison = compare_weights ~normalize:true w1 w2 in
406           match comparison with
407             | Le ->
408                 let r = aux t1 t2 in
409                   if r = Lt then Lt
410                   else if r = Eq then (
411                     match t1, t2 with
412                       | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
413                           if cmp tl1 tl2 = Lt then Lt else Incomparable
414                       | _, _ ->  Incomparable
415                   ) else Incomparable
416             | Ge ->
417                 let r = aux t1 t2 in
418                   if r = Gt then Gt
419                   else if r = Eq then (
420                     match t1, t2 with
421                       | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
422                           if cmp tl1 tl2 = Gt then Gt else Incomparable
423                       | _, _ ->  Incomparable
424                   ) else Incomparable
425             | Eq ->
426                 let r = aux t1 t2 in
427                   if r = Eq then (
428                     match t1, t2 with
429                       | Cic.Appl (h1::tl1), Cic.Appl (h2::tl2) when h1 = h2 ->
430                           cmp tl1 tl2
431                       | _, _ ->  Incomparable
432                   ) else r 
433             | res -> res
434 ;;
435
436 let names_of_context context = 
437   List.map
438     (function
439        | None -> None
440        | Some (n, e) -> Some n)
441     context
442 ;;
443
444
445 module OrderedTerm =
446 struct
447   type t = Cic.term
448       
449   let compare = Pervasives.compare
450 end
451
452 module TermSet = Set.Make(OrderedTerm);;
453 module TermMap = Map.Make(OrderedTerm);;
454
455 let symbols_of_term term =
456   let module C = Cic in
457   let rec aux map = function
458     | C.Meta _ -> map
459     | C.Appl l ->
460         List.fold_left (fun res t -> (aux res t)) map l
461     | t ->
462         let map = 
463           try
464             let c = TermMap.find t map in
465             TermMap.add t (c+1) map
466           with Not_found ->
467             TermMap.add t 1 map
468         in
469         map
470   in
471   aux TermMap.empty term
472 ;;
473
474
475 let metas_of_term term =
476   let module C = Cic in
477   let rec aux = function
478     | C.Meta _ as t -> TermSet.singleton t
479     | C.Appl l ->
480         List.fold_left (fun res t -> TermSet.union res (aux t)) TermSet.empty l
481     | t -> TermSet.empty (* TODO: maybe add other cases? *)
482   in
483   aux term
484 ;;
485
486
487 let rec lpo t1 t2 =
488   let module C = Cic in
489   match t1, t2 with
490   | t1, t2 when t1 = t2 -> Eq
491   | t1, (C.Meta _ as m) ->
492       if TermSet.mem m (metas_of_term t1) then Gt else Incomparable
493   | (C.Meta _ as m), t2 ->
494       if TermSet.mem m (metas_of_term t2) then Lt else Incomparable
495   | C.Appl (hd1::tl1), C.Appl (hd2::tl2) -> (
496       let res =
497         let f o r t =
498           if r then true else
499             match lpo t o with
500             | Gt | Eq -> true
501             | _ -> false
502         in
503         let res1 = List.fold_left (f t2) false tl1 in
504         if res1 then Gt
505         else let res2 = List.fold_left (f t1) false tl2 in
506         if res2 then Lt
507         else Incomparable
508       in
509       if res <> Incomparable then
510         res
511       else
512         let f o r t =
513           if not r then false else
514             match lpo o t with
515             | Gt -> true
516             | _ -> false
517         in
518         match aux_ordering hd1 hd2 with
519         | Gt ->
520             let res = List.fold_left (f t1) false tl2 in
521             if res then Gt
522             else Incomparable
523         | Lt ->
524             let res = List.fold_left (f t2) false tl1 in
525             if res then Lt
526             else Incomparable
527         | Eq -> (
528             let lex_res =
529               try
530                 List.fold_left2
531                   (fun r t1 t2 -> if r <> Eq then r else lpo t1 t2)
532                   Eq tl1 tl2
533               with Invalid_argument _ ->
534                 Incomparable
535             in
536             match lex_res with
537             | Gt ->
538                 if List.fold_left (f t1) false tl2 then Gt
539                 else Incomparable
540             | Lt ->
541                 if List.fold_left (f t2) false tl1 then Lt
542                 else Incomparable
543             | _ -> Incomparable
544           )
545         | _ -> Incomparable
546     )
547   | t1, t2 -> aux_ordering t1 t2
548 ;;
549
550
551 (* settable by the user... *)
552 (* let compare_terms = ref nonrec_kbo;; *)
553 let compare_terms = ref ao;;
554
555 let guarded_simpl context t =
556   let t' = ProofEngineReduction.simpl context t in
557   let simpl_order = !compare_terms t t' in
558   if simpl_order = Gt then 
559     (prerr_endline ("reduce: "^(CicPp.ppterm t)^(CicPp.ppterm t'));
560      t')
561   else t
562 ;;
563
564 type equality_sign = Negative | Positive;;
565
566 let string_of_sign = function
567   | Negative -> "Negative"
568   | Positive -> "Positive"
569 ;;
570
571
572 type pos = Left | Right 
573
574 let string_of_pos = function
575   | Left -> "Left"
576   | Right -> "Right"
577 ;;
578
579
580 let eq_ind_URI () = LibraryObjects.eq_ind_URI ~eq:(LibraryObjects.eq_URI ())
581 let eq_ind_r_URI () = LibraryObjects.eq_ind_r_URI ~eq:(LibraryObjects.eq_URI ())
582 let sym_eq_URI () = LibraryObjects.sym_eq_URI ~eq:(LibraryObjects.eq_URI ())
583 let eq_XURI () =
584   let s = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
585   UriManager.uri_of_string (s ^ "#xpointer(1/1/1)")
586 let trans_eq_URI () = LibraryObjects.trans_eq_URI ~eq:(LibraryObjects.eq_URI ())