]> matita.cs.unibo.it Git - helm.git/blobdiff - components/acic_procedural/acic2Procedural.ml
branch for universe
[helm.git] / components / acic_procedural / acic2Procedural.ml
diff --git a/components/acic_procedural/acic2Procedural.ml b/components/acic_procedural/acic2Procedural.ml
new file mode 100644 (file)
index 0000000..c004fd3
--- /dev/null
@@ -0,0 +1,462 @@
+(* Copyright (C) 2003-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/.
+ *)
+
+module C    = Cic
+module I    = CicInspect
+module S    = CicSubstitution
+module TC   = CicTypeChecker 
+module Un   = CicUniv
+module UM   = UriManager
+module Obj  = LibraryObjects
+module HObj = HelmLibraryObjects
+module A    = Cic2acic
+module Ut   = CicUtil
+module E    = CicEnvironment
+module Pp   = CicPp
+module PEH  = ProofEngineHelpers
+module HEL  = HExtlib
+module DTI  = DoubleTypeInference
+
+module Cl   = ProceduralClassify
+module T    = ProceduralTypes
+module Cn   = ProceduralConversion
+module H    = ProceduralHelpers
+
+type status = {
+   sorts : (C.id, A.sort_kind) Hashtbl.t;
+   types : (C.id, A.anntypes) Hashtbl.t;
+   prefix: string;
+   max_depth: int option;
+   depth: int;
+   context: C.context;
+   intros: string option list;
+   clears: string list;
+   clears_note: string;
+   case: int list;
+   skip_thm_and_qed : bool;
+}
+
+(* helpers ******************************************************************)
+
+let split2_last l1 l2 =
+try
+   let n = pred (List.length l1) in
+   let before1, after1 = HEL.split_nth n l1 in
+   let before2, after2 = HEL.split_nth n l2 in
+   before1, before2, List.hd after1, List.hd after2
+with Invalid_argument _ -> failwith "A2P.split2_last"
+   
+let string_of_head = function
+   | C.ASort _         -> "sort"
+   | C.AConst _        -> "const"
+   | C.AMutInd _       -> "mutind"
+   | C.AMutConstruct _ -> "mutconstruct"
+   | C.AVar _          -> "var"
+   | C.ARel _          -> "rel"
+   | C.AProd _         -> "prod"
+   | C.ALambda _       -> "lambda"
+   | C.ALetIn _        -> "letin"
+   | C.AFix _          -> "fix"
+   | C.ACoFix _        -> "cofix"
+   | C.AAppl _         -> "appl"
+   | C.ACast _         -> "cast"
+   | C.AMutCase _      -> "mutcase"
+   | C.AMeta _         -> "meta"
+   | C.AImplicit _     -> "implict"
+
+let clear st = {st with intros = []}
+
+let next st = {(clear st) with depth = succ st.depth}
+
+let add st entry intro =
+   {st with context = entry :: st.context; intros = intro :: st.intros}
+
+let push st = {st with case = 1 :: st.case}
+
+let inc st =
+   {st with case = match st.case with 
+      | []       -> assert false
+      | hd :: tl -> succ hd :: tl
+   }
+
+let case st str =
+   let case = String.concat "." (List.rev_map string_of_int st.case) in
+   Printf.sprintf "case %s: %s" case str
+
+let test_depth st =
+try   
+   let msg = Printf.sprintf "Depth %u: " st.depth in
+   match st.max_depth with
+      | None   -> true, "" 
+      | Some d -> if st.depth < d then true, msg else false, "DEPTH EXCEDED: "
+with Invalid_argument _ -> failwith "A2P.test_depth"
+
+let is_rewrite_right = function
+   | C.AConst (_, uri, []) ->
+      UM.eq uri HObj.Logic.eq_ind_r_URI || Obj.is_eq_ind_r_URI uri
+   | _                     -> false
+
+let is_rewrite_left = function
+   | C.AConst (_, uri, []) ->
+      UM.eq uri HObj.Logic.eq_ind_URI || Obj.is_eq_ind_URI uri
+   | _                     -> false
+
+let is_fwd_rewrite_right hd tl =
+   if is_rewrite_right hd then match List.nth tl 3 with
+      | C.ARel _ -> true
+      | _        -> false
+   else false
+
+let is_fwd_rewrite_left hd tl =
+   if is_rewrite_left hd then match List.nth tl 3 with
+      | C.ARel _ -> true
+      | _        -> false
+   else false
+
+let get_inner_types st v =
+try
+   let id = Ut.id_of_annterm v in
+   try match Hashtbl.find st.types id with
+      | {A.annsynthesized = st; A.annexpected = Some et} -> Some (st, et)
+      | {A.annsynthesized = st; A.annexpected = None}    -> Some (st, st)
+   with Not_found -> None
+with Invalid_argument _ -> failwith "A2P.get_inner_types"
+(*
+let get_inner_sort st v =
+try
+   let id = Ut.id_of_annterm v in
+   try Hashtbl.find st.sorts id
+   with Not_found -> `Type (CicUniv.fresh())
+with Invalid_argument _ -> failwith "A2P.get_sort"
+*)
+let get_type msg st bo =
+try   
+   let ty, _ = TC.type_of_aux' [] st.context (H.cic bo) Un.empty_ugraph in
+   ty
+with e -> failwith (msg ^ ": " ^ Printexc.to_string e)
+
+let get_entry st id =
+   let rec aux = function
+      | []                                        -> assert false
+      | Some (C.Name name, e) :: _ when name = id -> e
+      | _ :: tl                                   -> aux tl
+   in
+   aux st.context
+
+let get_ind_names uri tno =
+try   
+   let ts = match E.get_obj Un.empty_ugraph uri with
+      | C.InductiveDefinition (ts, _, _, _), _ -> ts 
+      | _                                      -> assert false
+   in
+   match List.nth ts tno with
+      | (_, _, _, cs) -> List.map fst cs  
+with Invalid_argument _ -> failwith "A2P.get_ind_names"
+
+(* proof construction *******************************************************)
+
+let used_premise = C.Name "USED"
+
+let mk_exp_args hd tl classes synth =
+   let meta id = C.AImplicit (id, None) in
+   let map v (cl, b) =
+      if I.overlaps synth cl && b then v else meta ""
+   in
+   let rec aux = function
+      | [] -> []
+      | hd :: tl -> if hd = meta "" then aux tl else List.rev (hd :: tl)
+   in
+   let args = T.list_rev_map2 map tl classes in
+   let args = aux args in
+   if args = [] then hd else C.AAppl ("", hd :: args)
+
+let mk_convert st ?name sty ety note =
+   let e = Cn.hole "" in
+   let csty, cety = H.cic sty, H.cic ety in
+   let _note = Printf.sprintf "%s\nSINTH: %s\nEXP: %s"
+      note (Pp.ppterm csty) (Pp.ppterm cety)
+   in
+   assert (Ut.is_sober csty); 
+   assert (Ut.is_sober cety);
+   if Ut.alpha_equivalence csty cety then [(* T.Note note *)] else 
+   let sty, ety = H.acic_bc st.context sty, H.acic_bc st.context ety in
+   match name with
+      | None         -> [T.Change (sty, ety, None, e, ""(*note*))]
+      | Some (id, i) -> 
+         begin match get_entry st id with
+           | C.Def _  -> assert false (* [T.ClearBody (id, note)] *)
+           | C.Decl _ -> [T.Change (ety, sty, Some (id, Some id), e, "" (* note *))] 
+         end
+
+let convert st ?name v = 
+   match get_inner_types st v with
+      | None            -> [(*T.Note "NORMAL: NO INNER TYPES"*)]
+      | Some (sty, ety) -> mk_convert st ?name sty ety "NORMAL"
+
+let convert_elim st ?name t v pattern =
+   match t, get_inner_types st t, get_inner_types st v with
+      | _, None, _
+      | _, _, None                                            -> [(* T.Note "ELIM: NO INNER TYPES"*)]
+      | C.AAppl (_, hd :: tl), Some (tsty, _), Some (vsty, _) ->
+         let where = List.hd (List.rev tl) in
+         let cty = Cn.elim_inferred_type 
+            st.context (H.cic vsty) (H.cic where) (H.cic hd) (H.cic pattern)
+        in
+         mk_convert st ?name (Cn.fake_annotate "" st.context cty) tsty "ELIM"
+      | _, Some _, Some _                                     -> assert false
+         
+let get_intro = function 
+   | C.Anonymous -> None
+   | C.Name s    -> Some s
+
+let mk_intros st what script =
+   let intros st script =
+      if st.intros = [] then script else
+      let count = List.length st.intros in
+      T.Intros (Some count, List.rev st.intros, "") :: script
+   in
+   let clears st script =
+      if true (* st.clears = [] *) then script else T.Clear (st.clears, st.clears_note) :: script
+   in
+   intros st (clears st (convert st what @ script))   
+
+let mk_arg st = function
+   | C.ARel (_, _, i, name) as what -> convert st ~name:(name, i) what
+   | _                              -> []
+
+let mk_fwd_rewrite st dtext name tl direction t =   
+   assert (List.length tl = 6);
+   let what, where, predicate = List.nth tl 5, List.nth tl 3, List.nth tl 2 in
+   let e = Cn.mk_pattern 1 predicate in
+   match where with
+      | C.ARel (_, _, i, premise) as v ->
+         let where = Some (premise, name) in
+(*         let _script = convert_elim st ~name:(premise, i) t v e in *) 
+         let script = mk_arg st what @ mk_arg st v (* @ script *) in
+        let st = {st with context = Cn.clear st.context premise} in 
+        st, T.Rewrite (direction, what, where, e, dtext) :: script
+      | _                         -> assert false
+
+let mk_rewrite st dtext where qs tl direction t = 
+   assert (List.length tl = 5);
+   let predicate = List.nth tl 2 in
+   let e = Cn.mk_pattern 1 predicate in
+   let script = [] (* convert_elim st t t e *) in
+   script @ [T.Rewrite (direction, where, None, e, dtext); T.Branch (qs, "")]
+
+let rec proc_lambda st name v t =
+   let dno = DTI.does_not_occur 1 (H.cic t) in
+   let dno = dno && match get_inner_types st t with
+      | None          -> false
+      | Some (it, et) -> 
+         DTI.does_not_occur 1 (H.cic it) && DTI.does_not_occur 1 (H.cic et)
+   in
+   let name = match dno, name with
+      | true, _            -> C.Anonymous
+      | false, C.Anonymous -> H.mk_fresh_name st.context used_premise 
+      | false, name        -> name
+   in
+   let entry = Some (name, C.Decl (H.cic v)) in
+   let intro = get_intro name in
+   proc_proof (add st entry intro) t
+
+and proc_letin st what name v w t =
+   let intro = get_intro name in
+   let proceed, dtext = test_depth st in
+   let script = if proceed then 
+      let st, hyp, rqv = match get_inner_types st v with
+         | Some (ity, _) ->
+           let st, rqv = match v with
+               | C.AAppl (_, hd :: tl) when is_fwd_rewrite_right hd tl ->
+                 mk_fwd_rewrite st dtext intro tl true v
+              | C.AAppl (_, hd :: tl) when is_fwd_rewrite_left hd tl  ->
+                 mk_fwd_rewrite st dtext intro tl false v
+              | v                                                     ->
+                 let qs = [proc_proof (next st) v; [T.Id ""]] in
+                 let ity = H.acic_bc st.context ity in
+                 st, [T.Branch (qs, ""); T.Cut (intro, ity, dtext)]
+           in
+           st, C.Decl (H.cic ity), rqv
+        | None          ->
+           st, C.Def (H.cic v, H.cic w), [T.LetIn (intro, v, dtext)]
+      in
+      let entry = Some (name, hyp) in
+      let qt = proc_proof (next (add st entry intro)) t in
+      List.rev_append rqv qt      
+   else
+      [T.Apply (what, dtext)]
+   in
+   mk_intros st what script
+
+and proc_rel st what = 
+   let _, dtext = test_depth st in
+   let text = "assumption" in
+   let script = [T.Apply (what, dtext ^ text)] in 
+   mk_intros st what script
+
+and proc_mutconstruct st what = 
+   let _, dtext = test_depth st in
+   let script = [T.Apply (what, dtext)] in 
+   mk_intros st what script
+
+and proc_const st what = 
+   let _, dtext = test_depth st in
+   let script = [T.Apply (what, dtext)] in 
+   mk_intros st what script
+
+and proc_appl st what hd tl =
+   let proceed, dtext = test_depth st in
+   let script = if proceed then
+      let ty = get_type "TC2" st hd in
+      let classes, rc = Cl.classify st.context ty in
+      let goal_arity = match get_inner_types st what with
+         | None          -> 0
+        | Some (ity, _) -> snd (PEH.split_with_whd (st.context, H.cic ity))
+      in
+      let parsno, argsno = List.length classes, List.length tl in
+      let decurry = parsno - argsno in
+      let diff = goal_arity - decurry in
+      if diff < 0 then failwith (Printf.sprintf "NOT TOTAL: %i %s |--- %s" diff (Pp.ppcontext st.context) (Pp.ppterm (H.cic hd)));
+      let rec mk_synth a n =
+         if n < 0 then a else mk_synth (I.S.add n a) (pred n)
+      in
+      let synth = mk_synth I.S.empty decurry in
+      let text = "" (* Printf.sprintf "%u %s" parsno (Cl.to_string h) *) in
+      let script = List.rev (mk_arg st hd) in
+      match rc with
+         | Some (i, j, uri, tyno) ->
+           let classes, tl, _, where = split2_last classes tl in
+           let script = List.rev (mk_arg st where) @ script in
+           let synth = I.S.add 1 synth in
+           let names = get_ind_names uri tyno in
+           let qs = proc_bkd_proofs (next st) synth names classes tl in
+            if is_rewrite_right hd then 
+              script @ mk_rewrite st dtext where qs tl false what
+           else if is_rewrite_left hd then 
+              script @ mk_rewrite st dtext where qs tl true what
+           else
+              let predicate = List.nth tl (parsno - i) in
+               let e = Cn.mk_pattern j predicate in
+              let using = Some hd in
+              (* convert_elim st what what e @ *) script @ 
+              [T.Elim (where, using, e, dtext ^ text); T.Branch (qs, "")]
+        | None        ->
+           let qs = proc_bkd_proofs (next st) synth [] classes tl in
+           let hd = mk_exp_args hd tl classes synth in
+           script @ [T.Apply (hd, dtext ^ text); T.Branch (qs, "")]
+   else
+      [T.Apply (what, dtext)]
+   in
+   mk_intros st what script
+
+and proc_other st what =
+   let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head what) in
+   let script = [T.Note text] in
+   mk_intros st what script
+
+and proc_proof st t = 
+   let f st =
+      let xtypes, note = match get_inner_types st t with
+         | Some (it, et) -> Some (H.cic it, H.cic et), 
+         (Printf.sprintf "\nInferred: %s\nExpected: %s"
+         (Pp.ppterm (H.cic it)) (Pp.ppterm (H.cic et))) 
+         | None          -> None, "\nNo types"
+      in
+      let context, clears = Cn.get_clears st.context (H.cic t) xtypes in
+      let note = Pp.ppcontext st.context ^ note in
+      {st with context = context; clears = clears; clears_note = note; }
+   in
+   match t with
+      | C.ALambda (_, name, w, t)           -> proc_lambda st name w t
+      | C.ALetIn (_, name, v, w, t) as what -> proc_letin (f st) what name v w t
+      | C.ARel _ as what                    -> proc_rel (f st) what
+      | C.AMutConstruct _ as what           -> proc_mutconstruct (f st) what
+      | C.AConst _ as what                  -> proc_const (f st) what
+      | C.AAppl (_, hd :: tl) as what       -> proc_appl (f st) what hd tl
+      | what                                -> proc_other (f st) what
+
+and proc_bkd_proofs st synth names classes ts =
+try 
+   let get_note =
+      let names = ref (names, push st) in
+      fun f -> 
+         match !names with 
+           | [], st       -> fun _ -> f st
+           | "" :: tl, st -> names := tl, st; fun _ -> f st
+           | hd :: tl, st -> 
+              let note = case st hd in
+              names := tl, inc st; 
+              fun b -> if b then T.Note note :: f st else f st
+   in
+   let _, dtext = test_depth st in   
+   let aux (inv, _) v =
+      if I.overlaps synth inv then None else
+      if I.S.is_empty inv then Some (get_note (fun st -> proc_proof st v)) else
+      Some (fun _ -> [T.Apply (v, dtext ^ "dependent")])
+   in  
+   let ps = T.list_map2_filter aux classes ts in
+   let b = List.length ps > 1 in
+   List.rev_map (fun f -> f b) ps
+
+with Invalid_argument s -> failwith ("A2P.proc_bkd_proofs: " ^ s)
+
+(* object costruction *******************************************************)
+
+let is_theorem pars =
+   pars = [] ||
+   List.mem (`Flavour `Theorem) pars || List.mem (`Flavour `Fact) pars || 
+   List.mem (`Flavour `Remark) pars || List.mem (`Flavour `Lemma) pars
+
+let proc_obj st = function
+   | C.AConstant (_, _, s, Some v, t, [], pars) when is_theorem pars ->
+      let ast = proc_proof st v in
+      let steps, nodes = T.count_steps 0 ast, T.count_nodes 0 ast in
+      let text = Printf.sprintf "tactics: %u\nnodes: %u" steps nodes in
+      if st.skip_thm_and_qed then ast
+      else T.Theorem (Some s, t, "") :: ast @ [T.Qed text]
+   | _                                                               ->
+      failwith "not a theorem"
+
+(* interface functions ******************************************************)
+
+let acic2procedural ~ids_to_inner_sorts ~ids_to_inner_types ?depth
+?(skip_thm_and_qed=false) prefix aobj = 
+   let st = {
+      sorts       = ids_to_inner_sorts;
+      types       = ids_to_inner_types;
+      prefix      = prefix;
+      max_depth   = depth;
+      depth       = 0;
+      context     = [];
+      intros      = [];
+      clears      = [];
+      clears_note = "";
+      case        = [];
+      skip_thm_and_qed = skip_thm_and_qed;
+   } in
+   HLog.debug "Procedural: level 2 transformation";
+   let steps = proc_obj st aobj in
+   HLog.debug "Procedural: grafite rendering";
+   List.rev (T.render_steps [] steps)