]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/acic_procedural/acic2Procedural.ml
22936c1a4531a6338dcb2ca3e7916cf062f41490
[helm.git] / helm / software / components / acic_procedural / acic2Procedural.ml
1 (* Copyright (C) 2003-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 module C    = Cic
27 module D    = Deannotate
28 module DTI  = DoubleTypeInference
29 module TC   = CicTypeChecker 
30 module Un   = CicUniv
31 module UM   = UriManager
32 module Obj  = LibraryObjects
33 module HObj = HelmLibraryObjects
34 module A    = Cic2acic
35 module Ut   = CicUtil
36 module E    = CicEnvironment
37 module PER  = ProofEngineReduction
38
39 module Cl   = ProceduralClassify
40 module M    = ProceduralMode
41 module T    = ProceduralTypes
42 module Cn   = ProceduralConversion
43
44 type status = {
45    sorts : (C.id, A.sort_kind) Hashtbl.t;
46    types : (C.id, A.anntypes) Hashtbl.t;
47    prefix: string;
48    max_depth: int option;
49    depth: int;
50    context: C.context;
51    intros: string list;
52    ety: C.annterm option
53 }
54
55 (* helpers ******************************************************************)
56
57 let id x = x
58
59 let comp f g x = f (g x)
60
61 let cic = D.deannotate_term
62
63 let split2_last l1 l2 =
64 try
65    let n = pred (List.length l1) in
66    let before1, after1 = T.list_split n l1 in
67    let before2, after2 = T.list_split n l2 in
68    before1, before2, List.hd after1, List.hd after2
69 with Invalid_argument _ -> failwith "A2P.split2_last"
70
71 let string_of_head = function
72    | C.ASort _         -> "sort"
73    | C.AConst _        -> "const"
74    | C.AMutInd _       -> "mutind"
75    | C.AMutConstruct _ -> "mutconstruct"
76    | C.AVar _          -> "var"
77    | C.ARel _          -> "rel"
78    | C.AProd _         -> "prod"
79    | C.ALambda _       -> "lambda"
80    | C.ALetIn _        -> "letin"
81    | C.AFix _          -> "fix"
82    | C.ACoFix _        -> "cofix"
83    | C.AAppl _         -> "appl"
84    | C.ACast _         -> "cast"
85    | C.AMutCase _      -> "mutcase"
86    | C.AMeta _         -> "meta"
87    | C.AImplicit _     -> "implict"
88
89 let clear st = {st with intros = []; ety = None}
90
91 let next st = {(clear st) with depth = succ st.depth}
92
93 let set_ety st ety =
94    if st.ety = None then {st with ety = ety} else st
95
96 let add st entry intro ety = 
97    let st = set_ety st ety in
98    {st with context = entry :: st.context; intros = intro :: st.intros}
99
100 let test_depth st =
101 try   
102    let msg = Printf.sprintf "Depth %u: " st.depth in
103    match st.max_depth with
104       | None   -> true, "" 
105       | Some d -> if st.depth < d then true, msg else false, "DEPTH EXCEDED: "
106 with Invalid_argument _ -> failwith "A2P.test_depth"
107
108 let is_rewrite_right = function
109    | C.AConst (_, uri, []) ->
110       UM.eq uri HObj.Logic.eq_ind_r_URI || Obj.is_eq_ind_r_URI uri
111    | _                     -> false
112
113 let is_rewrite_left = function
114    | C.AConst (_, uri, []) ->
115       UM.eq uri HObj.Logic.eq_ind_URI || Obj.is_eq_ind_URI uri
116    | _                     -> false
117 (*
118 let get_ind_name uri tno xcno =
119 try   
120    let ts = match E.get_obj Un.empty_ugraph uri with
121       | C.InductiveDefinition (ts, _, _,_), _ -> ts 
122       | _                                     -> assert false
123    in
124    let tname, cs = match List.nth ts tno with
125       | (name, _, _, cs) -> name, cs
126    in
127    match xcno with
128       | None     -> tname
129       | Some cno -> fst (List.nth cs (pred cno))
130 with Invalid_argument _ -> failwith "A2P.get_ind_name"
131 *)
132 let get_inner_types st v =
133 try
134    let id = Ut.id_of_annterm v in
135    try match Hashtbl.find st.types id with
136       | {A.annsynthesized = st; A.annexpected = Some et} -> Some (st, et)
137       | {A.annsynthesized = st; A.annexpected = None}    -> Some (st, st)
138    with Not_found -> None
139 with Invalid_argument _ -> failwith "A2P.get_inner_types"
140
141 let get_inner_sort st v =
142 try
143    let id = Ut.id_of_annterm v in
144    try Hashtbl.find st.sorts id
145    with Not_found -> `Type (CicUniv.fresh())
146 with Invalid_argument _ -> failwith "A2P.get_sort"
147
148 (* proof construction *******************************************************)
149
150 let unused_premise = "UNUSED"
151
152 let defined_premise = "DEFINED"
153
154 let assumed_premise = "ASSUMED"
155
156 let expanded_premise = "EXPANDED"
157
158 let convert st v = 
159    match get_inner_types st v with
160       | Some (st, et) ->
161          let cst, cet = cic st, cic et in
162          if PER.alpha_equivalence cst cet then [] else 
163          [T.Change (st, et, "")]
164       | None          -> []
165
166 let eta_expand n t =
167    let ty = C.AImplicit ("", None) in
168    let name i = Printf.sprintf "%s%u" expanded_premise i in 
169    let lambda i t = C.ALambda ("", C.Name (name i), ty, t) in
170    let arg i n = T.mk_arel (n - i) (name i) in
171    let rec aux i f a =
172       if i >= n then f, a else aux (succ i) (comp f (lambda i)) (arg i n :: a)
173    in
174    let absts, args = aux 0 id [] in
175    match Cn.lift 1 n t with
176       | C.AAppl (id, ts) -> absts (C.AAppl (id, ts @ args))
177       | t                -> absts (C.AAppl ("", t :: args))  
178
179 let appl_expand n = function
180    | C.AAppl (id, ts) -> 
181       let before, after = T.list_split (List.length ts + n) ts in
182       C.AAppl ("", C.AAppl (id, before) :: after)
183    | _                -> assert false
184
185 let get_intro name t = 
186 try
187 match name with 
188    | C.Anonymous -> unused_premise
189    | C.Name s    -> 
190       if DTI.does_not_occur 1 (cic t) then unused_premise else s
191 with Invalid_argument _ -> failwith "A2P.get_intro"
192
193 let mk_intros st script =
194 try
195    if st.intros = [] then script else
196    let count = List.length st.intros in
197    let p0 = T.Whd (count, "") in
198    let p1 = T.Intros (Some count, List.rev st.intros, "") in
199    match st.ety with
200       | Some ety when Cn.need_whd count ety -> p0 :: p1 :: script
201       | _                                   -> p1 :: script
202 with Invalid_argument _ -> failwith "A2P.mk_intros"
203
204 let rec mk_atomic st dtext what =
205    if T.is_atomic what then [], what else
206    let name = defined_premise in
207    mk_fwd_proof st dtext name what, T.mk_arel 0 name
208
209 and mk_fwd_rewrite st dtext name tl direction =
210    let what, where = List.nth tl 5, List.nth tl 3 in
211    let rewrite premise =
212       let script, what = mk_atomic st dtext what in
213       T.Rewrite (direction, what, Some (premise, name), dtext) :: script
214    in
215    match where with
216       | C.ARel (_, _, _, binder) -> rewrite binder
217       | _                        -> 
218          assert (get_inner_sort st where = `Prop);
219          let pred, old = List.nth tl 2, List.nth tl 1 in
220          let pred_name = defined_premise in
221          let pred_text = "extracted" in
222          let p1 = T.LetIn (pred_name, pred, pred_text) in
223          let cut_name = assumed_premise in
224          let cut_type = C.AAppl ("", [T.mk_arel 0 pred_name; old]) in
225          let cut_text = "" in
226          let p2 = T.Cut (cut_name, cut_type, cut_text) in
227          let qs = [rewrite cut_name; mk_proof (next st) where] in 
228          [T.Branch (qs, ""); p2; p1] 
229
230 and mk_fwd_proof st dtext name = function
231    | C.AAppl (_, hd :: tl) as v                         -> 
232       if is_rewrite_right hd then mk_fwd_rewrite st dtext name tl true else  
233       if is_rewrite_left hd then mk_fwd_rewrite st dtext name tl false else
234       let ty, _ = TC.type_of_aux' [] st.context (cic hd) Un.empty_ugraph in
235       begin match get_inner_types st v with
236          | Some (ity, _) when M.bkd st.context ty ->
237             let qs = [[T.Id ""]; mk_proof (next st) v] in
238             [T.Branch (qs, ""); T.Cut (name, ity, dtext)]
239          | _                                      ->
240             let (classes, rc) as h = Cl.classify st.context ty in
241             let text = Printf.sprintf "%u %s" (List.length classes) (Cl.to_string h) in
242             [T.LetIn (name, v, dtext ^ text)]
243       end
244    | C.AMutCase (id, uri, tyno, outty, arg, cases) as v ->
245       begin match Cn.mk_ind st.context id uri tyno outty arg cases with 
246          | None   -> [T.LetIn (name, v, dtext)] 
247          | Some v -> mk_fwd_proof st dtext name v
248       end
249    | v                                                  ->
250       [T.LetIn (name, v, dtext)]
251
252 and mk_proof st = function
253    | C.ALambda (_, name, v, t) as what             ->
254       let entry = Some (name, C.Decl (cic v)) in
255       let intro = get_intro name t in
256       let ety = match get_inner_types st what with
257          | Some (_, ety) -> Some ety
258          | None          -> None
259       in
260       mk_proof (add st entry intro ety) t
261    | C.ALetIn (_, name, v, t) as what              ->
262       let proceed, dtext = test_depth st in
263       let script = if proceed then 
264          let entry = Some (name, C.Def (cic v, None)) in
265          let intro = get_intro name t in
266          let q = mk_proof (next (add st entry intro None)) t in
267          List.rev_append (mk_fwd_proof st dtext intro v) q
268       else
269          [T.Apply (what, dtext)]
270       in
271       mk_intros st script
272    | C.ARel _ as what                              ->
273       let _, dtext = test_depth st in
274       let text = "assumption" in
275       let script = [T.Apply (what, dtext ^ text)] in 
276       mk_intros st script
277    | C.AMutConstruct _ as what                     ->
278       let _, dtext = test_depth st in
279       let script = [T.Apply (what, dtext)] in 
280       mk_intros st script   
281    | C.AAppl (_, hd :: tl) as t                    ->
282       let proceed, dtext = test_depth st in
283       let script = if proceed then
284          let ty, _ = TC.type_of_aux' [] st.context (cic hd) Un.empty_ugraph in
285          let (classes, rc) as h = Cl.classify st.context ty in
286          let decurry = List.length classes - List.length tl in
287          if decurry < 0 then mk_proof (clear st) (appl_expand decurry t) else
288          if decurry > 0 then mk_proof (clear st) (eta_expand decurry t) else
289          let synth = Cl.S.singleton 0 in
290          let text = Printf.sprintf "%u %s" (List.length classes) (Cl.to_string h) in
291          match rc with
292             | Some (i, j) when i > 1 && i <= List.length classes ->
293                let classes, tl, _, what = split2_last classes tl in
294                let script, what = mk_atomic st dtext what in
295                let synth = Cl.S.add 1 synth in
296                let qs = mk_bkd_proofs (next st) synth classes tl in
297                if is_rewrite_right hd then 
298                   List.rev script @ convert st t @
299                   [T.Rewrite (false, what, None, dtext); T.Branch (qs, "")]
300                else if is_rewrite_left hd then 
301                   List.rev script @ convert st t @
302                   [T.Rewrite (true, what, None, dtext); T.Branch (qs, "")]
303                else   
304                   let using = Some hd in
305                   List.rev script @ convert st t @
306                   [T.Elim (what, using, dtext ^ text); T.Branch (qs, "")]
307             | _                                                  ->
308                let qs = mk_bkd_proofs (next st) synth classes tl in
309                let script, hd = mk_atomic st dtext hd in               
310                List.rev script @ convert st t @        
311                [T.Apply (hd, dtext ^ text); T.Branch (qs, "")]
312       else
313          [T.Apply (t, dtext)]
314       in
315       mk_intros st script
316    | C.AMutCase (id, uri, tyno, outty, arg, cases) ->
317       begin match Cn.mk_ind st.context id uri tyno outty arg cases with 
318          | None   -> 
319             let text = Printf.sprintf "%s" "UNEXPANDED: mutcase" in
320             let script = [T.Note text] in
321             mk_intros st script
322          | Some t -> mk_proof st t
323       end
324    | t                                             ->
325       let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head t) in
326       let script = [T.Note text] in
327       mk_intros st script
328
329 and mk_bkd_proofs st synth classes ts =
330 try 
331    let _, dtext = test_depth st in   
332    let aux inv v =
333       if Cl.overlaps synth inv then None else
334       if Cl.S.is_empty inv then Some (mk_proof st v) else
335       Some [T.Apply (v, dtext ^ "dependent")]
336    in
337    T.list_map2_filter aux classes ts
338 with Invalid_argument _ -> failwith "A2P.mk_bkd_proofs"
339
340 (* object costruction *******************************************************)
341
342 let is_theorem pars =   
343    List.mem (`Flavour `Theorem) pars || List.mem (`Flavour `Fact) pars || 
344    List.mem (`Flavour `Remark) pars || List.mem (`Flavour `Lemma) pars
345
346 let mk_obj st = function
347    | C.AConstant (_, _, s, Some v, t, [], pars) when is_theorem pars ->
348       let ast = mk_proof (set_ety st (Some t)) v in
349       let count = T.count_steps 0 ast in
350       let text = Printf.sprintf "tactics: %u" count in
351       T.Theorem (s, t, text) :: ast @ [T.Qed ""]
352    | _                                                               ->
353       failwith "not a theorem"
354
355 (* interface functions ******************************************************)
356
357 let acic2procedural ~ids_to_inner_sorts ~ids_to_inner_types ?depth prefix aobj = 
358    let st = {
359       sorts     = ids_to_inner_sorts;
360       types     = ids_to_inner_types;
361       prefix    = prefix;
362       max_depth = depth;
363       depth     = 0;
364       context   = [];
365       intros    = [];
366       ety       = None
367    } in
368    HLog.debug "Level 2 transformation";
369    let steps = mk_obj st aobj in
370    HLog.debug "grafite rendering";
371    List.rev (T.render_steps [] steps)