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