]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_tactics/nTactics.ml
better exception handling
[helm.git] / helm / software / components / ng_tactics / nTactics.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id: nCic.ml 9058 2008-10-13 17:42:30Z tassi $ *)
13
14 open Printf
15
16 let debug = false
17 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
18
19 open Continuationals.Stack
20 open NTacStatus
21 module Ast = CicNotationPt
22
23 let id_tac status = status ;;
24 let print_tac print_status message status = 
25   if print_status then pp_status status;
26   prerr_endline message; 
27   status
28 ;;
29
30 let dot_tac status =
31   let gstatus = 
32     match status#stack with
33     | [] -> assert false
34     | ([], _, [], _) :: _ as stack ->
35         (* backward compatibility: do-nothing-dot *)
36         stack
37     | (g, t, k, tag) :: s ->
38         match filter_open g, k with
39         | loc :: loc_tl, _ -> 
40              (([ loc ], t, loc_tl @+ k, tag) :: s) 
41         | [], loc :: k ->
42             assert (is_open loc);
43             (([ loc ], t, k, tag) :: s)
44         | _ -> fail (lazy "can't use \".\" here")
45   in
46    status#set_stack gstatus
47 ;;
48
49 let branch_tac status =
50   let gstatus = 
51     match status#stack with
52     | [] -> assert false
53     | (g, t, k, tag) :: s ->
54           match init_pos g with (* TODO *)
55           | [] | [ _ ] -> fail (lazy "too few goals to branch");
56           | loc :: loc_tl ->
57                ([ loc ], [], [], `BranchTag) :: (loc_tl, t, k, tag) :: s
58   in
59    status#set_stack gstatus
60 ;;
61
62 let shift_tac status =
63   let gstatus = 
64     match status#stack with
65     | (g, t, k, `BranchTag) :: (g', t', k', tag) :: s ->
66           (match g' with
67           | [] -> fail (lazy "no more goals to shift")
68           | loc :: loc_tl ->
69                 (([ loc ], t @+ filter_open g @+ k, [],`BranchTag)
70                 :: (loc_tl, t', k', tag) :: s))
71      | _ -> fail (lazy "can't shift goals here")
72   in
73    status#set_stack gstatus
74 ;;
75
76 let pos_tac i_s status =
77   let gstatus = 
78     match status#stack with
79     | [] -> assert false
80     | ([ loc ], t, [],`BranchTag) :: (g', t', k', tag) :: s
81       when is_fresh loc ->
82         let l_js = List.filter (fun (i, _) -> List.mem i i_s) ([loc] @+ g') in
83           ((l_js, t , [],`BranchTag)
84            :: (([ loc ] @+ g') @- l_js, t', k', tag) :: s)
85     | _ -> fail (lazy "can't use relative positioning here")
86   in
87    status#set_stack gstatus
88 ;;
89
90 let wildcard_tac status =
91   let gstatus = 
92     match status#stack with
93     | [] -> assert false
94     | ([ loc ] , t, [], `BranchTag) :: (g', t', k', tag) :: s
95        when is_fresh loc ->
96             (([loc] @+ g', t, [], `BranchTag) :: ([], t', k', tag) :: s)
97     | _ -> fail (lazy "can't use wildcard here")
98   in
99    status#set_stack gstatus
100 ;;
101
102 let merge_tac status =
103   let gstatus = 
104     match status#stack with
105     | [] -> assert false
106     | (g, t, k,`BranchTag) :: (g', t', k', tag) :: s ->
107         ((t @+ filter_open g @+ g' @+ k, t', k', tag) :: s)
108     | _ -> fail (lazy "can't merge goals here")
109   in
110    status#set_stack gstatus
111 ;;
112       
113 let focus_tac gs status =
114   let gstatus = 
115     match status#stack with
116     | [] -> assert false
117     | s -> assert(gs <> []);
118           let stack_locs =
119             let add_l acc _ _ l = if is_open l then l :: acc else acc in
120             fold ~env:add_l ~cont:add_l ~todo:add_l [] s
121           in
122           List.iter
123             (fun g ->
124               if not (List.exists (fun l -> goal_of_loc l = g) stack_locs) then
125                 fail (lazy (sprintf "goal %d not found (or closed)" g)))
126             gs;
127           (zero_pos gs, [], [], `FocusTag) :: deep_close gs s
128   in
129    status#set_stack gstatus
130 ;;
131
132 let unfocus_tac status =
133   let gstatus = 
134     match status#stack with
135     | [] -> assert false
136     | ([], [], [], `FocusTag) :: s -> s
137     | _ -> fail (lazy "can't unfocus, some goals are still open")
138   in
139    status#set_stack gstatus
140 ;;
141
142 let skip_tac status =
143   let gstatus = 
144     match status#stack with
145     | [] -> assert false
146     | (gl, t, k, tag) :: s -> 
147         let gl = List.map switch_of_loc gl in
148         if List.exists (function Open _ -> true | Closed _ -> false) gl then 
149           fail (lazy "cannot skip an open goal")
150         else 
151           ([],t,k,tag) :: s
152   in
153    status#set_stack gstatus
154 ;;
155
156 let block_tac l status =
157   List.fold_left (fun status tac -> tac status) status l
158 ;;
159
160 let compare_statuses ~past ~present =
161  let _,_,past,_,_ = past#obj in 
162  let _,_,present,_,_ = present#obj in 
163  List.map fst (List.filter (fun (i,_) -> not(List.mem_assoc i past)) present),
164  List.map fst (List.filter (fun (i,_) -> not (List.mem_assoc i present)) past)
165 ;;
166
167
168
169 (* Exec and distribute_tac form a retraction pair:
170     1) exec (distribute_tac low_tac) (s,i) = low_tac (s,i)
171     2) tac [s]::G = G1::...::Gn::G' && G' is G with some goals closed =>
172          distribute_tac (exec tac) [s]::G = (G1@...Gn)::G'
173     3) tac G = distribute_tac (exec tac) G if  
174        tac = distribute_tac lowtac
175     4) atomic_tac t === distribute_tac (exec t)
176
177    Note that executing an high tactic on a set of goals may be stronger
178    than executing the same tactic on those goals, but once at a time
179    (e.g. the tactic could perform a global analysis of the set of goals)
180 *)
181
182 let exec tac low_status g =
183   let stack = [ [0,Open g], [], [], `NoTag ] in
184   let status =
185    (new NTacStatus.status low_status#obj stack)#set_estatus
186     (low_status :> NEstatus.status)
187   in
188   let status = tac status in
189    (low_status#set_estatus (status :> NEstatus.status))#set_obj status#obj
190 ;;
191
192 let distribute_tac tac status =
193   match status#stack with
194   | [] -> assert false
195   | (g, t, k, tag) :: s ->
196       debug_print (lazy ("context length " ^string_of_int (List.length g)));
197       let rec aux s go gc =
198         function
199         | [] -> 
200             debug_print (lazy "no selected goals");
201             s, go, gc
202         | loc :: loc_tl ->
203             debug_print (lazy "inner eval tactical");
204             let s, go, gc =
205               if List.exists ((=) (goal_of_loc loc)) gc then
206                 s, go, gc
207               else
208                 match switch_of_loc loc with
209                 | Closed _ -> fail (lazy "cannot apply to a Closed goal")
210                 | Open n -> 
211                    let sn = tac s n in
212                    let go', gc' = compare_statuses ~past:s ~present:sn in
213                    sn, ((go @+ [n]) @- gc') @+ go', gc @+ gc'
214             in
215             aux s go gc loc_tl
216       in
217       let s0 =
218        (new NTacStatus.status status#obj ())#set_estatus
219         (status :> NEstatus.status) in
220       let s0, go0, gc0 = s0, [], [] in
221       let sn, gon, gcn = aux s0 go0 gc0 g in
222       debug_print (lazy ("opened: "
223         ^ String.concat " " (List.map string_of_int gon)));
224       debug_print (lazy ("closed: "
225         ^ String.concat " " (List.map string_of_int gcn)));
226       let stack =
227         (zero_pos gon, t @~- gcn, k @~- gcn, tag) :: deep_close gcn s
228       in
229        ((status#set_stack stack)#set_obj (sn :> lowtac_status)#obj)#set_estatus (sn :> NEstatus.status)
230 ;;
231
232 let atomic_tac htac = distribute_tac (exec htac) ;;
233
234 let try_tac tac status =
235   try
236     tac status
237   with NTacStatus.Error _ ->
238     status
239 ;;
240
241 let first_tac tacl status =
242   let res = 
243    HExtlib.list_findopt
244     (fun tac _ -> try Some (tac status) with NTacStatus.Error _ -> None) tacl
245   in
246     match res with
247       | None -> fail (lazy "No tactics left")
248       | Some x -> x
249 ;;
250
251 let exact_tac t = distribute_tac (fun status goal ->
252  let goalty = get_goalty status goal in
253  let status, t = disambiguate status t (Some goalty) (ctx_of goalty) in
254  instantiate status goal t)
255 ;;
256
257 let assumption_tac status = distribute_tac (fun status goal ->
258   let gty = get_goalty status goal in
259   let context = ctx_of gty in
260   let htac = 
261    first_tac
262     (List.map (fun (name,_) -> exact_tac ("",0,(Ast.Ident (name,None))))
263       context)
264   in
265     exec htac status goal) status
266 ;;
267
268 let find_in_context name context =
269   let rec aux acc = function
270     | [] -> raise Not_found
271     | (hd,_) :: tl when hd = name -> acc
272     | _ :: tl ->  aux (acc + 1) tl
273   in
274   aux 1 context
275 ;;
276
277 let clear_tac names =
278  if names = [] then id_tac
279  else
280   distribute_tac (fun status goal ->
281    let goalty = get_goalty status goal in
282    let js =
283      List.map 
284      (fun name -> 
285         try find_in_context name (ctx_of goalty)
286         with Not_found -> 
287           fail (lazy ("hypothesis '" ^ name ^ "' not found"))) 
288      names
289    in
290    let n,h,metasenv,subst,o = status#obj in
291    let metasenv,subst,_ = NCicMetaSubst.restrict metasenv subst goal js in
292     status#set_obj (n,h,metasenv,subst,o))
293 ;;
294
295 let generalize0_tac args =
296  if args = [] then id_tac
297  else exact_tac ("",0,Ast.Appl (Ast.Implicit :: args))
298 ;;
299
300 let select0_tac ~where:(wanted,hyps,where) ~job  =
301  let found, postprocess = 
302    match job with
303    | `Substexpand argsno -> mk_in_scope, mk_out_scope argsno
304    | `Collect l -> (fun s t -> l := t::!l; mk_in_scope s t), mk_out_scope 1
305    | `ChangeWith f -> f,(fun s t -> s, t)
306  in
307  distribute_tac (fun status goal ->
308    let goalty = get_goalty status goal in
309    let path = 
310      match where with None -> NCic.Implicit `Term | Some where -> where 
311    in
312    let status, newgoalctx =
313       List.fold_right
314        (fun (name,d as entry) (status,ctx) ->
315          try
316           let path = List.assoc name hyps in
317            match d with
318               NCic.Decl ty ->
319                let status,ty =
320                 select_term status ~found ~postprocess (mk_cic_term ctx ty)
321                  (wanted,path) in
322                let status,ty = term_of_cic_term status ty ctx in
323                 status,(name,NCic.Decl ty)::ctx
324             | NCic.Def (bo,ty) ->
325                let status,bo =
326                 select_term status ~found ~postprocess (mk_cic_term ctx bo)
327                  (wanted,path) in
328                let status,bo = term_of_cic_term status bo ctx in
329                 status,(name,NCic.Def (bo,ty))::ctx
330          with
331           Not_found -> status, entry::ctx
332        ) (ctx_of goalty) (status,[])
333    in
334    let status, newgoalty = 
335      select_term status ~found ~postprocess goalty (wanted,path) in
336    (* WARNING: the next two lines simply change the context of newgoalty
337       from the old to the new one. Otherwise mk_meta will do that herself,
338       calling relocate that calls delift. However, newgoalty is now
339       ?[out_scope] and thus the delift would trigger the special unification
340       case, which is wrong now :-( *)
341    let status,newgoalty = term_of_cic_term status newgoalty (ctx_of goalty) in
342    let newgoalty = mk_cic_term newgoalctx newgoalty in
343
344    let status, instance = 
345      mk_meta status newgoalctx (`Decl newgoalty) 
346    in
347    instantiate status goal instance)
348 ;;
349
350 let select_tac ~where ~job move_down_hyps = 
351  let (wanted,hyps,where) = GrafiteDisambiguate.disambiguate_npattern where in
352  let path = 
353   match where with None -> NCic.Implicit `Term | Some where -> where in
354  if not move_down_hyps then
355   select0_tac ~where:(wanted,hyps,Some path) ~job
356  else
357   let path = 
358    List.fold_left
359      (fun path (name,path_name) -> NCic.Prod ("_",path_name,path))
360      path (List.rev hyps)
361   in
362    block_tac [ 
363      generalize0_tac (List.map (fun (name,_) -> Ast.Ident (name,None)) hyps);
364      select0_tac ~where:(wanted,[],Some path) ~job;
365      clear_tac (List.map fst hyps) ]
366 ;;
367
368 let generalize_tac ~where = 
369  let l = ref [] in
370  block_tac [ 
371    select_tac ~where ~job:(`Collect l) true; 
372    print_tac true "ha selezionato?";
373    (fun s -> distribute_tac (fun status goal ->
374       let goalty = get_goalty status goal in
375       let status,canon,rest =
376        match !l with
377           [] ->
378            (match where with
379                _,_,(None,_,_)  -> fail (lazy "No term to generalize")
380              | txt,txtlen,(Some what,_,_) ->
381                 let status, what =
382                  disambiguate status (txt,txtlen,what) None (ctx_of goalty)
383                 in
384                  status,what,[]
385            )
386         | he::tl -> status,he,tl in
387       let status = 
388        List.fold_left 
389          (fun s t -> unify s (ctx_of goalty) canon t) status rest in
390       let status, canon = term_of_cic_term status canon (ctx_of goalty) in
391       instantiate status goal 
392        (mk_cic_term (ctx_of goalty) (NCic.Appl [NCic.Implicit `Term ; canon ]))
393    ) s) ]
394 ;;
395
396 let reduce_tac ~reduction ~where =
397   let change status t = 
398     match reduction with
399     | `Normalize perform_delta ->
400         normalize status
401          ?delta:(if perform_delta then None else Some max_int) (ctx_of t) t
402     | `Whd perform_delta -> 
403         whd status
404          ?delta:(if perform_delta then None else Some max_int) (ctx_of t) t
405   in
406   let where = GrafiteDisambiguate.disambiguate_npattern where in
407   select0_tac ~where ~job:(`ChangeWith change)
408 ;;
409
410 let change_tac ~where ~with_what =
411   let change status t = 
412     let status, ww = disambiguate status with_what  None (ctx_of t) in
413     let status = unify status (ctx_of t) t ww in
414     status, ww
415   in
416   let where = GrafiteDisambiguate.disambiguate_npattern where in
417   select0_tac ~where ~job:(`ChangeWith change)
418 ;;
419
420 let letin_tac ~where ~what:(_,_,w) name =
421  block_tac [
422   select_tac ~where ~job:(`Substexpand 1) true;
423   exact_tac ("",0,Ast.LetIn((Ast.Ident (name,None),None),w,Ast.Implicit));
424  ]
425 ;;
426
427 let apply_tac = exact_tac;;
428
429 type indtyinfo = {
430         rightno: int;
431         leftno: int;
432         consno: int;
433         lefts: NCic.term list;
434         rights: NCic.term list;
435         reference: NReference.reference;
436  }
437 ;;
438
439 let analyze_indty_tac ~what indtyref = distribute_tac (fun status goal ->
440   let goalty = get_goalty status goal in
441   let status, what = disambiguate status what None (ctx_of goalty) in
442   let status, ty_what = typeof status (ctx_of what) what in 
443   let status, (r,consno,lefts,rights) = analyse_indty status ty_what in
444   let leftno = List.length rights in
445   let rightno = List.length rights in
446   indtyref := Some { 
447     rightno = rightno; leftno = leftno; consno = consno;
448     lefts = lefts; rights = rights; reference = r;
449   };
450   exec id_tac status goal)
451 ;;
452
453 let elim_tac ~what ~where = 
454   let indtyinfo = ref None in
455   let sort = ref None in
456   let compute_goal_sort_tac = distribute_tac (fun status goal ->
457     let goalty = get_goalty status goal in
458     let status, goalsort = typeof status (ctx_of goalty) goalty in
459     sort := Some goalsort;
460     exec id_tac status goal)
461   in
462   atomic_tac (block_tac [
463     analyze_indty_tac ~what indtyinfo;    
464     (fun s -> select_tac 
465       ~where ~job:(`Substexpand ((HExtlib.unopt !indtyinfo).rightno+1)) true s);
466     compute_goal_sort_tac;
467     (fun status ->
468      let sort = HExtlib.unopt !sort in
469      let ity = HExtlib.unopt !indtyinfo in
470      let NReference.Ref (uri, _) = ity.reference in
471      let status, sort = term_of_cic_term status sort (ctx_of sort) in
472      let name = NUri.name_of_uri uri ^
473       match sort with
474        | NCic.Sort NCic.Prop -> "_ind"
475        | NCic.Sort _ -> "_rect"
476        | _ -> assert false 
477      in
478      let holes = 
479        HExtlib.mk_list Ast.Implicit (ity.leftno+1+ ity.consno + ity.rightno) in
480      let eliminator = 
481        let _,_,w = what in
482        Ast.Appl(Ast.Ident(name,None)::holes @ [ w ])
483      in
484      exact_tac ("",0,eliminator) status) ]) 
485 ;;
486
487 let rewrite_tac ~dir ~what:(_,_,what) ~where =
488  let name =
489   match dir with `LeftToRight -> "eq_elim_r" | `RightToLeft -> "eq_ind"
490  in
491   block_tac
492    [ select_tac ~where ~job:(`Substexpand 1) true;
493      exact_tac
494       ("",0,
495        Ast.Appl(Ast.Ident(name,None)::HExtlib.mk_list Ast.Implicit 5 @
496         [what]))]
497 ;;
498
499 let intro_tac name =
500  block_tac
501   [ exact_tac
502      ("",0,(Ast.Binder (`Lambda,
503       (Ast.Ident (name,None),None),Ast.Implicit)));
504     if name = "_" then clear_tac [name] else id_tac ]
505 ;;
506
507 let cases ~what status goal =
508  let gty = get_goalty status goal in
509  let status, what = disambiguate status what None (ctx_of gty) in
510  let status, ty = typeof status (ctx_of what) what in
511  let status, (ref, consno, _, _) = analyse_indty status ty in
512  let status, what = term_of_cic_term status what (ctx_of gty) in
513  let t =
514   NCic.Match (ref,NCic.Implicit `Term, what,
515     HExtlib.mk_list (NCic.Implicit `Term) consno)
516  in
517  let ctx = ctx_of gty in
518  let status,t,ty = refine status ctx (mk_cic_term ctx t) (Some gty) in
519  instantiate status goal t
520 ;;
521
522 let cases_tac ~what ~where = 
523   let indtyinfo = ref None in
524   atomic_tac 
525    (block_tac [
526       analyze_indty_tac ~what indtyinfo;
527       (fun s -> select_tac 
528        ~where ~job:(`Substexpand ((HExtlib.unopt !indtyinfo).rightno+1))true s);
529       distribute_tac (cases ~what) ])
530 ;;
531
532 let case1_tac name =
533  let name = if name = "_" then "_clearme" else name in
534  block_tac [ intro_tac name; 
535              cases_tac 
536               ~where:("",0,(None,[],None)) 
537               ~what:("",0,Ast.Ident (name,None));
538              if name = "_clearme" then clear_tac ["_clearme"] else id_tac ]
539 ;;
540
541 let assert0_tac (hyps,concl) = distribute_tac (fun status goal ->
542  let gty = get_goalty status goal in
543  let eq status ctx t1 t2 =
544   let status,t1 = disambiguate status t1 None ctx in
545   let status,t1 = apply_subst status ctx t1 in
546   let status,t1 = term_of_cic_term status t1 ctx in
547   let t2 = mk_cic_term ctx t2 in
548   let status,t2 = apply_subst status ctx t2 in
549   let status,t2 = term_of_cic_term status t2 ctx in
550   prerr_endline ("COMPARING: " ^ NCicPp.ppterm ~subst:[] ~metasenv:[] ~context:ctx t1 ^ " vs " ^ NCicPp.ppterm ~subst:[] ~metasenv:[] ~context:ctx t2);
551   assert (t1=t2);
552   status
553  in
554  let status,gty' = term_of_cic_term status gty (ctx_of gty) in
555  let status = eq status (ctx_of gty) concl gty' in
556  let status,_ =
557   List.fold_right2
558    (fun (id1,e1) ((id2,e2) as item) (status,ctx) ->
559      assert (id1=id2 || (prerr_endline (id1 ^ " vs " ^ id2); false));
560      match e1,e2 with
561         `Decl t1, NCic.Decl t2 ->
562           let status = eq status ctx t1 t2 in
563           status,item::ctx
564       | `Def (b1,t1), NCic.Def (b2,t2) ->
565           let status = eq status ctx t1 t2 in
566           let status = eq status ctx b1 b2 in
567           status,item::ctx
568       | _ -> assert false
569    ) hyps (ctx_of gty) (status,[])
570  in
571   exec id_tac status goal)
572 ;;
573
574 let assert_tac seqs status =
575  match status#stack with
576   | [] -> assert false
577   | (g,_,_,_) :: s ->
578      assert (List.length g = List.length seqs);
579      (match seqs with
580          [] -> id_tac
581        | [seq] -> assert0_tac seq
582        | _ ->
583          block_tac
584           (branch_tac::
585           HExtlib.list_concat ~sep:[shift_tac]
586             (List.map (fun seq -> [assert0_tac seq]) seqs)@
587           [merge_tac])
588      ) status
589 ;;
590
591 let auto ~params:(l,_) status goal =
592   let gty = get_goalty status goal in
593   let n,h,metasenv,subst,o = status#obj in
594   let status,t = term_of_cic_term status gty (ctx_of gty) in
595   let status, l = 
596     List.fold_left
597       (fun (status, l) t ->
598         let status, t = disambiguate status t None (ctx_of gty) in
599         let status, ty = typeof status (ctx_of t) t in
600         let status, t =  term_of_cic_term status t (ctx_of gty) in
601         let status, ty = term_of_cic_term status ty (ctx_of ty) in
602         (status, (t,ty) :: l))
603       (status,[]) l
604   in
605   let pt, metasenv, subst = 
606     Paramod.nparamod status metasenv subst (ctx_of gty) (NCic.Rel ~-1,t) l 
607   in      
608   let status = status#set_obj (n,h,metasenv,subst,o) in
609   instantiate status goal (NTacStatus.mk_cic_term (ctx_of gty) pt)
610 ;;
611
612 let auto_tac ~params status =
613   distribute_tac (auto ~params) status
614 ;;