]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/ocaml/paramodulation/indexing.ml
ocaml 3.09 transition
[helm.git] / helm / ocaml / paramodulation / indexing.ml
index 5b84bb72ade6e5afc5b1b76354b3bef66fa28a3d..c964e3a78c882f525df690c230ec60e18abd1eb4 100644 (file)
@@ -1,3 +1,27 @@
+(* Copyright (C) 2005, HELM Team.
+ * 
+ * This file is part of HELM, an Hypertextual, Electronic
+ * Library of Mathematics, developed at the Computer Science
+ * Department, University of Bologna, Italy.
+ * 
+ * HELM is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * 
+ * HELM is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HELM; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
+ * MA  02111-1307, USA.
+ * 
+ * For details, see the HELM World-Wide-Web page,
+ * http://cs.unibo.it/helm/.
+ *)
 
 let debug_print = Utils.debug_print;;
 
@@ -27,55 +51,14 @@ let print_candidates mode term res =
 let indexing_retrieval_time = ref 0.;;
 
 
-(* let my_apply_subst subst term = *)
-(*   let module C = Cic in *)
-(*   let lookup lift_amount meta = *)
-(*     match meta with *)
-(*     | C.Meta (i, _) -> ( *)
-(*         try *)
-(*           let _, (_, t, _) = List.find (fun (m, _) -> m = i) subst in *)
-(*           (\* CicSubstitution.lift lift_amount  *\)t *)
-(*         with Not_found -> meta *)
-(*       ) *)
-(*     | _ -> assert false *)
-(*   in *)
-(*   let rec apply_aux lift_amount =  function *)
-(*     | C.Meta (i, l) as t -> lookup lift_amount t *)
-(*     | C.Appl l -> C.Appl (List.map (apply_aux lift_amount) l) *)
-(*     | C.Prod (nn, s, t) -> *)
-(*         C.Prod (nn, apply_aux lift_amount s, apply_aux (lift_amount+1) t) *)
-(*     | C.Lambda (nn, s, t) -> *)
-(*         C.Lambda (nn, apply_aux lift_amount s, apply_aux (lift_amount+1) t) *)
-(*     | t -> t *)
-(*   in *)
-(*   apply_aux 0 term *)
-(* ;; *)
-
-
-(* let apply_subst subst term = *)
-(*   Printf.printf "| apply_subst:\n| subst: %s\n| term: %s\n" *)
-(*     (Utils.print_subst ~prefix:" ; " subst) (CicPp.ppterm term); *)
-(*   let res = my_apply_subst subst term in *)
-(* (\*   let res = CicMetaSubst.apply_subst subst term in *\) *)
-(*   Printf.printf "| res: %s\n" (CicPp.ppterm res); *)
-(*   print_endline "|"; *)
-(*   res *)
-(* ;; *)
-
-(* let apply_subst = my_apply_subst *)
 let apply_subst = CicMetaSubst.apply_subst
 
 
