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