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.
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_______________________________________________________________ *)
12 (* $Id: nCic.ml 9058 2008-10-13 17:42:30Z tassi $ *)
17 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
19 open Continuationals.Stack
21 module Ast = NotationPt
23 let id_tac status = status ;;
24 let print_tac print_status message status =
25 if print_status then pp_tac_status status;
26 prerr_endline message;
32 match status#stack with
34 | ([], _, [], _) :: _ as stack ->
35 (* backward compatibility: do-nothing-dot *)
37 | (g, t, k, tag) :: s ->
38 match filter_open g, k with
40 (([ loc ], t, loc_tl @+ k, tag) :: s)
43 (([ loc ], t, k, tag) :: s)
44 | _ -> fail (lazy "can't use \".\" here")
46 status#set_stack gstatus
49 let branch_tac ?(force=false) status =
51 match status#stack with
53 | (g, t, k, tag) :: s ->
54 match init_pos g with (* TODO *)
55 | [] -> fail (lazy "empty goals")
56 | [_] when (not force) -> fail (lazy "too few goals to branch")
58 ([ loc ], [], [], `BranchTag) :: (loc_tl, t, k, tag) :: s
60 status#set_stack gstatus
63 let shift_tac status =
65 match status#stack with
66 | (g, t, k, `BranchTag) :: (g', t', k', tag) :: s ->
68 | [] -> fail (lazy "no more goals to shift")
70 (([ loc ], t @+ filter_open g @+ k, [],`BranchTag)
71 :: (loc_tl, t', k', tag) :: s))
72 | _ -> fail (lazy "can't shift goals here")
74 status#set_stack gstatus
77 let pos_tac i_s status =
79 match status#stack with
81 | ([ loc ], t, [],`BranchTag) :: (g', t', k', tag) :: s
83 let l_js = List.filter (fun (i, _) -> List.mem i i_s) ([loc] @+ g') in
84 ((l_js, t , [],`BranchTag)
85 :: (([ loc ] @+ g') @- l_js, t', k', tag) :: s)
86 | _ -> fail (lazy "can't use relative positioning here")
88 status#set_stack gstatus
91 let case_tac lab status =
93 match status#stack with
95 | ([ loc ], t, [],`BranchTag) :: (g', t', k', tag) :: s
100 let _,_,metasenv,_,_ = status#obj in
101 match NCicUtils.lookup_meta (goal_of_loc curloc) metasenv with
102 attrs,_,_ when List.mem (`Name lab) attrs -> true
103 | _ -> false) ([loc] @+ g') in
104 ((l_js, t , [],`BranchTag)
105 :: (([ loc ] @+ g') @- l_js, t', k', tag) :: s)
106 | _ -> fail (lazy "can't use relative positioning here")
108 status#set_stack gstatus
111 let wildcard_tac status =
113 match status#stack with
115 | ([ loc ] , t, [], `BranchTag) :: (g', t', k', tag) :: s
117 (([loc] @+ g', t, [], `BranchTag) :: ([], t', k', tag) :: s)
118 | _ -> fail (lazy "can't use wildcard here")
120 status#set_stack gstatus
123 let merge_tac status =
125 match status#stack with
127 | (g, t, k,`BranchTag) :: (g', t', k', tag) :: s ->
128 ((t @+ filter_open g @+ g' @+ k, t', k', tag) :: s)
129 | _ -> fail (lazy "can't merge goals here")
131 status#set_stack gstatus
134 let focus_tac gs status =
136 match status#stack with
138 | s -> assert(gs <> []);
140 let add_l acc _ _ l = if is_open l then l :: acc else acc in
141 fold ~env:add_l ~cont:add_l ~todo:add_l [] s
145 if not (List.exists (fun l -> goal_of_loc l = g) stack_locs) then
146 fail (lazy (sprintf "goal %d not found (or closed)" g)))
148 (zero_pos gs, [], [], `FocusTag) :: deep_close gs s
150 status#set_stack gstatus
153 let unfocus_tac status =
155 match status#stack with
157 | (g, [], [], `FocusTag) :: s when filter_open g = [] -> s
158 | _ as s -> fail (lazy ("can't unfocus, some goals are still open:\n"^
159 Continuationals.Stack.pp s))
161 status#set_stack gstatus
164 let skip_tac status =
166 match status#stack with
168 | (gl, t, k, tag) :: s ->
169 let gl = List.map switch_of_loc gl in
170 if List.exists (function Open _ -> true | Closed _ -> false) gl then
171 fail (lazy "cannot skip an open goal")
175 status#set_stack gstatus
178 let block_tac l status =
179 List.fold_left (fun status tac -> tac status) status l
183 let compare_statuses ~past ~present =
184 let _,_,past,_,_ = past#obj in
185 let _,_,present,_,_ = present#obj in
186 List.map fst (List.filter (fun (i,_) -> not(List.mem_assoc i past)) present),
187 List.map fst (List.filter (fun (i,_) -> not (List.mem_assoc i present)) past)
192 (* Exec and distribute_tac form a retraction pair:
193 1) exec (distribute_tac low_tac) (s,i) = low_tac (s,i)
194 2) tac [s]::G = G1::...::Gn::G' && G' is G with some goals closed =>
195 distribute_tac (exec tac) [s]::G = (G1@...Gn)::G'
196 3) tac G = distribute_tac (exec tac) G if
197 tac = distribute_tac lowtac
198 4) atomic_tac t === distribute_tac (exec t)
200 Note that executing an high tactic on a set of goals may be stronger
201 than executing the same tactic on those goals, but once at a time
202 (e.g. the tactic could perform a global analysis of the set of goals)
205 (* CSC: potential bug here: the new methods still use the instance variables
206 of the old status and not the instance variables of the new one *)
207 let change_stack_type (status : 'a #NTacStatus.status) (stack: 'b) : 'b NTacStatus.status =
208 let uid = status#user in
211 inherit ['b] NTacStatus.status uid status#obj stack
212 method ppterm = status#ppterm
213 method ppcontext = status#ppcontext
214 method ppsubst = status#ppsubst
215 method ppobj = status#ppobj
216 method ppmetasenv = status#ppmetasenv
222 let exec tac (low_status : #lowtac_status) g =
223 let stack = [ [0,Open g], [], [], `NoTag ] in
224 let status = change_stack_type low_status stack in
225 let status = tac status in
226 (low_status#set_pstatus status)#set_obj status#obj
229 let distribute_tac tac (status : #tac_status) =
230 match status#stack with
232 | (g, t, k, tag) :: s ->
233 debug_print (lazy ("context length " ^string_of_int (List.length g)));
234 let rec aux s go gc =
237 debug_print (lazy "no selected goals");
240 debug_print (lazy "inner eval tactical");
242 if List.exists ((=) (goal_of_loc loc)) gc then
245 match switch_of_loc loc with
246 | Closed _ -> fail (lazy "cannot apply to a Closed goal")
249 let go', gc' = compare_statuses ~past:s ~present:sn in
250 sn, ((go @+ [n]) @- gc') @+ go', gc @+ gc'
254 let s0 = change_stack_type status () in
255 let s0, go0, gc0 = s0, [], [] in
256 let sn, gon, gcn = aux s0 go0 gc0 g in
257 debug_print (lazy ("opened: "
258 ^ String.concat " " (List.map string_of_int gon)));
259 debug_print (lazy ("closed: "
260 ^ String.concat " " (List.map string_of_int gcn)));
262 (zero_pos gon, t @~- gcn, k @~- gcn, tag) :: deep_close gcn s
264 ((status#set_stack stack)#set_obj(sn:>lowtac_status)#obj)#set_pstatus sn
267 let atomic_tac htac: #tac_status as 'a -> 'a = distribute_tac (exec htac) ;;
270 let rec repeat t (status : #tac_status as 'a) : 'a =
271 try repeat t (t status)
272 with NTacStatus.Error _ -> status
274 atomic_tac (repeat t) s
278 let try_tac tac status =
282 with NTacStatus.Error _ ->
285 atomic_tac try_tac status
288 let first_tac tacl status =
291 (fun tac _ -> try Some (tac status) with NTacStatus.Error _ -> None) tacl
294 | None -> fail (lazy "No tactics left")
298 let exact_tac t : 's tactic = distribute_tac (fun status goal ->
299 instantiate_with_ast status goal t)
302 let assumption_tac status = distribute_tac (fun status goal ->
303 let gty = get_goalty status goal in
304 let context = ctx_of gty in
307 (List.map (fun (name,_) -> exact_tac ("",0,(Ast.Ident (name,`Ambiguous))))
310 exec htac status goal) status
313 let find_in_context name context =
314 let rec aux acc = function
315 | [] -> raise Not_found
316 | (hd,_) :: tl when hd = name -> acc
317 | _ :: tl -> aux (acc + 1) tl
322 let clear_tac names =
323 if names = [] then id_tac
325 distribute_tac (fun status goal ->
326 let goalty = get_goalty status goal in
330 try find_in_context name (ctx_of goalty)
332 fail (lazy ("hypothesis '" ^ name ^ "' not found")))
335 let n,h,metasenv,subst,o = status#obj in
336 let metasenv,subst,_,_ = NCicMetaSubst.restrict status metasenv subst goal js in
337 status#set_obj (n,h,metasenv,subst,o))
340 let generalize0_tac args =
341 if args = [] then id_tac
342 else exact_tac ("",0,Ast.Appl (Ast.Implicit `JustOne :: args))
345 let select0_tac ~where ~job =
346 let found, postprocess =
348 | `Substexpand argsno -> mk_in_scope, mk_out_scope argsno
349 | `Collect l -> (fun s t -> l := t::!l; mk_in_scope s t), mk_out_scope 1
350 | `ChangeWith f -> f,(fun s t -> s, t)
352 distribute_tac (fun status goal ->
353 let wanted,hyps,where =
354 GrafiteDisambiguate.disambiguate_npattern status where in
355 let goalty = get_goalty status goal in
357 match where with None -> NCic.Implicit `Term | Some where -> where
359 let status, newgoalctx =
361 (fun (name,d as entry) (status,ctx) ->
363 let path = List.assoc name hyps in
367 select_term status ~found ~postprocess (mk_cic_term ctx ty)
369 let status,ty = term_of_cic_term status ty ctx in
370 status,(name,NCic.Decl ty)::ctx
371 | NCic.Def (bo,ty) ->
373 select_term status ~found ~postprocess (mk_cic_term ctx bo)
375 let status,bo = term_of_cic_term status bo ctx in
376 status,(name,NCic.Def (bo,ty))::ctx
378 Not_found -> status, entry::ctx
379 ) (ctx_of goalty) (status,[])
381 let status, newgoalty =
382 select_term status ~found ~postprocess goalty (wanted,path) in
383 (* WARNING: the next two lines simply change the context of newgoalty
384 from the old to the new one. Otherwise mk_meta will do that herself,
385 calling relocate that calls delift. However, newgoalty is now
386 ?[out_scope] and thus the delift would trigger the special unification
387 case, which is wrong now :-( *)
388 let status,newgoalty = term_of_cic_term status newgoalty (ctx_of goalty) in
389 let newgoalty = mk_cic_term newgoalctx newgoalty in
391 let status, instance =
392 mk_meta status newgoalctx (`Decl newgoalty) `IsTerm
394 instantiate ~refine:false status goal instance)
397 let select_tac ~where:((txt,txtlen,(wanted,hyps,path)) as where) ~job
400 if not move_down_hyps then
401 select0_tac ~where ~job
405 (fun path (name,ty) ->
406 NotationPt.Binder (`Forall, (NotationPt.Ident (name,`Ambiguous),Some ty),path))
407 (match path with Some x -> x | None -> NotationPt.UserInput) (List.rev hyps)
410 generalize0_tac (List.map (fun (name,_) -> Ast.Ident (name,`Ambiguous)) hyps);
411 select0_tac ~where:(txt,txtlen,(wanted,[],Some path)) ~job;
412 clear_tac (List.map fst hyps) ]
415 let generalize_tac ~where =
418 select_tac ~where ~job:(`Collect l) true;
419 (fun s -> distribute_tac (fun status goal ->
420 let goalty = get_goalty status goal in
421 let status,canon,rest =
425 _,_,(None,_,_) -> fail (lazy "No term to generalize")
426 | txt,txtlen,(Some what,_,_) ->
428 disambiguate status (ctx_of goalty) (txt,txtlen,what) None
432 | he::tl -> status,he,tl in
435 (fun s t -> unify s (ctx_of goalty) canon t) status rest in
436 let status, canon = term_of_cic_term status canon (ctx_of goalty) in
437 instantiate status goal
438 (mk_cic_term (ctx_of goalty) (NCic.Appl [NCic.Implicit `Term ; canon ]))
443 atomic_tac (block_tac [
444 exact_tac ("",0, Ast.Appl [Ast.Implicit `JustOne; Ast.Implicit `JustOne]);
446 pos_tac [3]; exact_tac t;
447 shift_tac; pos_tac [2]; skip_tac;
451 let lapply_tac (s,n,t) =
452 exact_tac (s,n, Ast.Appl [Ast.Implicit `JustOne; t])
455 let reduce_tac ~reduction ~where =
456 let change status t =
458 | `Normalize perform_delta ->
460 ?delta:(if perform_delta then None else Some max_int) (ctx_of t) t
461 | `Whd perform_delta ->
463 ?delta:(if perform_delta then None else Some max_int) (ctx_of t) t
465 select_tac ~where ~job:(`ChangeWith change) false
468 let change_tac ~where ~with_what =
469 let change status t =
470 let status, ww = disambiguate status (ctx_of t) with_what None in
471 let status = unify status (ctx_of t) t ww in
474 select_tac ~where ~job:(`ChangeWith change) false
477 let letin_tac ~where ~what:(_,_,w) name =
479 select_tac ~where ~job:(`Substexpand 1) true;
481 ("",0,Ast.LetIn((Ast.Ident (name,`Ambiguous),None),w,Ast.Implicit `JustOne));
485 let apply_tac (s,n,t) =
486 let t = Ast.Appl [t; Ast.Implicit `Vector] in
494 reference: NReference.reference;
498 let ref_of_indtyinfo iti = iti.reference;;
500 let analyze_indty_tac ~what indtyref =
501 distribute_tac (fun (status as orig_status) goal ->
502 let goalty = get_goalty status goal in
503 let status, what = disambiguate status (ctx_of goalty) what None in
504 let status, ty_what = typeof status (ctx_of what) what in
505 let status, (r,consno,lefts,rights) = analyse_indty status ty_what in
506 let leftno = List.length lefts in
507 let rightno = List.length rights in
509 rightno = rightno; leftno = leftno; consno = consno; reference = r;
511 exec id_tac orig_status goal)
514 let sort_of_goal_tac sortref = distribute_tac (fun status goal ->
515 let goalty = get_goalty status goal in
516 let status,sort = typeof status (ctx_of goalty) goalty in
517 let status, sort = fix_sorts status sort in
518 let status, sort = term_of_cic_term status sort (ctx_of goalty) in
523 let elim_tac ~what:(txt,len,what) ~where =
524 let what = txt, len, Ast.Appl [what; Ast.Implicit `Vector] in
525 let indtyinfo = ref None in
526 let sort = ref (NCic.Rel 1) in
527 atomic_tac (block_tac [
528 analyze_indty_tac ~what indtyinfo;
530 ~where ~job:(`Substexpand ((HExtlib.unopt !indtyinfo).rightno+1)) true s);
531 sort_of_goal_tac sort;
533 let ity = HExtlib.unopt !indtyinfo in
534 let NReference.Ref (uri, _) = ity.reference in
536 NUri.name_of_uri uri ^ "_" ^
537 snd (NCicElim.ast_of_sort
538 (match !sort with NCic.Sort x -> x | _ -> assert false))
542 Ast.Appl [ Ast.Ident (name,`Ambiguous) ; Ast.Implicit `Vector ; w ]
544 exact_tac ("",0,eliminator) status) ])
547 let rewrite_tac ~dir ~what:(_,_,what) ~where status =
548 let sortref = ref (NCic.Rel 1) in
549 let status = sort_of_goal_tac sortref status in
550 let suffix = "_" ^ snd (NCicElim.ast_of_sort
551 (match !sortref with NCic.Sort x -> x | _ -> assert false))
555 `LeftToRight -> "eq" ^ suffix ^ "_r"
556 | `RightToLeft -> "eq" ^ suffix
558 let what = Ast.Appl [what; Ast.Implicit `Vector] in
560 [ select_tac ~where ~job:(`Substexpand 2) true;
563 Ast.Appl(Ast.Ident(name,`Ambiguous)::HExtlib.mk_list (Ast.Implicit `JustOne) 5@
570 ("",0,(Ast.Binder (`Lambda,
571 (Ast.Ident (name,`Ambiguous),None),Ast.Implicit `JustOne)));
572 if name = "_" then clear_tac [name] else id_tac ]
575 let name_counter = ref 0;;
576 let intros_tac ?names_ref names s =
577 let names_ref, prefix =
578 match names_ref with | None -> ref [], "__" | Some r -> r, "H"
584 (* TODO: generate better names *)
585 let name = prefix ^ string_of_int !name_counter in
586 let s = intro_tac name s in
587 names_ref := !names_ref @ [name];
591 block_tac (List.map intro_tac names) s
594 let cases ~what status goal =
595 let gty = get_goalty status goal in
596 let status, what = disambiguate status (ctx_of gty) what None in
597 let status, ty = typeof status (ctx_of what) what in
598 let status, (ref, consno, _, _) = analyse_indty status ty in
599 let status, what = term_of_cic_term status what (ctx_of gty) in
601 NCic.Match (ref,NCic.Implicit `Term, what,
602 HExtlib.mk_list (NCic.Implicit `Term) consno)
604 instantiate status goal (mk_cic_term (ctx_of gty) t)
607 let cases_tac ~what:(txt,len,what) ~where =
608 let what = txt, len, Ast.Appl [what; Ast.Implicit `Vector] in
609 let indtyinfo = ref None in
612 analyze_indty_tac ~what indtyinfo;
614 ~where ~job:(`Substexpand ((HExtlib.unopt !indtyinfo).rightno+1))true s);
615 distribute_tac (cases ~what) ])
619 let name = if name = "_" then "_clearme" else name in
620 block_tac [ intro_tac name;
622 ~where:("",0,(None,[],None))
623 ~what:("",0,Ast.Ident (name,`Ambiguous));
624 if name = "_clearme" then clear_tac ["_clearme"] else id_tac ]
627 let constructor_tac ?(num=1) ~args = distribute_tac (fun status goal ->
628 if num < 1 then fail (lazy "constructor numbers begin with 1");
629 let gty = get_goalty status goal in
630 let status, (r,_,_,_) = analyse_indty status gty in
631 let ref = NReference.mk_constructor num r in
633 if args = [] then Ast.NRef ref else
634 Ast.Appl (HExtlib.list_concat ~sep:[Ast.Implicit `Vector]
635 ([Ast.NRef ref] :: List.map (fun _,_,x -> [x]) args))
637 exec (apply_tac ("",0,t)) status goal)
640 let assert0_tac (hyps,concl) = distribute_tac (fun status goal ->
641 let gty = get_goalty status goal in
642 let eq status ctx t1 t2 =
643 let status,t1 = disambiguate status ctx t1 None in
644 let status,t1 = apply_subst status ctx t1 in
645 let status,t1 = term_of_cic_term status t1 ctx in
646 let t2 = mk_cic_term ctx t2 in
647 let status,t2 = apply_subst status ctx t2 in
648 let status,t2 = term_of_cic_term status t2 ctx in
649 prerr_endline ("COMPARING: " ^ status#ppterm ~subst:[] ~metasenv:[] ~context:ctx t1 ^ " vs " ^ status#ppterm ~subst:[] ~metasenv:[] ~context:ctx t2);
653 let status,gty' = term_of_cic_term status gty (ctx_of gty) in
654 let status = eq status (ctx_of gty) concl gty' in
657 (fun (id1,e1) ((id2,e2) as item) (status,ctx) ->
658 assert (id1=id2 || (prerr_endline (id1 ^ " vs " ^ id2); false));
660 `Decl t1, NCic.Decl t2 ->
661 let status = eq status ctx t1 t2 in
663 | `Def (b1,t1), NCic.Def (b2,t2) ->
664 let status = eq status ctx t1 t2 in
665 let status = eq status ctx b1 b2 in
668 ) hyps (ctx_of gty) (status,[])
670 exec id_tac status goal)
673 let assert_tac seqs status =
674 match status#stack with
677 assert (List.length g = List.length seqs);
680 | [seq] -> assert0_tac seq
683 ((branch_tac ~force:false)::
684 HExtlib.list_concat ~sep:[shift_tac]
685 (List.map (fun seq -> [assert0_tac seq]) seqs)@
690 let inversion_tac ~what:(txt,len,what) ~where =
691 let what = txt, len, Ast.Appl [what; Ast.Implicit `Vector] in
692 let indtyinfo = ref None in
693 let sort = ref (NCic.Rel 1) in
694 atomic_tac (block_tac [
695 analyze_indty_tac ~what indtyinfo;
697 ~where ~job:(`Substexpand ((HExtlib.unopt !indtyinfo).rightno+1)) true s);
698 sort_of_goal_tac sort;
700 let ity = HExtlib.unopt !indtyinfo in
701 let NReference.Ref (uri, _) = ity.reference in
703 NUri.name_of_uri uri ^ "_inv_" ^
704 snd (NCicElim.ast_of_sort
705 (match !sort with NCic.Sort x -> x | _ -> assert false))
709 Ast.Appl [ Ast.Ident (name,`Ambiguous) ; Ast.Implicit `Vector ; w ]
711 exact_tac ("",0,eliminator) status) ])