]> matita.cs.unibo.it Git - helm.git/blob - components/acic_procedural/acic2Procedural.ml
bbc358f71e7fbc0db2eebce8f7624e393d072877
[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 }
54
55 (* helpers ******************************************************************)
56
57 let identity 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 = []}
90
91 let next st = {(clear st) with depth = succ st.depth}
92
93 let add st entry intro =
94    {st with context = entry :: st.context; intros = intro :: st.intros}
95
96 let test_depth st =
97 try   
98    let msg = Printf.sprintf "Depth %u: " st.depth in
99    match st.max_depth with
100       | None   -> true, "" 
101       | Some d -> if st.depth < d then true, msg else false, "DEPTH EXCEDED: "
102 with Invalid_argument _ -> failwith "A2P.test_depth"
103
104 let is_rewrite_right = function
105    | C.AConst (_, uri, []) ->
106       UM.eq uri HObj.Logic.eq_ind_r_URI || Obj.is_eq_ind_r_URI uri
107    | _                     -> false
108
109 let is_rewrite_left = function
110    | C.AConst (_, uri, []) ->
111       UM.eq uri HObj.Logic.eq_ind_URI || Obj.is_eq_ind_URI uri
112    | _                     -> false
113
114 let is_fwd_rewrite_right hd tl =
115    if is_rewrite_right hd then match List.nth tl 3 with
116       | C.ARel _ -> true
117       | _        -> false
118    else false
119
120 let is_fwd_rewrite_left hd tl =
121    if is_rewrite_left hd then match List.nth tl 3 with
122       | C.ARel _ -> true
123       | _        -> false
124    else false
125 (*
126 let get_ind_name uri tno xcno =
127 try   
128    let ts = match E.get_obj Un.empty_ugraph uri with
129       | C.InductiveDefinition (ts, _, _,_), _ -> ts 
130       | _                                     -> assert false
131    in
132    let tname, cs = match List.nth ts tno with
133       | (name, _, _, cs) -> name, cs
134    in
135    match xcno with
136       | None     -> tname
137       | Some cno -> fst (List.nth cs (pred cno))
138 with Invalid_argument _ -> failwith "A2P.get_ind_name"
139 *)
140 let get_inner_types st v =
141 try
142    let id = Ut.id_of_annterm v in
143    try match Hashtbl.find st.types id with
144       | {A.annsynthesized = st; A.annexpected = Some et} -> Some (st, et)
145       | {A.annsynthesized = st; A.annexpected = None}    -> Some (st, st)
146    with Not_found -> None
147 with Invalid_argument _ -> failwith "A2P.get_inner_types"
148
149 let get_inner_sort st v =
150 try
151    let id = Ut.id_of_annterm v in
152    try Hashtbl.find st.sorts id
153    with Not_found -> `Type (CicUniv.fresh())
154 with Invalid_argument _ -> failwith "A2P.get_sort"
155
156 (* proof construction *******************************************************)
157
158 let unused_premise = "UNUSED"
159
160 let defined_premise = "DEFINED"
161
162 let expanded_premise = "EXPANDED"
163
164 let convert st ?name v = 
165    match get_inner_types st v with
166       | None          -> []
167       | Some (st, et) ->
168          let cst, cet = cic st, cic et in
169          if PER.alpha_equivalence cst cet then [] else 
170          let e = Cn.mk_pattern [] (T.mk_arel 1 "") in
171          match name with
172             | None    -> [T.Change (st, et, None, e, "")]
173             | Some id -> [T.Change (st, et, Some (id, id), e, ""); T.ClearBody (id, "")]
174
175 let eta_expand n t =
176    let id = Ut.id_of_annterm t in
177    let ty = C.AImplicit ("", None) in
178    let name i = Printf.sprintf "%s%u" expanded_premise i in 
179    let lambda i t = C.ALambda (id, C.Name (name i), ty, t) in
180    let arg i n = T.mk_arel (n - i) (name (n - i - 1)) in
181    let rec aux i f a =
182       if i >= n then f, a else aux (succ i) (comp f (lambda i)) (arg i n :: a)
183    in
184    let absts, args = aux 0 identity [] in
185    match Cn.lift 1 n t with
186       | C.AAppl (id, ts) -> absts (C.AAppl (id, ts @ args))
187       | t                -> absts (C.AAppl ("", t :: args))  
188
189 let appl_expand n = function
190    | C.AAppl (id, ts) -> 
191       let before, after = T.list_split (List.length ts + n) ts in
192       C.AAppl (id, C.AAppl ("", before) :: after)
193    | _                -> assert false
194
195 let get_intro name t = 
196 try
197 match name with 
198    | C.Anonymous -> unused_premise
199    | C.Name s    -> 
200       if DTI.does_not_occur 1 (cic t) then unused_premise else s
201 with Invalid_argument _ -> failwith "A2P.get_intro"
202
203 let mk_intros st script =
204 try
205    if st.intros = [] then script else
206    let count = List.length st.intros in
207    T.Intros (Some count, List.rev st.intros, "") :: script
208 with Invalid_argument _ -> failwith "A2P.mk_intros"
209
210 let rec mk_atomic st dtext what =
211    if T.is_atomic what then 
212       match what with 
213       | C.ARel (_, _, _, name) -> convert st ~name what, what
214       | _                      -> [], what
215    else
216       let name = defined_premise in
217       let script = convert st ~name what in  
218       script @ mk_fwd_proof st dtext name what, T.mk_arel 0 name
219
220 and mk_fwd_rewrite st dtext name tl direction =
221    let what, where = List.nth tl 5, List.nth tl 3 in
222    let rps, predicate = [List.nth tl 4], List.nth tl 2 in
223    let e = Cn.mk_pattern rps predicate in
224    match where with
225       | C.ARel (_, _, _, premise) ->
226          let script, what = mk_atomic st dtext what in
227          T.Rewrite (direction, what, Some (premise, name), e, dtext) :: script
228       | _                         -> assert false
229
230 and mk_fwd_proof st dtext name = function
231    | C.ALetIn (_, n, v, t)                           ->
232       let entry = Some (n, C.Def (cic v, None)) in
233       let intro = get_intro n t in
234       let qt = mk_fwd_proof (add st entry intro) dtext name t in
235       let qv = mk_fwd_proof st "" intro v in
236       List.append qt qv
237    | C.AAppl (_, hd :: tl) as v                         -> 
238       if is_fwd_rewrite_right hd tl then mk_fwd_rewrite st dtext name tl true else
239       if is_fwd_rewrite_left hd tl then mk_fwd_rewrite st dtext name tl false else
240       let ty, _ = TC.type_of_aux' [] st.context (cic hd) Un.empty_ugraph in
241       begin match get_inner_types st v with
242          | Some (ity, _) when M.bkd st.context ty ->
243             let qs = [[T.Id ""]; mk_proof (next st) v] in
244             [T.Branch (qs, ""); T.Cut (name, ity, dtext)]
245          | _                                      ->
246             let (classes, rc) as h = Cl.classify st.context ty in
247             let text = Printf.sprintf "%u %s" (List.length classes) (Cl.to_string h) in
248             [T.LetIn (name, v, dtext ^ text)]
249       end
250    | C.AMutCase (id, uri, tyno, outty, arg, cases) as v ->
251       begin match Cn.mk_ind st.context id uri tyno outty arg cases with 
252          | None   -> [T.LetIn (name, v, dtext)] 
253          | Some v -> mk_fwd_proof st dtext name v
254       end
255    | C.ACast (_, v, _)                                  ->
256       mk_fwd_proof st dtext name v
257    | v                                                  ->
258       match get_inner_types st v with
259          | Some (ity, _) ->
260             let qs = [[T.Id ""]; mk_proof (next st) v] in
261             [T.Branch (qs, ""); T.Cut (name, ity, dtext)]
262          | _             ->
263             [T.LetIn (name, v, dtext)]
264
265 and mk_proof st = function
266    | C.ALambda (_, name, v, t)                     ->
267       let entry = Some (name, C.Decl (cic v)) in
268       let intro = get_intro name t in
269       mk_proof (add st entry intro) t
270    | C.ALetIn (_, name, v, t) as what              ->
271       let proceed, dtext = test_depth st in
272       let script = if proceed then 
273          let entry = Some (name, C.Def (cic v, None)) in
274          let intro = get_intro name t in
275          let q = mk_proof (next (add st entry intro)) t in
276          List.rev_append (mk_fwd_proof st dtext intro v) q
277       else
278          [T.Apply (what, dtext)]
279       in
280       mk_intros st script
281    | C.ARel _ as what                              ->
282       let _, dtext = test_depth st in
283       let text = "assumption" in
284       let script = [T.Apply (what, dtext ^ text)] in 
285       mk_intros st script
286    | C.AMutConstruct _ as what                     ->
287       let _, dtext = test_depth st in
288       let script = [T.Apply (what, dtext)] in 
289       mk_intros st script   
290    | C.AAppl (_, hd :: tl) as t                    ->
291       let proceed, dtext = test_depth st in
292       let script = if proceed then
293          let ty, _ = TC.type_of_aux' [] st.context (cic hd) Un.empty_ugraph in
294          let (classes, rc) as h = Cl.classify st.context ty in
295          let premises, _ = Cl.split st.context ty in
296          let decurry = List.length classes - List.length tl in
297          if decurry < 0 then mk_proof (clear st) (appl_expand decurry t) else
298          if decurry > 0 then mk_proof (clear st) (eta_expand decurry t) else
299          let synth = I.S.singleton 0 in
300          let text = Printf.sprintf "%u %s" (List.length classes) (Cl.to_string h) in
301          match rc with
302             | Some (i, j) when i > 1 && i <= List.length classes && M.is_eliminator premises ->
303                let classes, tl, _, what = split2_last classes tl in
304                let script, what = mk_atomic st dtext what in
305                let synth = I.S.add 1 synth in
306                let qs = mk_bkd_proofs (next st) synth classes tl in
307                if is_rewrite_right hd then 
308                   let rps, predicate = [List.nth tl 4], List.nth tl 2 in
309                   let e = Cn.mk_pattern rps predicate in
310                   List.rev script @ convert st t @
311                   [T.Rewrite (false, what, None, e, dtext); T.Branch (qs, "")]
312                else if is_rewrite_left hd then 
313                   let rps, predicate = [List.nth tl 4], List.nth tl 2 in
314                   let e = Cn.mk_pattern rps predicate in
315                   List.rev script @ convert st t @
316                   [T.Rewrite (true, what, None, e, dtext); T.Branch (qs, "")]
317                else   
318                   let using = Some hd in
319                   List.rev script @ convert st t @
320                   [T.Elim (what, using, dtext ^ text); T.Branch (qs, "")]
321             | _                                                  ->
322                let qs = mk_bkd_proofs (next st) synth classes tl in
323                let script, hd = mk_atomic st dtext hd in               
324                List.rev script @ convert st t @        
325                [T.Apply (hd, dtext ^ text); T.Branch (qs, "")]
326       else
327          [T.Apply (t, dtext)]
328       in
329       mk_intros st script
330    | C.AMutCase (id, uri, tyno, outty, arg, cases) ->
331       begin match Cn.mk_ind st.context id uri tyno outty arg cases with 
332          | _ (* None *)  -> 
333             let text = Printf.sprintf "%s" "UNEXPANDED: mutcase" in
334             let script = [T.Note text] in
335             mk_intros st script
336 (*         | Some t -> mk_proof st t *)
337       end
338    | C.ACast (_, t, _)                             ->
339       mk_proof st t
340    | t                                             ->
341       let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head t) in
342       let script = [T.Note text] in
343       mk_intros st script
344
345 and mk_bkd_proofs st synth classes ts =
346 try 
347    let _, dtext = test_depth st in   
348    let aux inv v =
349       if I.overlaps synth inv then None else
350       if I.S.is_empty inv then Some (mk_proof st v) else
351       Some [T.Apply (v, dtext ^ "dependent")]
352    in
353    T.list_map2_filter aux classes ts
354 with Invalid_argument _ -> failwith "A2P.mk_bkd_proofs"
355
356 (* object costruction *******************************************************)
357
358 let is_theorem pars =   
359    List.mem (`Flavour `Theorem) pars || List.mem (`Flavour `Fact) pars || 
360    List.mem (`Flavour `Remark) pars || List.mem (`Flavour `Lemma) pars
361
362 let mk_obj st = function
363    | C.AConstant (_, _, s, Some v, t, [], pars) when is_theorem pars ->
364       let ast = mk_proof st v in
365       let count = T.count_steps 0 ast in
366       let text = Printf.sprintf "tactics: %u" count in
367       T.Theorem (s, t, text) :: ast @ [T.Qed ""]
368    | _                                                               ->
369       failwith "not a theorem"
370
371 (* interface functions ******************************************************)
372
373 let acic2procedural ~ids_to_inner_sorts ~ids_to_inner_types ?depth prefix aobj = 
374    let st = {
375       sorts     = ids_to_inner_sorts;
376       types     = ids_to_inner_types;
377       prefix    = prefix;
378       max_depth = depth;
379       depth     = 0;
380       context   = [];
381       intros    = []
382    } in
383    HLog.debug "Level 2 transformation";
384    let steps = mk_obj st aobj in
385    HLog.debug "grafite rendering";
386    List.rev (T.render_steps [] steps)