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