]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/acic_procedural/procedural2.ml
Preparing for 0.5.9 release.
[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    cr       : bool;
58    context  : C.context;
59    case     : int list
60 }
61
62 let debug = ref false
63
64 (* helpers ******************************************************************)
65
66 let split2_last l1 l2 =
67 try
68    let n = pred (List.length l1) in
69    let before1, after1 = HEL.split_nth n l1 in
70    let before2, after2 = HEL.split_nth n l2 in
71    before1, before2, List.hd after1, List.hd after2
72 with Invalid_argument _ -> failwith "A2P.split2_last"
73    
74 let string_of_head = function
75    | C.ASort _         -> "sort"
76    | C.AConst _        -> "const"
77    | C.AMutInd _       -> "mutind"
78    | C.AMutConstruct _ -> "mutconstruct"
79    | C.AVar _          -> "var"
80    | C.ARel _          -> "rel"
81    | C.AProd _         -> "prod"
82    | C.ALambda _       -> "lambda"
83    | C.ALetIn _        -> "letin"
84    | C.AFix _          -> "fix"
85    | C.ACoFix _        -> "cofix"
86    | C.AAppl _         -> "appl"
87    | C.ACast _         -> "cast"
88    | C.AMutCase _      -> "mutcase"
89    | C.AMeta _         -> "meta"
90    | C.AImplicit _     -> "implict"
91
92 let next st = {st with depth = succ st.depth}
93
94 let add st entry = {st with context = entry :: st.context}
95
96 let push st = {st with case = 1 :: st.case}
97
98 let inc st =
99    {st with case = match st.case with 
100       | []       -> []
101       | hd :: tl -> succ hd :: tl
102    }
103
104 let case st str =
105    let case = String.concat "." (List.rev_map string_of_int st.case) in
106    Printf.sprintf "case %s: %s" case str
107
108 let test_depth st =
109 try   
110    let msg = Printf.sprintf "Depth %u: " st.depth in
111    match st.max_depth with
112       | None   -> true, "" 
113       | Some d -> if st.depth < d then true, msg else false, "DEPTH EXCEDED: "
114 with Invalid_argument _ -> failwith "A2P.test_depth"
115
116 let is_rewrite_right st = function
117    | C.AConst (_, uri, []) -> st.defaults && Obj.is_eq_ind_r_URI uri
118    | _                     -> false
119
120 let is_rewrite_left st = function
121    | C.AConst (_, uri, []) -> st.defaults && Obj.is_eq_ind_URI uri
122    | _                     -> false
123
124 let is_fwd_rewrite_right st hd tl =
125    if is_rewrite_right st hd then match List.nth tl 3 with
126       | C.ARel _ -> true
127       | _        -> false
128    else false
129
130 let is_fwd_rewrite_left st hd tl =
131    if is_rewrite_left st hd then match List.nth tl 3 with
132       | C.ARel _ -> true
133       | _        -> false
134    else false
135
136 let get_inner_types st v =
137 try
138    let id = Ut.id_of_annterm v in
139    try match Hashtbl.find st.types id with
140       | {A.annsynthesized = ity; A.annexpected = Some ety} -> Some (ity, ety)
141       | {A.annsynthesized = ity; A.annexpected = None}     -> Some (ity, ity)
142    with Not_found -> None
143 with Invalid_argument _ -> failwith "P2.get_inner_types"
144
145 let get_entry st id =
146    let rec aux = function
147       | []                                        -> assert false
148       | Some (C.Name name, e) :: _ when name = id -> e
149       | _ :: tl                                   -> aux tl
150    in
151    aux st.context
152
153 let string_of_atomic = function
154    | C.ARel (_, _, _, s)               -> s
155    | C.AVar (_, uri, _)                -> H.name_of_uri uri None None
156    | C.AConst (_, uri, _)              -> H.name_of_uri uri None None
157    | C.AMutInd (_, uri, i, _)          -> H.name_of_uri uri (Some i) None
158    | C.AMutConstruct (_, uri, i, j, _) -> H.name_of_uri uri (Some i) (Some j)
159    | _                                 -> ""
160
161 let get_sub_names head l =
162    let s = string_of_atomic head in
163    if s = "" then [] else
164    let map (names, i) _ = 
165       let name = Printf.sprintf "%s_%u" s i in name :: names, succ i
166    in
167    let names, _ = List.fold_left map ([], 1) l in 
168    List.rev names
169
170 let get_type msg st t = H.get_type msg st.context (H.cic t) 
171
172 let get_uri_of_head = function
173    | C.AConst (_, u, _)                                 ->
174       Some (u, 0, 0, 0)
175    | C.AAppl (_, C.AConst (_, u, _) :: vs)              ->
176       Some (u, 0, 0, List.length vs)
177    | C.AMutInd (_, u, i, _)                             ->
178       Some (u, succ i, 0, 0)
179    | C.AAppl (_, C.AMutInd (_, u, i, _) :: vs)          ->
180       Some (u, succ i, 0, List.length vs)
181    | C.AMutConstruct (_, u, i, j, _)                    ->
182       Some (u, succ i, j, 0)
183    | C.AAppl (_, C.AMutConstruct (_, u, i, j, _) :: vs) ->
184       Some (u, succ i, j, List.length vs)
185    | _                                                  ->
186       None
187
188 let get_uri_of_apply = function
189    | T.Exact (t, _)
190    | T.Apply (t, _) -> get_uri_of_head t
191    | _              -> None
192
193 let is_reflexivity st step =
194    match get_uri_of_apply step with
195       | None                -> false
196       | Some (uri, i, j, n) ->
197          st.defaults && Obj.is_eq_URI uri && i = 1 && j = 1 && n = 0
198
199 let is_ho_reflexivity st step =
200    match get_uri_of_apply step with
201       | None                -> false
202       | Some (uri, i, j, n) ->
203          st.defaults && Obj.is_eq_URI uri && i = 1 && j = 1 && n > 0
204
205 let are_convertible st pred sx dx =
206    let pred, sx, dx = H.cic pred, H.cic sx, H.cic dx in
207    let sx, dx = C.Appl [pred; sx], C.Appl [pred; dx] in
208    fst (R.are_convertible st.context sx dx Un.default_ugraph)
209
210 (* proof construction *******************************************************)
211
212 let anonymous_premise = C.Name "UNNAMED"
213
214 let mk_lapply_args hd tl classes = 
215    let map _ = Cn.meta "" in
216    let args = List.rev_map map tl in
217    if args = [] then hd else C.AAppl ("", hd :: args)
218
219 let mk_apply_args hd tl classes synth qs =
220    let exp = ref 0 in
221    let map v (cl, b) =
222       if I.overlaps synth cl
223          then if b then v, v else Cn.meta "", v
224          else Cn.meta "", Cn.meta ""
225    in
226    let rec rev a = function
227       | []       -> a
228       | hd :: tl -> 
229          if snd hd <> Cn.meta "" then incr exp;
230          rev (snd hd :: a) tl 
231    in
232    let rec aux = function
233       | []       -> []
234       | hd :: tl -> 
235          if fst hd = Cn.meta "" then aux tl else rev [] (hd :: tl)
236    in
237    let args = T.list_rev_map2 map tl classes in
238    let args = aux args in
239    let part = !exp < List.length tl in
240    if args = [] then part, hd, qs else part, C.AAppl ("", hd :: args), qs
241
242 let mk_convert st ?name sty ety note =
243    let ppterm t = 
244       let a = ref "" in Ut.pp_term (fun s -> a := !a ^ s) [] st.context t; !a
245    in 
246    let e = Cn.hole "" in
247    let csty, cety = H.cic sty, H.cic ety in
248    let note = 
249       if !debug then
250          let sname = match name with None -> "" | Some (id, _) -> id in
251          Printf.sprintf "%s: %s\nSINTH: %s\nEXP: %s"
252             note sname (ppterm csty) (ppterm cety)
253       else ""
254    in
255    if H.alpha ~flatten:true st.context csty cety then [T.Note note] else 
256    let sty, ety = H.acic_bc st.context sty, H.acic_bc st.context ety in
257    match name with
258       | None         -> [T.Change (sty, ety, None, e, note)]
259       | Some (id, i) -> 
260          begin match get_entry st id with
261             | C.Def _  -> 
262                [T.Change (ety, sty, Some (id, Some id), e, note);
263                 T.ClearBody (id, "")
264                ]
265             | C.Decl _ -> 
266                [T.Change (ety, sty, Some (id, Some id), e, note)] 
267          end
268
269 let convert st ?name v = 
270    match get_inner_types st v with
271       | None            -> 
272          if !debug then [T.Note "NORMAL: NO INNER TYPES"] else []
273       | Some (sty, ety) -> mk_convert st ?name sty ety "NORMAL"
274           
275 let get_intro = function 
276    | C.Anonymous -> None
277    | C.Name s    -> Some s
278
279 let mk_preamble st what script = match script with
280    | step :: script when is_reflexivity st step ->
281       T.Reflexivity (T.note_of_step step) :: script
282    | step :: script when is_ho_reflexivity st step ->
283       convert st what @ T.Reflexivity (T.note_of_step step) :: script
284    | T.Exact _ :: _ -> script
285    | _              -> convert st what @ script   
286
287 let mk_arg st = function
288    | C.ARel (_, _, i, name) as what -> convert st ~name:(name, i) what
289    | _                              -> []
290
291 let mk_fwd_rewrite st dtext name tl direction v t ity ety =
292    let compare premise = function
293       | None   -> true
294       | Some s -> s = premise
295    in
296    assert (List.length tl = 6);
297    let what, where, predicate = List.nth tl 5, List.nth tl 3, List.nth tl 2 in
298    let e = Cn.mk_pattern 1 ety predicate in
299    if (Cn.does_not_occur e) then st, [] else 
300    match where with
301       | C.ARel (_, _, i, premise) as w ->
302          let script name =
303             let where = Some (premise, name) in
304             let script = mk_arg st what @ mk_arg st w in
305             T.Rewrite (direction, what, where, e, dtext) :: script
306          in
307          if DTI.does_not_occur (succ i) (H.cic t) || compare premise name then
308             {st with context = Cn.clear st.context premise}, script name
309          else begin
310             assert (Ut.is_sober st.context (H.cic ity));
311             let ity = H.acic_bc st.context ity in
312             let br1 = [T.Id ""] in
313             let br2 = List.rev (T.Exact (w, "assumption") :: script None) in
314             let text = "non-linear rewrite" in
315             st, [T.Branch ([br2; br1], ""); T.Cut (name, ity, text)]
316          end
317       | _                         -> assert false
318
319 let mk_rewrite st dtext where qs tl direction t ity = 
320    let ppterm t = 
321       let a = ref "" in Ut.pp_term (fun s -> a := !a ^ s) [] st.context t; !a
322    in 
323    assert (List.length tl = 5);
324    let pred, sx, dx = List.nth tl 2, List.nth tl 1, List.nth tl 4 in
325    let dtext = if !debug then dtext ^ ppterm (H.cic pred) else dtext in
326    let e = Cn.mk_pattern 1 ity pred in
327    let script = [T.Branch (qs, "")] in
328    if Cn.does_not_occur e then script else
329    if st.cr && are_convertible st pred sx dx then 
330       let dtext = "convertible rewrite" ^ dtext in
331       let ity, ety, e = Cn.beta sx pred, Cn.beta dx pred, Cn.hole "" in
332       let city, cety = H.cic ity, H.cic ety in
333       if H.alpha ~flatten:true st.context city cety then script else
334       T.Change (ity, ety, None, e, dtext) :: script
335    else
336    T.Rewrite (direction, where, None, e, dtext) :: script
337
338 let rec proc_lambda st what name v t =
339    let dtext = if !debug then CicPp.ppcontext st.context else "" in
340    let name = match name with
341       | C.Anonymous -> H.mk_fresh_name true st.context anonymous_premise
342       | name        -> name
343    in
344    let entry = Some (name, C.Decl (H.cic v)) in
345    let intro = get_intro name in
346    let script = proc_proof (add st entry) t in
347    let script = T.Intros (Some 1, [intro], dtext) :: script in
348    mk_preamble st what script
349
350 and proc_letin st what name v w t =
351    let intro = get_intro name in
352    let proceed, dtext = test_depth st in
353    let script = if proceed then 
354       let st, hyp, rqv = match get_inner_types st what, get_inner_types st v with
355          | Some (C.ALetIn (_, _, iv, iw, _), _), _ when
356             H.alpha ~flatten:true st.context (H.cic v) (H.cic iv) &&
357             H.alpha ~flatten:true st.context (H.cic w) (H.cic iw)
358                                                    ->
359             st, C.Def (H.cic v, H.cic w), [T.Intros (Some 1, [intro], dtext)]
360          | _, Some (ity, ety)                      ->
361             let st, rqv = match v with
362                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_right st hd tl ->
363                   mk_fwd_rewrite st dtext intro tl true v t ity ety
364                | C.AAppl (_, hd :: tl) when is_fwd_rewrite_left st hd tl  ->
365                   mk_fwd_rewrite st dtext intro tl false v t ity ety
366                | C.AAppl (_, hd :: tl)                                    ->
367                   let ty = match get_inner_types st hd with
368                      | Some (ity, _) -> H.cic ity 
369                      | None          -> get_type "TC3" st hd 
370                   in
371                   let classes, _ = Cl.classify st.context ty in
372                   let parsno, argsno = List.length classes, List.length tl in
373                   let decurry = parsno - argsno in
374                   if decurry <> 0 then begin              
375 (* FG: we fall back in the cut case *)               
376                      assert (Ut.is_sober st.context (H.cic ety));
377                      let ety = H.acic_bc st.context ety in
378                      let qs = [proc_proof (next st) v; [T.Id ""]] in
379                      st, [T.Branch (qs, ""); T.Cut (intro, ety, dtext)]
380                   end else
381                   let names, synth = get_sub_names hd tl, I.S.empty in
382                   let qs = proc_bkd_proofs (next st) synth names classes tl in
383                   let hd = mk_lapply_args hd tl classes in
384                   let qs = [T.Id ""] :: qs in
385                   st, [T.Branch (qs, ""); T.LApply (intro, hd, dtext)]
386                | v                                                        ->
387                   assert (Ut.is_sober st.context (H.cic ety));
388                   let ety = H.acic_bc st.context ety in
389                   let qs = [proc_proof (next st) v; [T.Id ""]] in
390                   st, [T.Branch (qs, ""); T.Cut (intro, ety, dtext)]
391             in
392             st, C.Decl (H.cic ity), rqv
393          | _, None                 ->
394             st, C.Def (H.cic v, H.cic w), [T.LetIn (intro, v, dtext)]
395       in
396       let entry = Some (name, hyp) in
397       let qt = proc_proof (next (add st entry)) t in
398       List.rev_append rqv qt      
399    else
400       [T.Exact (what, dtext)]
401    in
402    mk_preamble st what script
403
404 and proc_rel st what = 
405    let _, dtext = test_depth st in
406    let text = "assumption" in
407    let script = [T.Exact (what, dtext ^ text)] in 
408    mk_preamble st what script
409
410 and proc_mutconstruct st what = 
411    let _, dtext = test_depth st in
412    let script = [T.Exact (what, dtext)] in 
413    mk_preamble st what script
414
415 and proc_const st what = 
416    let _, dtext = test_depth st in
417    let script = [T.Exact (what, dtext)] in 
418    mk_preamble st what script
419
420 and proc_appl st what hd tl =
421    let proceed, dtext = test_depth st in
422    let script = if proceed then
423       let ty = match get_inner_types st hd with
424          | Some (ity, _) -> H.cic ity 
425          | None          -> get_type "TC2" st hd 
426       in
427       let classes, rc = Cl.classify st.context ty in
428       let goal_arity, goal = match get_inner_types st what with
429          | None          -> 0, None
430          | Some (ity, _) -> 
431            snd (PEH.split_with_whd (st.context, H.cic ity)), Some (H.cic ity)
432       in
433       let parsno, argsno = List.length classes, List.length tl in
434       let decurry = parsno - argsno in
435       let diff = goal_arity - decurry in
436       if diff < 0 then 
437          let text = Printf.sprintf "partial application: %i" diff in
438          prerr_endline ("Procedural 2: " ^ text);
439          [T.Exact (what, dtext ^ text)]
440       else
441       let classes = Cl.adjust st.context tl ?goal classes in
442       let rec mk_synth a n =
443          if n < 0 then a else mk_synth (I.S.add n a) (pred n)
444       in
445       let synth = mk_synth I.S.empty decurry in
446       let text = if !debug
447          then Printf.sprintf "%u %s" parsno (Cl.to_string synth (classes, rc))
448          else ""
449       in
450       let script = List.rev (mk_arg st hd) in
451       let tactic b t n = if b then T.Apply (t, n) else T.Exact (t, n) in
452       match rc with
453          | Some (i, j, uri, tyno) when decurry = 0 ->
454             let classes2, tl2, _, where = split2_last classes tl in
455             let script2 = List.rev (mk_arg st where) @ script in
456             let synth2 = I.S.add 1 synth in
457             let names = H.get_ind_names uri tyno in
458             let qs = proc_bkd_proofs (next st) synth2 names classes2 tl2 in
459             let ity = match get_inner_types st what with
460                 | Some (ity, _) -> ity 
461                 | None          -> 
462                    Cn.fake_annotate "" st.context (get_type "TC3" st what)
463             in
464             if List.length qs <> List.length names then
465                let qs = proc_bkd_proofs (next st) synth [] classes tl in
466                let b, hd, qs = mk_apply_args hd tl classes synth qs in
467                script @ [tactic b hd (dtext ^ text); T.Branch (qs, "")]
468             else if is_rewrite_right st hd then 
469                script2 @ mk_rewrite st dtext where qs tl2 false what ity
470             else if is_rewrite_left st hd then 
471                script2 @ mk_rewrite st dtext where qs tl2 true what ity
472             else
473                let predicate = List.nth tl2 (parsno - i) in
474                let e = Cn.mk_pattern j ity predicate in
475                let using = Some hd in
476                script2 @ 
477                [T.Elim (where, using, e, dtext ^ text); T.Branch (qs, "")]
478          | _                                       ->
479             let names = get_sub_names hd tl in
480             let qs = proc_bkd_proofs (next st) synth names classes tl in
481             let b, hd, qs = mk_apply_args hd tl classes synth qs in
482             script @ [tactic b hd (dtext ^ text); T.Branch (qs, "")]
483    else
484       [T.Exact (what, dtext)]
485    in
486    mk_preamble st what script
487
488 and proc_case st what uri tyno u v ts =
489    let proceed, dtext = test_depth st in
490    let script = if proceed then
491       let synth, classes = I.S.empty, Cl.make ts in
492       let names = H.get_ind_names uri tyno in
493       let qs = proc_bkd_proofs (next st) synth names classes ts in
494       let lpsno, _ = H.get_ind_type uri tyno in
495       let ps, _ = H.get_ind_parameters st.context (H.cic v) in
496       let _, rps = HEL.split_nth lpsno ps in
497       let rpsno = List.length rps in 
498       let ity = match get_inner_types st what with
499          | Some (ity, _) -> ity 
500          | None          -> 
501             Cn.fake_annotate "" st.context (get_type "TC4" st what)
502       in
503       let e = Cn.mk_pattern rpsno ity u in
504       let text = "" in
505       let script = List.rev (mk_arg st v) in
506       script @ [T.Cases (v, e, dtext ^ text); T.Branch (qs, "")]   
507    else
508       [T.Exact (what, dtext)]
509    in
510    mk_preamble st what script
511
512 and proc_other st what =
513    let _, dtext = test_depth st in
514    let text = Printf.sprintf "%s: %s" "UNEXPANDED" (string_of_head what) in
515    let script = [T.Exact (what, dtext ^ text)] in 
516    mk_preamble st what script
517
518 and proc_proof st t = 
519    let f st =
520 (*      
521       let xtypes, note = match get_inner_types st t with
522          | Some (it, et) -> Some (H.cic it, H.cic et), 
523           (Printf.sprintf "\nInferred: %s\nExpected: %s"
524           (Pp.ppterm (H.cic it)) (Pp.ppterm (H.cic et))) 
525          | None          -> None, "\nNo types"
526       in    
527       let context, clears = Cn.get_clears st.context (H.cic t) xtypes in
528       {st with context = context}
529 *)
530       st
531    in
532    match t with
533       | C.ALambda (_, name, w, t) as what        -> proc_lambda (f st) what name w t
534       | C.ALetIn (_, name, v, w, t) as what      -> proc_letin (f st) what name v w t
535       | C.ARel _ as what                         -> proc_rel (f st) what
536       | C.AMutConstruct _ as what                -> proc_mutconstruct (f st) what
537       | C.AConst _ as what                       -> proc_const (f st) what
538       | C.AAppl (_, hd :: tl) as what            -> proc_appl (f st) what hd tl
539 (* FG: we deactivate the tactic "cases" because it does not work properly
540       | C.AMutCase (_, uri, i, u, v, ts) as what -> proc_case (f st) what uri i u v ts
541 *)      
542       | what                                     -> proc_other (f st) what
543
544 and proc_bkd_proofs st synth names classes ts =
545 try 
546    let get_names b = ref (names, if b then push st else st) in
547    let get_note f b names = 
548       match !names with 
549          | [], st       -> f st
550          | "" :: tl, st -> names := tl, st; f st
551          | hd :: tl, st -> 
552             let note = case st hd in
553             names := tl, inc st; 
554             if b then T.Note note :: f st else f st
555    in
556    let _, dtext = test_depth st in   
557    let aux (inv, _) v =
558       if I.overlaps synth inv then None else
559       if I.S.is_empty inv then Some (get_note (fun st -> proc_proof st v)) else
560       Some (get_note (fun _ -> [T.Exact (v, dtext ^ "dependent")]))
561    in   
562    let ps = T.list_map2_filter aux classes ts in
563    let b = List.length ps > 1 in
564    let names = get_names b in
565    List.rev_map (fun f -> f b names) ps
566
567 with Invalid_argument s -> failwith ("A2P.proc_bkd_proofs: " ^ s)
568
569 (* initialization ***********************************************************)
570
571 let init ~ids_to_inner_sorts ~ids_to_inner_types params context =
572    let depth_map x y = match x, y with
573       | None, G.IPDepth depth -> Some depth
574       | _                     -> x
575    in
576    {
577       sorts       = ids_to_inner_sorts;
578       types       = ids_to_inner_types;
579       params      = params;
580       max_depth   = List.fold_left depth_map None params;
581       depth       = 0;
582       defaults    = not (List.mem G.IPNoDefaults params);
583       cr          = List.mem G.IPCR params;
584       context     = context;
585       case        = []
586    }