]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/acic_procedural/acic2Procedural.ml
0edb5c8b041c9e2c5415790bd3a1badfca2ead20
[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 I    = CicInspect
28 module S    = CicSubstitution
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 Pp   = CicPp
38 module PEH  = ProofEngineHelpers
39 module HEL  = HExtlib
40 module DTI  = DoubleTypeInference
41 module NU   = CicNotationUtil
42 module L    = Librarian
43
44 module Cl   = ProceduralClassify
45 module T    = ProceduralTypes
46 module Cn   = ProceduralConversion
47 module H    = ProceduralHelpers
48 module X    = ProceduralTeX
49
50 type status = {
51    sorts : (C.id, A.sort_kind) Hashtbl.t;
52    types : (C.id, A.anntypes) Hashtbl.t;
53    max_depth: int option;
54    depth: int;
55    context: C.context;
56    case: int list
57 }
58
59 let tex_formatter = ref None
60
61 let debug = ref false
62
63 (* helpers ******************************************************************)
64
65 let split2_last l1 l2 =
66 try
67    let n = pred (List.length l1) in
68    let before1, after1 = HEL.split_nth n l1 in
69    let before2, after2 = HEL.split_nth n l2 in
70    before1, before2, List.hd after1, List.hd after2
71 with Invalid_argument _ -> failwith "A2P.split2_last"
72    
73 let string_of_head = function
74    | C.ASort _         -> "sort"
75    | C.AConst _        -> "const"
76    | C.AMutInd _       -> "mutind"
77    | C.AMutConstruct _ -> "mutconstruct"
78    | C.AVar _          -> "var"
79    | C.ARel _          -> "rel"
80    | C.AProd _         -> "prod"
81    | C.ALambda _       -> "lambda"
82    | C.ALetIn _        -> "letin"
83    | C.AFix _          -> "fix"
84    | C.ACoFix _        -> "cofix"
85    | C.AAppl _         -> "appl"
86    | C.ACast _         -> "cast"
87    | C.AMutCase _      -> "mutcase"
88    | C.AMeta _         -> "meta"
89    | C.AImplicit _     -> "implict"
90
91 let next st = {st with depth = succ st.depth}
92
93 let add st entry = {st with context = entry :: st.context}
94
95 let push st = {st with case = 1 :: st.case}
96
97 let inc st =
98    {st with case = match st.case with 
99       | []       -> []
100       | hd :: tl -> succ hd :: tl
101    }
102
103 let case st str =
104    let case = String.concat "." (List.rev_map string_of_int st.case) in
105    Printf.sprintf "case %s: %s" case str
106
107 let test_depth st =
108 try   
109    let msg = Printf.sprintf "Depth %u: " st.depth in
110    match st.max_depth with
111       | None   -> true, "" 
112       | Some d -> if st.depth < d then true, msg else false, "DEPTH EXCEDED: "
113 with Invalid_argument _ -> failwith "A2P.test_depth"
114
115 let is_rewrite_right = function
116    | C.AConst (_, uri, []) ->
117       UM.eq uri HObj.Logic.eq_ind_r_URI || Obj.is_eq_ind_r_URI uri
118    | _                     -> false
119
120 let is_rewrite_left = function
121    | C.AConst (_, uri, []) ->
122       UM.eq uri HObj.Logic.eq_ind_URI || Obj.is_eq_ind_URI uri
123    | _                     -> false
124
125 let is_fwd_rewrite_right hd tl =
126    if is_rewrite_right hd then match List.nth tl 3 with
127       | C.ARel _ -> true
128       | _        -> false
129    else false
130
131 let is_fwd_rewrite_left hd tl =
132    if is_rewrite_left hd then match List.nth tl 3 with
133       | C.ARel _ -> true
134       | _        -> false
135    else false
136
137 let get_inner_types st v =
138 try
139    let id = Ut.id_of_annterm v in
140    try match Hashtbl.find st.types id with
141       | {A.annsynthesized = st; A.annexpected = Some et} -> Some (st, et)
142       | {A.annsynthesized = st; A.annexpected = None}    -> Some (st, st)
143    with Not_found -> None
144 with Invalid_argument _ -> failwith "A2P.get_inner_types"
145 (*
146 let get_inner_sort st v =
147 try
148    let id = Ut.id_of_annterm v in
149    try Hashtbl.find st.sorts id
150    with Not_found -> `Type (CicUniv.fresh())
151 with Invalid_argument _ -> failwith "A2P.get_sort"
152 *)
153 let get_entry st id =
154    let rec aux = function
155       | []                                        -> assert false
156       | Some (C.Name name, e) :: _ when name = id -> e
157       | _ :: tl                                   -> aux tl
158    in
159    aux st.context
160
161 let string_of_atomic = function
162    | C.ARel (_, _, _, s)               -> s
163    | C.AVar (_, uri, _)                -> H.name_of_uri uri None None
164    | C.AConst (_, uri, _)              -> H.name_of_uri uri None None
165    | C.AMutInd (_, uri, i, _)          -> H.name_of_uri uri (Some i) None
166    | C.AMutConstruct (_, uri, i, j, _) -> H.name_of_uri uri (Some i) (Some j)
167    | _                                 -> ""
168
169 let get_sub_names head l =
170    let s = string_of_atomic head in
171    if s = "" then [] else
172    let map (names, i) _ = 
173       let name = Printf.sprintf "%s_%u" s i in name :: names, succ i
174    in
175    let names, _ = List.fold_left map ([], 1) l in 
176    List.rev names
177
178 let get_type msg st t = H.get_type msg st.context (H.cic t) 
179
180 let clear_absts m =
181    let rec aux k n = function
182       | C.ALambda (id, s, v, t) when k > 0 -> 
183          C.ALambda (id, s, v, aux (pred k) n t)
184       | C.ALambda (_, _, _, t) when n > 0 -> 
185          aux 0 (pred n) (Cn.lift 1 (-1) t)
186       | t                  when n > 0 ->
187          Printf.eprintf "A2P.clear_absts: %u %s\n" n (Pp.ppterm (H.cic t));
188          assert false
189       | t                             -> t
190    in 
191    aux m
192
193 (* proof construction *******************************************************)
194
195 let anonymous_premise = C.Name "UNNAMED"
196
197 let mk_exp_args hd tl classes synth =
198    let meta id = C.AImplicit (id, None) in
199    let map v (cl, b) =
200       if I.overlaps synth cl && b then v else meta ""
201    in
202    let rec aux = function
203       | [] -> []
204       | hd :: tl -> if hd = meta "" then aux tl else List.rev (hd :: tl)
205    in
206    let args = T.list_rev_map2 map tl classes in
207    let args = aux args in
208    if args = [] then hd else C.AAppl ("", hd :: args)
209
210 let mk_convert st ?name sty ety note =
211    let e = Cn.hole "" in
212    let csty, cety = H.cic sty, H.cic ety in
213    let script = 
214       if !debug then
215          let sname = match name with None -> "" | Some (id, _) -> id in
216          let note = Printf.sprintf "%s: %s\nSINTH: %s\nEXP: %s"
217             note sname (Pp.ppterm csty) (Pp.ppterm cety)
218          in 
219          [T.Note note]
220       else []
221    in
222    assert (Ut.is_sober st.context csty); 
223    assert (Ut.is_sober st.context cety);
224    if Ut.alpha_equivalence csty cety then script else 
225    let sty, ety = H.acic_bc st.context sty, H.acic_bc st.context ety in
226    match name with
227       | None         -> T.Change (sty, ety, None, e, "") :: script
228       | Some (id, i) -> 
229          begin match get_entry st id with
230             | C.Def _  -> assert false (* T.ClearBody (id, "") :: script *)
231             | C.Decl _ -> 
232                T.Change (ety, sty, Some (id, Some id), e, "") :: script 
233          end
234
235 let convert st ?name v = 
236    match get_inner_types st v with
237       | None            -> 
238          if !debug then [T.Note "NORMAL: NO INNER TYPES"] else []
239       | Some (sty, ety) -> mk_convert st ?name sty ety "NORMAL"
240           
241 let get_intro = function 
242    | C.Anonymous -> None
243    | C.Name s    -> Some s
244
245 let mk_preamble st what script =
246    convert st what @ script   
247
248 let mk_arg st = function
249    | C.ARel (_, _, i, name) as what -> convert st ~name:(name, i) what
250    | _                              -> []
251
252 let mk_fwd_rewrite st dtext name tl direction v t ity =
253    let compare premise = function
254       | None   -> true
255       | Some s -> s = premise
256    in
257    assert (List.length tl = 6);
258    let what, where, predicate = List.nth tl 5, List.nth tl 3, List.nth tl 2 in
259    let e = Cn.mk_pattern 1 predicate in
260    if (Cn.does_not_occur e) then st, [] else 
261    match where with
262       | C.ARel (_, _, i, premise) as w ->
263          let script name =
264             let where = Some (premise, name) in
265             let script = mk_arg st what @ mk_arg st w in
266             T.Rewrite (direction, what, where, e, dtext) :: script
267          in
268          if DTI.does_not_occur (succ i) (H.cic t) || compare premise name then
269             {st with context = Cn.clear st.context premise}, script name
270          else begin
271             assert (Ut.is_sober st.context (H.cic ity));
272             let ity = H.acic_bc st.context ity in
273             let br1 = [T.Id ""] in
274             let br2 = List.rev (T.Apply (w, "assumption") :: script None) in
275             let text = "non-linear rewrite" in
276             st, [T.Branch ([br2; br1], ""); T.Cut (name, ity, text)]
277          end
278       | _                         -> assert false
279
280 let mk_rewrite st dtext where qs tl direction t = 
281    assert (List.length tl = 5);
282    let predicate = List.nth tl 2 in
283    let e = Cn.mk_pattern 1 predicate in
284    let script = [T.Branch (qs, "")] in
285    if (Cn.does_not_occur e) then script else
286    T.Rewrite (direction, where, None, e, dtext) :: script
287
288 let rec proc_lambda st what name v t =
289    let name = match name with
290       | C.Anonymous -> H.mk_fresh_name st.context anonymous_premise
291       | name        -> name
292    in
293    let entry = Some (name, C.Decl (H.cic v)) in
294    let intro = get_intro name in
295    let script = proc_proof (add st entry) t in
296    let script = T.Intros (Some 1, [intro], "") :: script in
297    mk_preamble st what script
298
299 and proc_letin st what name v w t =
300    let intro = get_intro name in
301    let proceed, dtext = test_depth st in
302    let script = if proceed then 
303       let st, hyp, rqv = match get_inner_types st v with
304          | Some (ity, _) ->
305             let st, rqv = match v with
306                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_right hd tl ->
307                   mk_fwd_rewrite st dtext intro tl true v t ity
308                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_left hd tl  ->
309                   mk_fwd_rewrite st dtext intro tl false v t ity
310                | v                                                     ->
311                   assert (Ut.is_sober st.context (H.cic ity));
312                   let ity = H.acic_bc st.context ity in
313                   let qs = [proc_proof (next st) v; [T.Id ""]] in
314                   st, [T.Branch (qs, ""); T.Cut (intro, ity, dtext)]
315             in
316             st, C.Decl (H.cic ity), rqv
317          | None          ->
318             st, C.Def (H.cic v, H.cic w), [T.LetIn (intro, v, dtext)]
319       in
320       let entry = Some (name, hyp) in
321       let qt = proc_proof (next (add st entry)) t in
322       List.rev_append rqv qt      
323    else
324       [T.Apply (what, dtext)]
325    in
326    mk_preamble st what script
327
328 and proc_rel st what = 
329    let _, dtext = test_depth st in
330    let text = "assumption" in
331    let script = [T.Apply (what, dtext ^ text)] in 
332    mk_preamble st what script
333
334 and proc_mutconstruct st what = 
335    let _, dtext = test_depth st in
336    let script = [T.Apply (what, dtext)] in 
337    mk_preamble st what script
338
339 and proc_const st what = 
340    let _, dtext = test_depth st in
341    let script = [T.Apply (what, dtext)] in 
342    mk_preamble st what script
343
344 and proc_appl st what hd tl =
345    let proceed, dtext = test_depth st in
346    let script = if proceed then
347       let ty = match get_inner_types st hd with
348          | Some (ity, _) -> H.cic ity 
349          | None          -> get_type "TC2" st hd 
350       in
351       let classes, rc = Cl.classify st.context ty in
352       let goal_arity, goal = match get_inner_types st what with
353          | None            -> 0, None
354          | Some (ity, ety) -> 
355            snd (PEH.split_with_whd (st.context, H.cic ity)), Some (H.cic ety)
356       in
357       let parsno, argsno = List.length classes, List.length tl in
358       let decurry = parsno - argsno in
359       let diff = goal_arity - decurry in
360       if diff < 0 then failwith (Printf.sprintf "NOT TOTAL: %i %s |--- %s" diff (Pp.ppcontext st.context) (Pp.ppterm (H.cic hd)));
361       let classes = Cl.adjust st.context tl ?goal classes in
362       let rec mk_synth a n =
363          if n < 0 then a else mk_synth (I.S.add n a) (pred n)
364       in
365       let synth = mk_synth I.S.empty decurry in
366       let text = "" (* Printf.sprintf "%u %s" parsno (Cl.to_string h) *) in
367       let script = List.rev (mk_arg st hd) in
368       match rc with
369          | Some (i, j, uri, tyno) ->
370             let classes2, tl2, _, where = split2_last classes tl in
371             let script2 = List.rev (mk_arg st where) @ script in
372             let synth2 = I.S.add 1 synth in
373             let names = H.get_ind_names uri tyno in
374             let qs = proc_bkd_proofs (next st) synth2 names classes2 tl2 in
375             if List.length qs <> List.length names then
376                let qs = proc_bkd_proofs (next st) synth [] classes tl in
377                let hd = mk_exp_args hd tl classes synth in
378                script @ [T.Apply (hd, dtext ^ text); T.Branch (qs, "")]
379             else if is_rewrite_right hd then 
380                script2 @ mk_rewrite st dtext where qs tl2 false what
381             else if is_rewrite_left hd then 
382                script2 @ mk_rewrite st dtext where qs tl2 true what
383             else
384                let predicate = List.nth tl2 (parsno - i) in
385                let e = Cn.mk_pattern j predicate in
386                let using = Some hd in
387                script2 @ 
388                [T.Elim (where, using, e, dtext ^ text); T.Branch (qs, "")]
389          | None        ->
390             let names = get_sub_names hd tl in
391             let qs = proc_bkd_proofs (next st) synth names classes tl in
392             let hd = mk_exp_args hd tl classes synth in
393             script @ [T.Apply (hd, dtext ^ text); T.Branch (qs, "")]
394    else
395       [T.Apply (what, dtext)]
396    in
397    mk_preamble st what script
398
399 and proc_case st what uri tyno u v ts =
400    let proceed, dtext = test_depth st in
401    let script = if proceed then
402       let synth, classes = I.S.empty, Cl.make ts in
403       let names = H.get_ind_names uri tyno in
404       let qs = proc_bkd_proofs (next st) synth names classes ts in
405       let lpsno, _ = H.get_ind_type uri tyno in
406       let ps, sort_disp = H.get_ind_parameters st.context (H.cic v) in
407       let _, rps = HEL.split_nth lpsno ps in
408       let rpsno = List.length rps in   
409       let predicate = clear_absts rpsno (1 - sort_disp) u in
410       let e = Cn.mk_pattern rpsno predicate in
411       let text = "" in
412       let script = List.rev (mk_arg st v) in
413       script @ [T.Cases (v, e, dtext ^ text); T.Branch (qs, "")]   
414    else
415       [T.Apply (what, dtext)]
416    in
417    mk_preamble st what script
418
419 and proc_other st what =
420    let _, dtext = test_depth st in
421    let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head what) in
422    let script = [T.Apply (what, dtext ^ text)] in 
423    mk_preamble st what script
424
425 and proc_proof st t = 
426    let f st =
427       let xtypes, note = match get_inner_types st t with
428          | Some (it, et) -> Some (H.cic it, H.cic et), 
429           (Printf.sprintf "\nInferred: %s\nExpected: %s"
430           (Pp.ppterm (H.cic it)) (Pp.ppterm (H.cic et))) 
431          | None          -> None, "\nNo types"
432       in
433       let context, _clears = Cn.get_clears st.context (H.cic t) xtypes in
434       {st with context = context}
435    in
436    match t with
437       | C.ALambda (_, name, w, t) as what        -> proc_lambda (f st) what name w t
438       | C.ALetIn (_, name, v, w, t) as what      -> proc_letin (f st) what name v w t
439       | C.ARel _ as what                         -> proc_rel (f st) what
440       | C.AMutConstruct _ as what                -> proc_mutconstruct (f st) what
441       | C.AConst _ as what                       -> proc_const (f st) what
442       | C.AAppl (_, hd :: tl) as what            -> proc_appl (f st) what hd tl
443       | C.AMutCase (_, uri, i, u, v, ts) as what -> proc_case (f st) what uri i u v ts
444       | what                                     -> proc_other (f st) what
445
446 and proc_bkd_proofs st synth names classes ts =
447 try 
448    let get_names b = ref (names, if b then push st else st) in
449    let get_note f b names = 
450       match !names with 
451          | [], st       -> f st
452          | "" :: tl, st -> names := tl, st; f st
453          | hd :: tl, st -> 
454             let note = case st hd in
455             names := tl, inc st; 
456             if b then T.Note note :: f st else f st
457    in
458    let _, dtext = test_depth st in   
459    let aux (inv, _) v =
460       if I.overlaps synth inv then None else
461       if I.S.is_empty inv then Some (get_note (fun st -> proc_proof st v)) else
462       Some (get_note (fun _ -> [T.Apply (v, dtext ^ "dependent")]))
463    in   
464    let ps = T.list_map2_filter aux classes ts in
465    let b = List.length ps > 1 in
466    let names = get_names b in
467    List.rev_map (fun f -> f b names) ps
468
469 with Invalid_argument s -> failwith ("A2P.proc_bkd_proofs: " ^ s)
470
471 (* object costruction *******************************************************)
472
473 let th_flavours = [`Theorem; `Lemma; `Remark; `Fact]
474
475 let def_flavours = [`Definition]
476
477 let get_flavour ?flavour attrs =
478    let rec aux = function
479       | []               -> List.hd th_flavours
480       | `Flavour fl :: _ -> fl
481       | _ :: tl          -> aux tl
482    in
483    match flavour with
484       | Some fl -> fl
485       | None    -> aux attrs
486
487 let proc_obj ?flavour ?(info="") st = function
488    | C.AConstant (_, _, s, Some v, t, [], attrs)         ->
489       begin match get_flavour ?flavour attrs with
490          | flavour when List.mem flavour th_flavours  ->
491             let ast = proc_proof st v in
492             let steps, nodes = T.count_steps 0 ast, T.count_nodes 0 ast in
493             let text = Printf.sprintf "%s\n%s%s: %u\n%s: %u\n%s"
494                "COMMENTS" info "Tactics" steps "Final nodes" nodes "END"
495             in
496             T.Statement (flavour, Some s, t, None, "") :: ast @ [T.Qed text]
497          | flavour when List.mem flavour def_flavours ->
498             [T.Statement (flavour, Some s, t, Some v, "")]
499          | _                                  ->
500             failwith "not a theorem, definition, axiom or inductive type"
501       end
502    | C.AConstant (_, _, s, None, t, [], attrs)           ->
503       [T.Statement (`Axiom, Some s, t, None, "")]
504    | C.AInductiveDefinition (_, types, [], lpsno, attrs) ->
505       [T.Inductive (types, lpsno, "")] 
506    | _                                          ->
507       failwith "not a theorem, definition, axiom or inductive type"
508
509 (* interface functions ******************************************************)
510
511 let procedural_of_acic_object ~ids_to_inner_sorts ~ids_to_inner_types 
512    ?info ?depth ?flavour prefix anobj = 
513    let st = {
514       sorts       = ids_to_inner_sorts;
515       types       = ids_to_inner_types;
516       max_depth   = depth;
517       depth       = 0;
518       context     = [];
519       case        = []
520    } in
521    L.time_stamp "P : LEVEL 1  ";
522    HLog.debug "Procedural: level 1 transformation";
523    let steps = proc_obj st ?flavour ?info anobj in
524    let _ = match !tex_formatter with
525       | None     -> ()
526       | Some frm -> X.tex_of_steps frm st.sorts steps
527    in
528    L.time_stamp "P : RENDERING";
529    HLog.debug "Procedural: grafite rendering";
530    let r = List.rev (T.render_steps [] steps) in
531    L.time_stamp "P : DONE     "; r
532
533 let procedural_of_acic_term ~ids_to_inner_sorts ~ids_to_inner_types ?depth
534    prefix context annterm = 
535    let st = {
536       sorts       = ids_to_inner_sorts;
537       types       = ids_to_inner_types;
538       max_depth   = depth;
539       depth       = 0;
540       context     = context;
541       case        = []
542    } in
543    HLog.debug "Procedural: level 1 transformation";
544    let steps = proc_proof st annterm in
545    let _ = match !tex_formatter with
546       | None     -> ()
547       | Some frm -> X.tex_of_steps frm st.sorts steps
548    in
549    HLog.debug "Procedural: grafite rendering";
550    List.rev (T.render_steps [] steps)