]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/acic_procedural/procedural2.ml
- Procedural convertible rewrites in the conclusion are now detected and replaced...
[helm.git] / helm / software / components / acic_procedural / procedural2.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 R    = CicReduction
30 module TC   = CicTypeChecker 
31 module Un   = CicUniv
32 module UM   = UriManager
33 module Obj  = LibraryObjects
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 module G    = GrafiteAst
44
45 module Cl   = ProceduralClassify
46 module T    = ProceduralTypes
47 module Cn   = ProceduralConversion
48 module H    = ProceduralHelpers
49
50 type status = {
51    sorts    : (C.id, A.sort_kind) Hashtbl.t;
52    types    : (C.id, A.anntypes) Hashtbl.t;
53    params   : G.inline_param list;
54    max_depth: int option;
55    depth    : int;
56    defaults : bool;
57    context  : C.context;
58    case     : int list
59 }
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 st = function
116    | C.AConst (_, uri, []) -> st.defaults && Obj.is_eq_ind_r_URI uri
117    | _                     -> false
118
119 let is_rewrite_left st = function
120    | C.AConst (_, uri, []) -> st.defaults && Obj.is_eq_ind_URI uri
121    | _                     -> false
122
123 let is_fwd_rewrite_right st hd tl =
124    if is_rewrite_right st hd then match List.nth tl 3 with
125       | C.ARel _ -> true
126       | _        -> false
127    else false
128
129 let is_fwd_rewrite_left st hd tl =
130    if is_rewrite_left st 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 = ity; A.annexpected = Some ety} -> Some (ity, ety)
140       | {A.annsynthesized = ity; A.annexpected = None}     -> Some (ity, ity)
141    with Not_found -> None
142 with Invalid_argument _ -> failwith "P2.get_inner_types"
143
144 let get_entry st id =
145    let rec aux = function
146       | []                                        -> assert false
147       | Some (C.Name name, e) :: _ when name = id -> e
148       | _ :: tl                                   -> aux tl
149    in
150    aux st.context
151
152 let string_of_atomic = function
153    | C.ARel (_, _, _, s)               -> s
154    | C.AVar (_, uri, _)                -> H.name_of_uri uri None None
155    | C.AConst (_, uri, _)              -> H.name_of_uri uri None None
156    | C.AMutInd (_, uri, i, _)          -> H.name_of_uri uri (Some i) None
157    | C.AMutConstruct (_, uri, i, j, _) -> H.name_of_uri uri (Some i) (Some j)
158    | _                                 -> ""
159
160 let get_sub_names head l =
161    let s = string_of_atomic head in
162    if s = "" then [] else
163    let map (names, i) _ = 
164       let name = Printf.sprintf "%s_%u" s i in name :: names, succ i
165    in
166    let names, _ = List.fold_left map ([], 1) l in 
167    List.rev names
168
169 let get_type msg st t = H.get_type msg st.context (H.cic t) 
170
171 let get_uri_of_head = function
172    | C.AConst (_, u, _)
173    | C.AAppl (_, C.AConst (_, u, _) :: _)              -> Some (u, 0, 0)
174    | C.AMutInd (_, u, i, _)
175    | C.AAppl (_, C.AMutInd (_, u, i, _) :: _)          -> Some (u, succ i, 0)
176    | C.AMutConstruct (_, u, i, j, _)
177    | C.AAppl (_, C.AMutConstruct (_, u, i, j, _) :: _) -> Some (u, succ i, j)
178    | _                                                 -> None
179
180 let get_uri_of_apply = function
181    | T.Exact (t, _)
182    | T.Apply (t, _) -> get_uri_of_head t
183    | _              -> None
184
185 let is_reflexivity st step =
186    match get_uri_of_apply step with
187       | None             -> false
188       | Some (uri, i, j) -> st.defaults && Obj.is_eq_URI uri && i = 1 && j = 1
189
190 let are_convertible st pred sx dx =
191    let pred, sx, dx = H.cic pred, H.cic sx, H.cic dx in
192    let sx, dx = C.Appl [pred; sx], C.Appl [pred; dx] in
193    fst (R.are_convertible st.context sx dx Un.default_ugraph)
194
195 (* proof construction *******************************************************)
196
197 let anonymous_premise = C.Name "UNNAMED"
198
199 let mk_exp_args hd tl classes synth qs =
200    let exp = ref 0 in
201    let meta id = C.AImplicit (id, None) in
202    let map v (cl, b) =
203       if I.overlaps synth cl
204          then if b then v, v else meta "", v
205          else meta "", meta ""
206    in
207    let rec rev a = function
208       | []       -> a
209       | hd :: tl -> 
210          if snd hd <> meta "" then incr exp;
211          rev (snd hd :: a) tl 
212    in
213    let rec aux = function
214       | []       -> []
215       | hd :: tl -> 
216          if fst hd = meta "" then aux tl else rev [] (hd :: tl)
217    in
218    let args = T.list_rev_map2 map tl classes in
219    let args = aux args in
220    let part = !exp < List.length tl in
221    if args = [] then part, hd, qs else part, C.AAppl ("", hd :: args), qs
222
223 let mk_convert st ?name sty ety note =
224    let ppterm t = 
225       let a = ref "" in Ut.pp_term (fun s -> a := !a ^ s) [] st.context t; !a
226    in 
227    let e = Cn.hole "" in
228    let csty, cety = H.cic sty, H.cic ety in
229    let note = 
230       if !debug then
231          let sname = match name with None -> "" | Some (id, _) -> id in
232          Printf.sprintf "%s: %s\nSINTH: %s\nEXP: %s"
233             note sname (ppterm csty) (ppterm cety)
234       else ""
235    in
236    if H.alpha ~flatten:true st.context csty cety then [T.Note note] else 
237    let sty, ety = H.acic_bc st.context sty, H.acic_bc st.context ety in
238    match name with
239       | None         -> [T.Change (sty, ety, None, e, note)]
240       | Some (id, i) -> 
241          begin match get_entry st id with
242             | C.Def _  -> 
243                [T.Change (ety, sty, Some (id, Some id), e, note);
244                 T.ClearBody (id, "")
245                ]
246             | C.Decl _ -> 
247                [T.Change (ety, sty, Some (id, Some id), e, note)] 
248          end
249
250 let convert st ?name v = 
251    match get_inner_types st v with
252       | None            -> 
253          if !debug then [T.Note "NORMAL: NO INNER TYPES"] else []
254       | Some (sty, ety) -> mk_convert st ?name sty ety "NORMAL"
255           
256 let get_intro = function 
257    | C.Anonymous -> None
258    | C.Name s    -> Some s
259
260 let mk_preamble st what script = match script with
261    | step :: script when is_reflexivity st step ->
262       convert st what @ T.Reflexivity (T.note_of_step step) :: script
263    | T.Exact _ :: _ -> script
264    | _              -> convert st what @ script   
265
266 let mk_arg st = function
267    | C.ARel (_, _, i, name) as what -> convert st ~name:(name, i) what
268    | _                              -> []
269
270 let mk_fwd_rewrite st dtext name tl direction v t ity ety =
271    let compare premise = function
272       | None   -> true
273       | Some s -> s = premise
274    in
275    assert (List.length tl = 6);
276    let what, where, predicate = List.nth tl 5, List.nth tl 3, List.nth tl 2 in
277    let e = Cn.mk_pattern 1 ety predicate in
278    if (Cn.does_not_occur e) then st, [] else 
279    match where with
280       | C.ARel (_, _, i, premise) as w ->
281          let script name =
282             let where = Some (premise, name) in
283             let script = mk_arg st what @ mk_arg st w in
284             T.Rewrite (direction, what, where, e, dtext) :: script
285          in
286          if DTI.does_not_occur (succ i) (H.cic t) || compare premise name then
287             {st with context = Cn.clear st.context premise}, script name
288          else begin
289             assert (Ut.is_sober st.context (H.cic ity));
290             let ity = H.acic_bc st.context ity in
291             let br1 = [T.Id ""] in
292             let br2 = List.rev (T.Exact (w, "assumption") :: script None) in
293             let text = "non-linear rewrite" in
294             st, [T.Branch ([br2; br1], ""); T.Cut (name, ity, text)]
295          end
296       | _                         -> assert false
297
298 let mk_rewrite st dtext where qs tl direction t ity = 
299    let ppterm t = 
300       let a = ref "" in Ut.pp_term (fun s -> a := !a ^ s) [] st.context t; !a
301    in 
302    assert (List.length tl = 5);
303    let pred, sx, dx = List.nth tl 2, List.nth tl 1, List.nth tl 4 in
304    let dtext = if !debug then dtext ^ ppterm (H.cic pred) else dtext in
305    let e = Cn.mk_pattern 1 ity pred in
306    let script = [T.Branch (qs, "")] in
307    if Cn.does_not_occur e then script else
308    if are_convertible st pred sx dx then 
309       let dtext = "convertible rewrite" ^ dtext in
310       let ity, ety, e = Cn.beta sx pred, Cn.beta dx pred, Cn.hole "" in
311       let city, cety = H.cic ity, H.cic ety in
312       if H.alpha ~flatten:true st.context city cety then script else
313       T.Change (ity, ety, None, e, dtext) :: script
314    else
315    T.Rewrite (direction, where, None, e, dtext) :: script
316
317 let rec proc_lambda st what name v t =
318    let dtext = if !debug then CicPp.ppcontext st.context else "" in
319    let name = match name with
320       | C.Anonymous -> H.mk_fresh_name true st.context anonymous_premise
321       | name        -> name
322    in
323    let entry = Some (name, C.Decl (H.cic v)) in
324    let intro = get_intro name in
325    let script = proc_proof (add st entry) t in
326    let script = T.Intros (Some 1, [intro], dtext) :: script in
327    mk_preamble st what script
328
329 and proc_letin st what name v w t =
330    let intro = get_intro name in
331    let proceed, dtext = test_depth st in
332    let script = if proceed then 
333       let st, hyp, rqv = match get_inner_types st what, get_inner_types st v with
334          | Some (C.ALetIn (_, _, iv, iw, _), _), _ when
335             H.alpha ~flatten:true st.context (H.cic v) (H.cic iv) &&
336             H.alpha ~flatten:true st.context (H.cic w) (H.cic iw)
337                                                    ->
338             st, C.Def (H.cic v, H.cic w), [T.Intros (Some 1, [intro], dtext)]
339          | _, Some (ity, ety)                      ->
340             let st, rqv = match v with
341                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_right st hd tl ->
342                   mk_fwd_rewrite st dtext intro tl true v t ity ety
343                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_left st hd tl  ->
344                   mk_fwd_rewrite st dtext intro tl false v t ity ety
345                | v                                                        ->
346                   assert (Ut.is_sober st.context (H.cic ety));
347                   let ety = H.acic_bc st.context ety in
348                   let qs = [proc_proof (next st) v; [T.Id ""]] in
349                   st, [T.Branch (qs, ""); T.Cut (intro, ety, dtext)]
350             in
351             st, C.Decl (H.cic ity), rqv
352          | _, None                 ->
353             st, C.Def (H.cic v, H.cic w), [T.LetIn (intro, v, dtext)]
354       in
355       let entry = Some (name, hyp) in
356       let qt = proc_proof (next (add st entry)) t in
357       List.rev_append rqv qt      
358    else
359       [T.Exact (what, dtext)]
360    in
361    mk_preamble st what script
362
363 and proc_rel st what = 
364    let _, dtext = test_depth st in
365    let text = "assumption" in
366    let script = [T.Exact (what, dtext ^ text)] in 
367    mk_preamble st what script
368
369 and proc_mutconstruct st what = 
370    let _, dtext = test_depth st in
371    let script = [T.Exact (what, dtext)] in 
372    mk_preamble st what script
373
374 and proc_const st what = 
375    let _, dtext = test_depth st in
376    let script = [T.Exact (what, dtext)] in 
377    mk_preamble st what script
378
379 and proc_appl st what hd tl =
380    let proceed, dtext = test_depth st in
381    let script = if proceed then
382       let ty = match get_inner_types st hd with
383          | Some (ity, _) -> H.cic ity 
384          | None          -> get_type "TC2" st hd 
385       in
386       let classes, rc = Cl.classify st.context ty in
387       let goal_arity, goal = match get_inner_types st what with
388          | None          -> 0, None
389          | Some (ity, _) -> 
390            snd (PEH.split_with_whd (st.context, H.cic ity)), Some (H.cic ity)
391       in
392       let parsno, argsno = List.length classes, List.length tl in
393       let decurry = parsno - argsno in
394       let diff = goal_arity - decurry in
395       if diff < 0 then 
396          let text = Printf.sprintf "partial application: %i" diff in
397          prerr_endline ("Procedural 2: " ^ text);
398          [T.Exact (what, dtext ^ text)]
399       else
400       let classes = Cl.adjust st.context tl ?goal classes in
401       let rec mk_synth a n =
402          if n < 0 then a else mk_synth (I.S.add n a) (pred n)
403       in
404       let synth = mk_synth I.S.empty decurry in
405       let text = if !debug
406          then Printf.sprintf "%u %s" parsno (Cl.to_string synth (classes, rc))
407          else ""
408       in
409       let script = List.rev (mk_arg st hd) in
410       let tactic b t n = if b then T.Apply (t, n) else T.Exact (t, n) in
411       match rc with
412          | Some (i, j, uri, tyno) when decurry = 0 ->
413             let classes2, tl2, _, where = split2_last classes tl in
414             let script2 = List.rev (mk_arg st where) @ script in
415             let synth2 = I.S.add 1 synth in
416             let names = H.get_ind_names uri tyno in
417             let qs = proc_bkd_proofs (next st) synth2 names classes2 tl2 in
418             let ity = match get_inner_types st what with
419                 | Some (ity, _) -> ity 
420                 | None          -> 
421                    Cn.fake_annotate "" st.context (get_type "TC3" st what)
422             in
423             if List.length qs <> List.length names then
424                let qs = proc_bkd_proofs (next st) synth [] classes tl in
425                let b, hd, qs = mk_exp_args hd tl classes synth qs in
426                script @ [tactic b hd (dtext ^ text); T.Branch (qs, "")]
427             else if is_rewrite_right st hd then 
428                script2 @ mk_rewrite st dtext where qs tl2 false what ity
429             else if is_rewrite_left st hd then 
430                script2 @ mk_rewrite st dtext where qs tl2 true what ity
431             else
432                let predicate = List.nth tl2 (parsno - i) in
433                let e = Cn.mk_pattern j ity predicate in
434                let using = Some hd in
435                script2 @ 
436                [T.Elim (where, using, e, dtext ^ text); T.Branch (qs, "")]
437          | _                                       ->
438             let names = get_sub_names hd tl in
439             let qs = proc_bkd_proofs (next st) synth names classes tl in
440             let b, hd, qs = mk_exp_args hd tl classes synth qs in
441             script @ [tactic b hd (dtext ^ text); T.Branch (qs, "")]
442    else
443       [T.Exact (what, dtext)]
444    in
445    mk_preamble st what script
446
447 and proc_case st what uri tyno u v ts =
448    let proceed, dtext = test_depth st in
449    let script = if proceed then
450       let synth, classes = I.S.empty, Cl.make ts in
451       let names = H.get_ind_names uri tyno in
452       let qs = proc_bkd_proofs (next st) synth names classes ts in
453       let lpsno, _ = H.get_ind_type uri tyno in
454       let ps, _ = H.get_ind_parameters st.context (H.cic v) in
455       let _, rps = HEL.split_nth lpsno ps in
456       let rpsno = List.length rps in 
457       let ity = match get_inner_types st what with
458          | Some (ity, _) -> ity 
459          | None          -> 
460             Cn.fake_annotate "" st.context (get_type "TC4" st what)
461       in
462       let e = Cn.mk_pattern rpsno ity u in
463       let text = "" in
464       let script = List.rev (mk_arg st v) in
465       script @ [T.Cases (v, e, dtext ^ text); T.Branch (qs, "")]   
466    else
467       [T.Exact (what, dtext)]
468    in
469    mk_preamble st what script
470
471 and proc_other st what =
472    let _, dtext = test_depth st in
473    let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head what) in
474    let script = [T.Exact (what, dtext ^ text)] in 
475    mk_preamble st what script
476
477 and proc_proof st t = 
478    let f st =
479 (*      
480       let xtypes, note = match get_inner_types st t with
481          | Some (it, et) -> Some (H.cic it, H.cic et), 
482           (Printf.sprintf "\nInferred: %s\nExpected: %s"
483           (Pp.ppterm (H.cic it)) (Pp.ppterm (H.cic et))) 
484          | None          -> None, "\nNo types"
485       in    
486       let context, clears = Cn.get_clears st.context (H.cic t) xtypes in
487       {st with context = context}
488 *)
489       st
490    in
491    match t with
492       | C.ALambda (_, name, w, t) as what        -> proc_lambda (f st) what name w t
493       | C.ALetIn (_, name, v, w, t) as what      -> proc_letin (f st) what name v w t
494       | C.ARel _ as what                         -> proc_rel (f st) what
495       | C.AMutConstruct _ as what                -> proc_mutconstruct (f st) what
496       | C.AConst _ as what                       -> proc_const (f st) what
497       | C.AAppl (_, hd :: tl) as what            -> proc_appl (f st) what hd tl
498 (* FG: we deactivate the tactic "cases" because it does not work properly
499       | C.AMutCase (_, uri, i, u, v, ts) as what -> proc_case (f st) what uri i u v ts
500 *)      
501       | what                                     -> proc_other (f st) what
502
503 and proc_bkd_proofs st synth names classes ts =
504 try 
505    let get_names b = ref (names, if b then push st else st) in
506    let get_note f b names = 
507       match !names with 
508          | [], st       -> f st
509          | "" :: tl, st -> names := tl, st; f st
510          | hd :: tl, st -> 
511             let note = case st hd in
512             names := tl, inc st; 
513             if b then T.Note note :: f st else f st
514    in
515    let _, dtext = test_depth st in   
516    let aux (inv, _) v =
517       if I.overlaps synth inv then None else
518       if I.S.is_empty inv then Some (get_note (fun st -> proc_proof st v)) else
519       Some (get_note (fun _ -> [T.Exact (v, dtext ^ "dependent")]))
520    in   
521    let ps = T.list_map2_filter aux classes ts in
522    let b = List.length ps > 1 in
523    let names = get_names b in
524    List.rev_map (fun f -> f b names) ps
525
526 with Invalid_argument s -> failwith ("A2P.proc_bkd_proofs: " ^ s)
527
528 (* initialization ***********************************************************)
529
530 let init ~ids_to_inner_sorts ~ids_to_inner_types params context =
531    let depth_map x y = match x, y with
532       | None, G.IPDepth depth -> Some depth
533       | _                     -> x
534    in
535    {
536       sorts       = ids_to_inner_sorts;
537       types       = ids_to_inner_types;
538       params      = params;
539       max_depth   = List.fold_left depth_map None params;
540       depth       = 0;
541       defaults    = not (List.mem G.IPNoDefaults params);
542       context     = context;
543       case        = []
544    }