-(* Profiling code
-let apply_subst =
-  let profile = CicUtil.profile "apply_subst" in
-  (fun s a -> profile.profile (apply_subst s) a)
-;;
-*)
-
 
 (*
 (* NO INDEXING *)
+let init_index () = ()
+  
 let empty_table () = []
 
 let index table equality =
@@ -100,6 +83,8 @@ let get_candidates mode table term = table
 
 (*
 (* PATH INDEXING *)
+let init_index () = ()
+
 let empty_table () =
   Path_indexing.PSTrie.empty
 ;;
@@ -128,6 +113,10 @@ let get_candidates mode trie term =
 
 
 (* DISCRIMINATION TREES *)
+let init_index () =
+  Hashtbl.clear Discrimination_tree.arities;
+;;
+
 let empty_table () =
   Discrimination_tree.DiscriminationTree.empty
 ;;
@@ -155,16 +144,16 @@ let get_candidates mode tree term =
 ;;
 
 
-(* let get_candidates = *)
-(*   let profile = CicUtil.profile "Indexing.get_candidates" in *)
-(*   (fun mode tree term -> profile.profile (get_candidates mode tree) term) *)
-(* ;; *)
-
-
 let match_unif_time_ok = ref 0.;;
 let match_unif_time_no = ref 0.;;
 
 
+(*
+  finds the first equality in the index that matches "term", of type "termty"
+  termty can be Implicit if it is not needed. The result (one of the sides of
+  the equality, actually) should be not greater (wrt the term ordering) than
+  term
+*)
 let rec find_matches metasenv context ugraph lift_amount term termty =
   let module C = Cic in
   let module U = Utils in
@@ -172,22 +161,16 @@ let rec find_matches metasenv context ugraph lift_amount term termty =
   let module M = CicMetaSubst in
   let module HL = HelmLibraryObjects in
   let cmp = !Utils.compare_terms in
-(*   let names = Utils.names_of_context context in *)
-(*   let termty, ugraph = *)
-(*     CicTypeChecker.type_of_aux' metasenv context term ugraph *)
-(*   in *)
+  let check = match termty with C.Implicit None -> false | _ -> true in
   function
     | [] -> None
     | candidate::tl ->
         let pos, (_, proof, (ty, left, right, o), metas, args) = candidate in
-(*         if not (fst (CicReduction.are_convertible *)
-(*                        ~metasenv context termty ty ugraph)) then ( *)
-(* (\*           debug_print (lazy ( *\) *)
-(* (\*             Printf.sprintf "CANDIDATE HAS WRONG TYPE: %s required, %s found" *\) *)
-(* (\*               (CicPp.pp termty names) (CicPp.pp ty names))); *\) *)
-(*           find_matches metasenv context ugraph lift_amount term termty tl *)
-(*         ) else *)
-          let do_match c other eq_URI =
+        if check && not (fst (CicReduction.are_convertible
+                                ~metasenv context termty ty ugraph)) then (
+          find_matches metasenv context ugraph lift_amount term termty tl
+        ) else
+          let do_match c eq_URI =
             let subst', metasenv', ugraph' =
               let t1 = Unix.gettimeofday () in
               try
@@ -206,23 +189,23 @@ let rec find_matches metasenv context ugraph lift_amount term termty =
                   (candidate, eq_URI))
           in
           let c, other, eq_URI =
-            if pos = Utils.Left then left, right, HL.Logic.eq_ind_URI
-            else right, left, HL.Logic.eq_ind_r_URI
+            if pos = Utils.Left then left, right, Utils.eq_ind_URI ()
+            else right, left, Utils.eq_ind_r_URI ()
           in
           if o <> U.Incomparable then
             try
-              do_match c other eq_URI
+              do_match c eq_URI
             with Inference.MatchingFailure ->
               find_matches metasenv context ugraph lift_amount term termty tl
           else
             let res =
-              try do_match c other eq_URI
+              try do_match c eq_URI
               with Inference.MatchingFailure -> None
             in
             match res with
             | Some (_, s, _, _, _) ->
-                let c' = (* M. *)apply_subst s c
-                and other' = (* M. *)apply_subst s other in
+                let c' = apply_subst s c
+                and other' = apply_subst s other in
                 let order = cmp c' other' in
                 let names = U.names_of_context context in
                 if order = U.Gt then
@@ -235,6 +218,10 @@ let rec find_matches metasenv context ugraph lift_amount term termty =
 ;;
 
 
+(*
+  as above, but finds all the matching equalities, and the matching condition
+  can be either Inference.matching or Inference.unification
+*)
 let rec find_all_matches ?(unif_fun=Inference.unification)
     metasenv context ugraph lift_amount term termty =
   let module C = Cic in
@@ -243,84 +230,75 @@ let rec find_all_matches ?(unif_fun=Inference.unification)
   let module M = CicMetaSubst in
   let module HL = HelmLibraryObjects in
   let cmp = !Utils.compare_terms in
-(*   let names = Utils.names_of_context context in *)
-(*   let termty, ugraph = *)
-(*     CicTypeChecker.type_of_aux' metasenv context term ugraph *)
-(*   in *)
   function
     | [] -> []
     | candidate::tl ->
         let pos, (_, _, (ty, left, right, o), metas, args) = candidate in
-(*         if not (fst (CicReduction.are_convertible *)
-(*                        ~metasenv context termty ty ugraph)) then ( *)
-(* (\*           debug_print (lazy ( *\) *)
-(* (\*             Printf.sprintf "CANDIDATE HAS WRONG TYPE: %s required, %s found" *\) *)
-(* (\*               (CicPp.pp termty names) (CicPp.pp ty names))); *\) *)
-(*           find_all_matches ~unif_fun metasenv context ugraph *)
-(*             lift_amount term termty tl *)
-(*         ) else *)
-          let do_match c other eq_URI =
-            let subst', metasenv', ugraph' =
-              let t1 = Unix.gettimeofday () in
-              try
-                let r = 
-                  unif_fun (metasenv @ metas) context
-                    term (S.lift lift_amount c) ugraph in
-                let t2 = Unix.gettimeofday () in
-                match_unif_time_ok := !match_unif_time_ok +. (t2 -. t1);
-                r
-              with
-              | Inference.MatchingFailure
-              | CicUnification.UnificationFailure _
-              | CicUnification.Uncertain _ as e ->
-                let t2 = Unix.gettimeofday () in
-                match_unif_time_no := !match_unif_time_no +. (t2 -. t1);
-                raise e
-            in
-            (C.Rel (1 + lift_amount), subst', metasenv', ugraph',
-             (candidate, eq_URI))
-          in
-          let c, other, eq_URI =
-            if pos = Utils.Left then left, right, HL.Logic.eq_ind_URI
-            else right, left, HL.Logic.eq_ind_r_URI
-          in
-          if o <> U.Incomparable then
+        let do_match c eq_URI =
+          let subst', metasenv', ugraph' =
+            let t1 = Unix.gettimeofday () in
             try
-              let res = do_match c other eq_URI in
-              res::(find_all_matches ~unif_fun metasenv context ugraph
-                      lift_amount term termty tl)
+              let r = 
+                unif_fun (metasenv @ metas) context
+                  term (S.lift lift_amount c) ugraph in
+              let t2 = Unix.gettimeofday () in
+              match_unif_time_ok := !match_unif_time_ok +. (t2 -. t1);
+              r
             with
             | Inference.MatchingFailure
             | CicUnification.UnificationFailure _
-            | CicUnification.Uncertain _ ->
+            | CicUnification.Uncertain _ as e ->
+                let t2 = Unix.gettimeofday () in
+                match_unif_time_no := !match_unif_time_no +. (t2 -. t1);
+                raise e
+          in
+          (C.Rel (1 + lift_amount), subst', metasenv', ugraph',
+           (candidate, eq_URI))
+        in
+        let c, other, eq_URI =
+          if pos = Utils.Left then left, right, Utils.eq_ind_URI ()
+          else right, left, Utils.eq_ind_r_URI ()
+        in
+        if o <> U.Incomparable then
+          try
+            let res = do_match c eq_URI in
+            res::(find_all_matches ~unif_fun metasenv context ugraph
+                    lift_amount term termty tl)
+          with
+          | Inference.MatchingFailure
+          | CicUnification.UnificationFailure _
+          | CicUnification.Uncertain _ ->
+              find_all_matches ~unif_fun metasenv context ugraph
+                lift_amount term termty tl
+        else
+          try
+            let res = do_match c eq_URI in
+            match res with
+            | _, s, _, _, _ ->
+                let c' = apply_subst s c
+                and other' = apply_subst s other in
+                let order = cmp c' other' in
+                let names = U.names_of_context context in
+                if order <> U.Lt && order <> U.Le then
+                  res::(find_all_matches ~unif_fun metasenv context ugraph
+                          lift_amount term termty tl)
+                else
+                  find_all_matches ~unif_fun metasenv context ugraph
+                    lift_amount term termty tl
+          with
+          | Inference.MatchingFailure
+          | CicUnification.UnificationFailure _
+          | CicUnification.Uncertain _ ->
               find_all_matches ~unif_fun metasenv context ugraph
                 lift_amount term termty tl
-          else
-            try
-              let res = do_match c other eq_URI in
-              match res with
-              | _, s, _, _, _ ->
-                  let c' = (* M. *)apply_subst s c
-                  and other' = (* M. *)apply_subst s other in
-                  let order = cmp c' other' in
-                  let names = U.names_of_context context in
-                  if order <> U.Lt && order <> U.Le then
-                    res::(find_all_matches ~unif_fun metasenv context ugraph
-                            lift_amount term termty tl)
-                  else
-                    find_all_matches ~unif_fun metasenv context ugraph
-                      lift_amount term termty tl
-            with
-            | Inference.MatchingFailure
-            | CicUnification.UnificationFailure _
-            | CicUnification.Uncertain _ ->
-                find_all_matches ~unif_fun metasenv context ugraph
-                  lift_amount term termty tl
 ;;
 
 
+(*
+  returns true if target is subsumed by some equality in table
+*)
 let subsumption env table target =
-  let _, (ty, left, right, _), tmetas, _ = target in
+  let _, _, (ty, left, right, _), tmetas, _ = target in
   let metasenv, context, ugraph = env in
   let metasenv = metasenv @ tmetas in
   let samesubst subst subst' =
@@ -344,43 +322,58 @@ let subsumption env table target =
         find_all_matches ~unif_fun:Inference.matching
           metasenv context ugraph 0 left ty leftc
   in
-  let ok what (_, subst, menv, ug, ((pos, (_, _, (_, l, r, o), _, _)), _)) =
-    try
-      let other = if pos = Utils.Left then r else l in
-      let subst', menv', ug' =
-        let t1 = Unix.gettimeofday () in
+  let rec ok what = function
+    | [] -> false, []
+    | (_, subst, menv, ug, ((pos, (_, _, (_, l, r, o), m, _)), _))::tl ->
         try
-          let r = 
-            Inference.matching metasenv context what other ugraph in
-          let t2 = Unix.gettimeofday () in
-          match_unif_time_ok := !match_unif_time_ok +. (t2 -. t1);
-          r
-        with Inference.MatchingFailure as e ->
-          let t2 = Unix.gettimeofday () in
-          match_unif_time_no := !match_unif_time_no +. (t2 -. t1);
-          raise e
+          let other = if pos = Utils.Left then r else l in
+          let subst', menv', ug' =
+            let t1 = Unix.gettimeofday () in
+            try
+              let r = 
+                Inference.matching (metasenv @ menv @ m) context what other ugraph
+             in
+              let t2 = Unix.gettimeofday () in
+              match_unif_time_ok := !match_unif_time_ok +. (t2 -. t1);
+              r
+            with Inference.MatchingFailure as e ->
+              let t2 = Unix.gettimeofday () in
+              match_unif_time_no := !match_unif_time_no +. (t2 -. t1);
+              raise e
+          in
+          if samesubst subst subst' then
+            true, subst
+          else
+            ok what tl
+        with Inference.MatchingFailure ->
+          ok what tl
+  in
+  let r, subst = ok right leftr in
+  let r, s =
+    if r then
+      true, subst
+    else
+      let rightr =
+       match right with
+         | Cic.Meta _ -> []
+         | _ ->
+              let rightc = get_candidates Matching table right in
+               find_all_matches ~unif_fun:Inference.matching
+                 metasenv context ugraph 0 right ty rightc
       in
-      samesubst subst subst'
-    with Inference.MatchingFailure ->
-      false
+       ok left rightr
   in
-  let r = List.exists (ok right) leftr in
-  if r then
-    true
-  else
-    let rightr =
-      match right with
-      | Cic.Meta _ -> []
-      | _ ->
-          let rightc = get_candidates Matching table right in
-          find_all_matches ~unif_fun:Inference.matching
-            metasenv context ugraph 0 right ty rightc
-    in
-    List.exists (ok left) rightr
+    (if r then 
+       debug_print 
+        (lazy
+           (Printf.sprintf "SUBSUMPTION! %s\n%s\n"
+              (Inference.string_of_equality target) (Utils.print_subst s))));
+    r, s
 ;;
 
 
-let rec demodulate_term metasenv context ugraph table lift_amount term =
+let rec demodulation_aux ?(typecheck=false)
+    metasenv context ugraph table lift_amount term =
   let module C = Cic in
   let module S = CicSubstitution in
   let module M = CicMetaSubst in
@@ -390,8 +383,10 @@ let rec demodulate_term metasenv context ugraph table lift_amount term =
   | C.Meta _ -> None
   | term ->
       let termty, ugraph =
-        C.Implicit None, ugraph
-(*         CicTypeChecker.type_of_aux' metasenv context term ugraph *)
+        if typecheck then
+          CicTypeChecker.type_of_aux' metasenv context term ugraph
+        else
+          C.Implicit None, ugraph
       in
       let res =
         find_matches metasenv context ugraph lift_amount term termty candidates
@@ -408,7 +403,7 @@ let rec demodulate_term metasenv context ugraph table lift_amount term =
                      (res, tl @ [S.lift 1 t])
                    else 
                      let r =
-                       demodulate_term metasenv context ugraph table
+                       demodulation_aux metasenv context ugraph table
                          lift_amount t
                      in
                      match r with
@@ -423,11 +418,11 @@ let rec demodulate_term metasenv context ugraph table lift_amount term =
             )
         | C.Prod (nn, s, t) ->
             let r1 =
-              demodulate_term metasenv context ugraph table lift_amount s in (
+              demodulation_aux metasenv context ugraph table lift_amount s in (
               match r1 with
               | None ->
                   let r2 =
-                    demodulate_term metasenv
+                    demodulation_aux metasenv
                       ((Some (nn, C.Decl s))::context) ugraph
                       table (lift_amount+1) t
                   in (
@@ -441,27 +436,38 @@ let rec demodulate_term metasenv context ugraph table lift_amount term =
                   Some (C.Prod (nn, s', (S.lift 1 t)),
                         subst, menv, ug, eq_found)
             )
+        | C.Lambda (nn, s, t) ->
+            let r1 =
+              demodulation_aux metasenv context ugraph table lift_amount s in (
+              match r1 with
+              | None ->
+                  let r2 =
+                    demodulation_aux metasenv
+                      ((Some (nn, C.Decl s))::context) ugraph
+                      table (lift_amount+1) t
+                  in (
+                    match r2 with
+                    | None -> None
+                    | Some (t', subst, menv, ug, eq_found) ->
+                        Some (C.Lambda (nn, (S.lift 1 s), t'),
+                              subst, menv, ug, eq_found)
+                  )
+              | Some (s', subst, menv, ug, eq_found) ->
+                  Some (C.Lambda (nn, s', (S.lift 1 t)),
+                        subst, menv, ug, eq_found)
+            )
         | t ->
             None
 ;;
 
 
-let build_ens_for_sym_eq ty x y = 
-  [(UriManager.uri_of_string
-      "cic:/Coq/Init/Logic/Logic_lemmas/equality/A.var", ty);
-   (UriManager.uri_of_string
-      "cic:/Coq/Init/Logic/Logic_lemmas/equality/x.var", x);
-   (UriManager.uri_of_string
-      "cic:/Coq/Init/Logic/Logic_lemmas/equality/y.var", y)]
-;;
-
-
 let build_newtarget_time = ref 0.;;
 
 
 let demod_counter = ref 1;;
 
-let rec demodulation newmeta env table sign target =
+(** demodulation, when target is an equality *)
+let rec demodulation_equality newmeta env table sign target =
   let module C = Cic in
   let module S = CicSubstitution in
   let module M = CicMetaSubst in
@@ -476,38 +482,40 @@ let rec demodulation newmeta env table sign target =
     let time1 = Unix.gettimeofday () in
     
     let pos, (_, proof', (ty, what, other, _), menv', args') = eq_found in
+    let ty =
+      try fst (CicTypeChecker.type_of_aux' metasenv context what ugraph)
+      with CicUtil.Meta_not_found _ -> ty
+    in
     let what, other = if pos = Utils.Left then what, other else other, what in
     let newterm, newproof =
-      let bo = (* M. *)apply_subst subst (S.subst other t) in
-      let t' =
-        let name = C.Name ("x_Demod_" ^ (string_of_int !demod_counter)) in
-        incr demod_counter;
-        let l, r =
-          if is_left then t, S.lift 1 right else S.lift 1 left, t in
-        (name, ty, S.lift 1 eq_ty, l, r)
+      let bo = apply_subst subst (S.subst other t) in
+      let name = C.Name ("x_Demod_" ^ (string_of_int !demod_counter)) in
+      incr demod_counter;
+      let bo' =
+        let l, r = if is_left then t, S.lift 1 right else S.lift 1 left, t in
+        C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []);
+                S.lift 1 eq_ty; l; r]
       in
       if sign = Utils.Positive then
         (bo,
-         Inference.ProofBlock (subst, eq_URI, t', eq_found, proof))
+         Inference.ProofBlock (
+           subst, eq_URI, (name, ty), bo'(* t' *), eq_found, proof))
       else
         let metaproof = 
           incr maxmeta;
           let irl =
             CicMkImplicit.identity_relocation_list_for_metavariable context in
-          Printf.printf "\nADDING META: %d\n" !maxmeta;
+          debug_print (lazy (Printf.sprintf "\nADDING META: %d\n" !maxmeta));
           print_newline ();
           C.Meta (!maxmeta, irl)
         in
-        let target' =
           let eq_found =
             let proof' =
-              let ens =
-                if pos = Utils.Left then
-                  build_ens_for_sym_eq ty what other
-                else
-                  build_ens_for_sym_eq ty other what
+              let termlist =
+                if pos = Utils.Left then [ty; what; other]
+                else [ty; other; what]
               in
-              Inference.ProofSymBlock (ens, proof')
+              Inference.ProofSymBlock (termlist, proof')
             in
             let what, other =
               if pos = Utils.Left then what, other else other, what
@@ -517,35 +525,30 @@ let rec demodulation newmeta env table sign target =
           in
           let target_proof =
             let pb =
-              Inference.ProofBlock (subst, eq_URI, t', eq_found,
-                                    Inference.BasicProof metaproof)
+              Inference.ProofBlock (subst, eq_URI, (name, ty), bo',
+                                    eq_found, Inference.BasicProof metaproof)
             in
             match proof with
             | Inference.BasicProof _ ->
                 print_endline "replacing a BasicProof";
                 pb
-            | Inference.ProofGoalBlock (_, parent_eq) ->
+            | Inference.ProofGoalBlock (_, parent_proof) ->
                 print_endline "replacing another ProofGoalBlock";
-                Inference.ProofGoalBlock (pb, parent_eq)
+                Inference.ProofGoalBlock (pb, parent_proof)
             | _ -> assert false
           in
-          (0, target_proof, (eq_ty, left, right, order), metas, args)
-        in
         let refl =
           C.Appl [C.MutConstruct (* reflexivity *)
-                    (HelmLibraryObjects.Logic.eq_URI, 0, 1, []);
+                    (LibraryObjects.eq_URI (), 0, 1, []);
                   eq_ty; if is_left then right else left]          
         in
         (bo,
-         Inference.ProofGoalBlock (Inference.BasicProof refl, target'))
+         Inference.ProofGoalBlock (Inference.BasicProof refl, target_proof))
     in
     let left, right = if is_left then newterm, right else left, newterm in
     let m = (Inference.metas_of_term left) @ (Inference.metas_of_term right) in
     let newmetasenv = List.filter (fun (i, _, _) -> List.mem i m) metas
-    and newargs =
-      List.filter
-        (function C.Meta (i, _) -> List.mem i m | _ -> assert false)
-        args
+    and newargs = args
     in
     let ordering = !Utils.compare_terms left right in
 
@@ -556,48 +559,58 @@ let rec demodulation newmeta env table sign target =
       let w = Utils.compute_equality_weight eq_ty left right in
       (w, newproof, (eq_ty, left, right, ordering), newmetasenv, newargs)
     in
-(*     if sign = Utils.Positive then ( *)
-(*       let newm, res = Inference.fix_metas !maxmeta res in *)
-(*       maxmeta := newm; *)
-(*       !maxmeta, res *)
-(*     ) else *)
-    !maxmeta(* newmeta *), res
+    !maxmeta, res
   in
-  let res = demodulate_term metasenv' context ugraph table 0 left in
-(*   let build_identity (w, p, (t, l, r, o), m, a) = *)
-(*     match o with *)
-(*     | Utils.Gt -> (w, p, (t, r, r, Utils.Eq), m, a) *)
-(*     | _ -> (w, p, (t, l, l, Utils.Eq), m, a) *)
-(*   in *)
-  match res with
-  | Some t ->
-      let newmeta, newtarget = build_newtarget true t in
-      if (Inference.is_identity (metasenv', context, ugraph) newtarget) ||
-        (Inference.meta_convertibility_eq target newtarget) then
-          newmeta, newtarget
-      else
-(*         if subsumption env table newtarget then *)
-(*           newmeta, build_identity newtarget *)
-(*         else *)
-        demodulation newmeta env table sign newtarget
-  | None ->
-      let res = demodulate_term metasenv' context ugraph table 0 right in
-      match res with
-      | Some t ->
-          let newmeta, newtarget = build_newtarget false t in
-          if (Inference.is_identity (metasenv', context, ugraph) newtarget) ||
+  let res = demodulation_aux metasenv' context ugraph table 0 left in
+  let newmeta, newtarget = 
+    match res with
+    | Some t ->
+       let newmeta, newtarget = build_newtarget true t in
+         if (Inference.is_identity (metasenv', context, ugraph) newtarget) ||
             (Inference.meta_convertibility_eq target newtarget) then
-              newmeta, newtarget
-          else
-(*             if subsumption env table newtarget then *)
-(*               newmeta, build_identity newtarget *)
-(*             else *)
-              demodulation newmeta env table sign newtarget
-      | None ->
-          newmeta, target
+             newmeta, newtarget
+         else
+            demodulation_equality newmeta env table sign newtarget
+    | None ->
+       let res = demodulation_aux metasenv' context ugraph table 0 right in
+         match res with
+         | Some t ->
+             let newmeta, newtarget = build_newtarget false t in
+               if (Inference.is_identity (metasenv', context, ugraph) newtarget) ||
+                 (Inference.meta_convertibility_eq target newtarget) then
+                   newmeta, newtarget
+               else
+                 demodulation_equality newmeta env table sign newtarget
+         | None ->
+             newmeta, target
+  in
+  (* newmeta, newtarget *)
+  (* tentiamo di ridurre usando CicReduction.normalize *)
+  let w, p, (ty, left, right, o), m, a = newtarget in
+  let left' = ProofEngineReduction.simpl context left in
+  let right' = ProofEngineReduction.simpl context right in
+  let newleft =
+    if !Utils.compare_terms left' left = Utils.Lt then left' else left in
+  let newright = 
+    if !Utils.compare_terms right' right = Utils.Lt then right' else right in
+  if newleft != left || newright != right then (
+    debug_print
+      (lazy
+        (Printf.sprintf "left: %s, left': %s\nright: %s, right': %s\n"
+           (CicPp.ppterm left) (CicPp.ppterm left') (CicPp.ppterm right)
+           (CicPp.ppterm right')))
+  );
+  let w' = Utils.compute_equality_weight ty newleft newright in
+  let o' = !Utils.compare_terms newleft newright in
+  newmeta, (w', p, (ty, newleft, newright, o'), m, a)
 ;;
 
 
+(**
+   Performs the beta expansion of the term "term" w.r.t. "table",
+   i.e. returns the list of all the terms t s.t. "(t term) = t2", for some t2
+   in table.
+*)
 let rec betaexpand_term metasenv context ugraph table lift_amount term =
   let module C = Cic in
   let module S = CicSubstitution in
@@ -607,7 +620,7 @@ let rec betaexpand_term metasenv context ugraph table lift_amount term =
   let res, lifted_term = 
     match term with
     | C.Meta (i, l) ->
-        let l', lifted_l = 
+        let l', lifted_l =
           List.fold_right
             (fun arg (res, lifted_tl) ->
                match arg with
@@ -630,11 +643,11 @@ let rec betaexpand_term metasenv context ugraph table lift_amount term =
                | None ->
                    (List.map
                       (fun (r, s, m, ug, eq_found) ->
-                         None::r, s, m, ug, eq_found) res, 
+                         None::r, s, m, ug, eq_found) res,
                     None::lifted_tl)
             ) l ([], [])
         in
-        let e = 
+        let e =
           List.map
             (fun (l, s, m, ug, eq_found) ->
                (C.Meta (i, l), s, m, ug, eq_found)) l'
@@ -660,6 +673,22 @@ let rec betaexpand_term metasenv context ugraph table lift_amount term =
                C.Prod (nn, lifted_s, t), s, m, ug, eq_found) l2 in
         l1' @ l2', C.Prod (nn, lifted_s, lifted_t)
           
+    | C.Lambda (nn, s, t) ->
+        let l1, lifted_s =
+          betaexpand_term metasenv context ugraph table lift_amount s in
+        let l2, lifted_t =
+          betaexpand_term metasenv ((Some (nn, C.Decl s))::context) ugraph
+            table (lift_amount+1) t in
+        let l1' =
+          List.map
+            (fun (t, s, m, ug, eq_found) ->
+               C.Lambda (nn, t, lifted_t), s, m, ug, eq_found) l1
+        and l2' =
+          List.map
+            (fun (t, s, m, ug, eq_found) ->
+               C.Lambda (nn, lifted_s, t), s, m, ug, eq_found) l2 in
+        l1' @ l2', C.Lambda (nn, lifted_s, lifted_t)
+
     | C.Appl l ->
         let l', lifted_l =
           List.fold_right
@@ -688,7 +717,7 @@ let rec betaexpand_term metasenv context ugraph table lift_amount term =
     | t -> [], (S.lift lift_amount t)
   in
   match term with
-  | C.Meta _ -> res, lifted_term
+  | C.Meta (i, l) -> res, lifted_term
   | term ->
       let termty, ugraph =
         C.Implicit None, ugraph
@@ -704,6 +733,11 @@ let rec betaexpand_term metasenv context ugraph table lift_amount term =
 
 let sup_l_counter = ref 1;;
 
+(**
+   superposition_left 
+   returns a list of new clauses inferred with a left superposition step
+   the negative equation "target" and one of the positive equations in "table"
+*)
 let superposition_left newmeta (metasenv, context, ugraph) table target =
   let module C = Cic in
   let module S = CicSubstitution in
@@ -719,78 +753,62 @@ let superposition_left newmeta (metasenv, context, ugraph) table target =
   let maxmeta = ref newmeta in
   let build_new (bo, s, m, ug, (eq_found, eq_URI)) =
 
-    print_endline "\nSUPERPOSITION LEFT\n";
-    
+    debug_print (lazy "\nSUPERPOSITION LEFT\n");
+
     let time1 = Unix.gettimeofday () in
     
     let pos, (_, proof', (ty, what, other, _), menv', args') = eq_found in
     let what, other = if pos = Utils.Left then what, other else other, what in
     let newgoal, newproof =
-      let bo' = (* M. *)apply_subst s (S.subst other bo) in
-      let t' =
-        let name = C.Name ("x_SupL_" ^ (string_of_int !sup_l_counter)) in
-        incr sup_l_counter;
+      let bo' = apply_subst s (S.subst other bo) in
+      let name = C.Name ("x_SupL_" ^ (string_of_int !sup_l_counter)) in
+      incr sup_l_counter;
+      let bo'' = 
         let l, r =
           if ordering = U.Gt then bo, S.lift 1 right else S.lift 1 left, bo in
-        (name, ty, S.lift 1 eq_ty, l, r)
+        C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []);
+                S.lift 1 eq_ty; l; r]
       in
-(*       let bo'' = *)
-(*         C.Appl ( *)
-(*           [C.MutInd (HL.Logic.eq_URI, 0, []); *)
-(*            S.lift 1 eq_ty] @ *)
-(*             if ordering = U.Gt then [S.lift 1 bo'; S.lift 1 right] *)
-(*             else [S.lift 1 left; S.lift 1 bo']) *)
-(*       in *)
-(*       let t' = *)
-(*         let name = C.Name ("x_SupL_" ^ (string_of_int !sup_l_counter)) in *)
-(*         incr sup_l_counter; *)
-(*         C.Lambda (name, ty, bo'') *)
-(*       in *)
       incr maxmeta;
       let metaproof =
         let irl =
           CicMkImplicit.identity_relocation_list_for_metavariable context in
         C.Meta (!maxmeta, irl)
       in
-      let target' =
-        let eq_found =
-          let proof' =
-            let ens =
-              if pos = Utils.Left then
-                build_ens_for_sym_eq ty what other
-              else
-                build_ens_for_sym_eq ty other what
-            in
-            Inference.ProofSymBlock (ens, proof')
+      let eq_found =
+        let proof' =
+          let termlist =
+            if pos = Utils.Left then [ty; what; other]
+            else [ty; other; what]
           in
-          let what, other =
-            if pos = Utils.Left then what, other else other, what
-          in
-          pos, (0, proof', (ty, other, what, Utils.Incomparable), menv', args')
+          Inference.ProofSymBlock (termlist, proof')
         in
-        let target_proof =
-          let pb =
-            Inference.ProofBlock (s, eq_URI, t', eq_found,
-                                  Inference.BasicProof metaproof)
-          in
-          match proof with
-          | Inference.BasicProof _ ->
-              print_endline "replacing a BasicProof";
-              pb
-          | Inference.ProofGoalBlock (_, parent_eq) ->
-              print_endline "replacing another ProofGoalBlock";
-              Inference.ProofGoalBlock (pb, parent_eq)
-          | _ -> assert false
+        let what, other =
+          if pos = Utils.Left then what, other else other, what
         in
-        (weight, target_proof, (eq_ty, left, right, ordering), [], [])
+        pos, (0, proof', (ty, other, what, Utils.Incomparable), menv', args')
+      in
+      let target_proof =
+        let pb =
+          Inference.ProofBlock (s, eq_URI, (name, ty), bo'', eq_found,
+                                Inference.BasicProof metaproof)
+        in
+        match proof with
+        | Inference.BasicProof _ ->
+            debug_print (lazy "replacing a BasicProof");
+            pb
+        | Inference.ProofGoalBlock (_, parent_proof) ->
+            debug_print (lazy "replacing another ProofGoalBlock");
+            Inference.ProofGoalBlock (pb, parent_proof)
+        | _ -> assert false
       in
       let refl =
         C.Appl [C.MutConstruct (* reflexivity *)
-                  (HelmLibraryObjects.Logic.eq_URI, 0, 1, []);
+                  (LibraryObjects.eq_URI (), 0, 1, []);
                 eq_ty; if ordering = U.Gt then right else left]
       in
       (bo',
-       Inference.ProofGoalBlock (Inference.BasicProof refl, target'))
+       Inference.ProofGoalBlock (Inference.BasicProof refl, target_proof))
     in
     let left, right =
       if ordering = U.Gt then newgoal, right else left, newgoal in
@@ -811,6 +829,13 @@ let superposition_left newmeta (metasenv, context, ugraph) table target =
 
 let sup_r_counter = ref 1;;
 
+(**
+   superposition_right
+   returns a list of new clauses inferred with a right superposition step
+   between the positive equation "target" and one in the "table" "newmeta" is
+   the first free meta index, i.e. the first number above the highest meta
+   index: its updated value is also returned
+*)
 let superposition_right newmeta (metasenv, context, ugraph) table target =
   let module C = Cic in
   let module S = CicSubstitution in
@@ -829,7 +854,7 @@ let superposition_right newmeta (metasenv, context, ugraph) table target =
         let res l r =
           List.filter
             (fun (_, subst, _, _, _) ->
-               let subst = (* M. *)apply_subst subst in
+               let subst = apply_subst subst in
                let o = !Utils.compare_terms (subst l) (subst r) in
                o <> U.Lt && o <> U.Le)
             (fst (betaexpand_term metasenv' context ugraph table 0 l))
@@ -843,7 +868,7 @@ let superposition_right newmeta (metasenv, context, ugraph) table target =
     let pos, (_, proof', (ty, what, other, _), menv', args') = eq_found in
     let what, other = if pos = Utils.Left then what, other else other, what in
     let newgoal, newproof =
-      let bo' = (* M. *)apply_subst s (S.subst other bo) in
+      let bo' = apply_subst s (S.subst other bo) in
       let t' =
         let name = C.Name ("x_SupR_" ^ (string_of_int !sup_r_counter)) in
         incr sup_r_counter;
@@ -851,27 +876,21 @@ let superposition_right newmeta (metasenv, context, ugraph) table target =
           if ordering = U.Gt then bo, S.lift 1 right else S.lift 1 left, bo in
         (name, ty, S.lift 1 eq_ty, l, r)
       in
-(*       let bo'' = *)
-(*         C.Appl ( *)
-(*           [C.MutInd (HL.Logic.eq_URI, 0, []); S.lift 1 eq_ty] @ *)
-(*             if ordering = U.Gt then [S.lift 1 bo'; S.lift 1 right] *)
-(*             else [S.lift 1 left; S.lift 1 bo']) *)
-(*       in *)
-(*       let t' = *)
-(*         let name = C.Name ("x_SupR_" ^ (string_of_int !sup_r_counter)) in *)
-(*         incr sup_r_counter; *)
-(*         C.Lambda (name, ty, bo'') *)
-(*       in *)
+      let name = C.Name ("x_SupR_" ^ (string_of_int !sup_r_counter)) in
+      incr sup_r_counter;
+      let bo'' =
+        let l, r =
+          if ordering = U.Gt then bo, S.lift 1 right else S.lift 1 left, bo in
+        C.Appl [C.MutInd (LibraryObjects.eq_URI (), 0, []);
+                S.lift 1 eq_ty; l; r]
+      in
       bo',
-      Inference.ProofBlock (s, eq_URI, t', eq_found, eqproof(* target *))
-(*       (\* M. *\)apply_subst s *)
-(*         (C.Appl [C.Const (eq_URI, []); ty; what; t'; *)
-(*                  eqproof; other; proof']) *)
+      Inference.ProofBlock (s, eq_URI, (name, ty), bo'', eq_found, eqproof)
     in
     let newmeta, newequality = 
       let left, right =
-        if ordering = U.Gt then newgoal, (* M. *)apply_subst s right
-        else (* M. *)apply_subst s left, newgoal in
+        if ordering = U.Gt then newgoal, apply_subst s right
+        else apply_subst s left, newgoal in
       let neworder = !Utils.compare_terms left right 
       and newmenv = newmetas @ menv'
       and newargs = args @ args' in
@@ -889,18 +908,144 @@ let superposition_right newmeta (metasenv, context, ugraph) table target =
 
     newequality
   in
-
-(*   let build_new = *)
-(*     let profile = CicUtil.profile "Indexing.superposition_right.build_new" in *)
-(*     (fun o e -> profile.profile (build_new o) e) *)
-(*   in *)
-  
   let new1 = List.map (build_new U.Gt) res1
   and new2 = List.map (build_new U.Lt) res2 in
-  let ok = function
-    | _, _, (_, left, right, _), _, _ ->
-        not (fst (CR.are_convertible context left right ugraph))
-  in
+  let ok e = not (Inference.is_identity (metasenv, context, ugraph) e) in
   (!maxmeta,
    (List.filter ok (new1 @ new2)))
 ;;
+
+
+(** demodulation, when the target is a goal *)
+let rec demodulation_goal newmeta env table goal =
+  let module C = Cic in
+  let module S = CicSubstitution in
+  let module M = CicMetaSubst in
+  let module HL = HelmLibraryObjects in
+  let metasenv, context, ugraph = env in
+  let maxmeta = ref newmeta in
+  let proof, metas, term = goal in
+  let metasenv' = metasenv @ metas in
+
+  let build_newgoal (t, subst, menv, ug, (eq_found, eq_URI)) =
+    let pos, (_, proof', (ty, what, other, _), menv', args') = eq_found in
+    let what, other = if pos = Utils.Left then what, other else other, what in
+    let ty =
+      try fst (CicTypeChecker.type_of_aux' metasenv context what ugraph)
+      with CicUtil.Meta_not_found _ -> ty
+    in
+    let newterm, newproof =
+      let bo = apply_subst subst (S.subst other t) in
+      let bo' = apply_subst subst t in 
+      let name = C.Name ("x_DemodGoal_" ^ (string_of_int !demod_counter)) in
+      incr demod_counter;
+      let metaproof = 
+        incr maxmeta;
+        let irl =
+          CicMkImplicit.identity_relocation_list_for_metavariable context in
+        debug_print (lazy (Printf.sprintf "\nADDING META: %d\n" !maxmeta));
+        C.Meta (!maxmeta, irl)
+      in
+      let eq_found =
+        let proof' =
+          let termlist =
+            if pos = Utils.Left then [ty; what; other]
+            else [ty; other; what]
+          in
+          Inference.ProofSymBlock (termlist, proof')
+        in
+        let what, other =
+          if pos = Utils.Left then what, other else other, what
+        in
+        pos, (0, proof', (ty, other, what, Utils.Incomparable), menv', args')
+      in
+      let goal_proof =
+        let pb =
+          Inference.ProofBlock (subst, eq_URI, (name, ty), bo',
+                                eq_found, Inference.BasicProof metaproof)
+        in
+        let rec repl = function
+          | Inference.NoProof ->
+              debug_print (lazy "replacing a NoProof");
+              pb
+          | Inference.BasicProof _ ->
+              debug_print (lazy "replacing a BasicProof");
+              pb
+          | Inference.ProofGoalBlock (_, parent_proof) ->
+              debug_print (lazy "replacing another ProofGoalBlock");
+              Inference.ProofGoalBlock (pb, parent_proof)
+          | (Inference.SubProof (term, meta_index, p) as subproof) ->
+              debug_print
+                (lazy
+                   (Printf.sprintf "replacing %s"
+                      (Inference.string_of_proof subproof)));
+              Inference.SubProof (term, meta_index, repl p)
+          | _ -> assert false
+        in repl proof
+      in
+      bo, Inference.ProofGoalBlock (Inference.NoProof, goal_proof)
+    in
+    let m = Inference.metas_of_term newterm in
+    let newmetasenv = List.filter (fun (i, _, _) -> List.mem i m) metas in
+    !maxmeta, (newproof, newmetasenv, newterm)
+  in  
+  let res =
+    demodulation_aux ~typecheck:true metasenv' context ugraph table 0 term
+  in
+  match res with
+  | Some t ->
+      let newmeta, newgoal = build_newgoal t in
+      let _, _, newg = newgoal in
+      if Inference.meta_convertibility term newg then
+        newmeta, newgoal
+      else
+        demodulation_goal newmeta env table newgoal
+  | None ->
+      newmeta, goal
+;;
+
+
+(** demodulation, when the target is a theorem *)
+let rec demodulation_theorem newmeta env table theorem =
+  let module C = Cic in
+  let module S = CicSubstitution in
+  let module M = CicMetaSubst in
+  let module HL = HelmLibraryObjects in
+  let metasenv, context, ugraph = env in
+  let maxmeta = ref newmeta in
+  let proof, metas, term = theorem in
+  let term, termty, metas = theorem in
+  let metasenv' = metasenv @ metas in
+
+  let build_newtheorem (t, subst, menv, ug, (eq_found, eq_URI)) =
+    let pos, (_, proof', (ty, what, other, _), menv', args') = eq_found in
+    let what, other = if pos = Utils.Left then what, other else other, what in
+    let newterm, newty =
+      let bo = apply_subst subst (S.subst other t) in
+      let bo' = apply_subst subst t in 
+      let name = C.Name ("x_DemodThm_" ^ (string_of_int !demod_counter)) in
+      incr demod_counter;
+      let newproof =
+        Inference.ProofBlock (subst, eq_URI, (name, ty), bo', eq_found,
+                              Inference.BasicProof term)
+      in
+      (Inference.build_proof_term newproof, bo)
+    in
+    let m = Inference.metas_of_term newterm in
+    let newmetasenv = List.filter (fun (i, _, _) -> List.mem i m) metas in
+    !maxmeta, (newterm, newty, newmetasenv)
+  in  
+  let res =
+    demodulation_aux ~typecheck:true metasenv' context ugraph table 0 termty
+  in
+  match res with
+  | Some t ->
+      let newmeta, newthm = build_newtheorem t in
+      let newt, newty, _ = newthm in
+      if Inference.meta_convertibility termty newty then
+        newmeta, newthm
+      else
+        demodulation_theorem newmeta env table newthm
+  | None ->
+      newmeta, theorem
+;;