]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_tactics/nTacStatus.ml
[ porting from CerCo's Matita ]
[helm.git] / matita / components / ng_tactics / nTacStatus.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 let debug = ref false;;
15 let pp x = 
16  if !debug then prerr_endline (Lazy.force x) else ()
17 ;;
18
19 type automation_cache = NDiscriminationTree.DiscriminationTree.t
20 type unit_eq_cache = NCicParamod.state
21
22 exception Error of string lazy_t * exn option
23 let fail ?exn msg = raise (Error (msg,exn))
24
25 module NRef = NReference
26
27 let wrap fname f x =
28   try f x 
29   with 
30   | MultiPassDisambiguator.DisambiguationError _ 
31   | NCicRefiner.RefineFailure _ 
32   | NCicUnification.UnificationFailure _ 
33   | NCicTypeChecker.TypeCheckerFailure _ 
34   | NCicMetaSubst.MetaSubstFailure _ as exn -> fail ~exn (lazy fname)
35 ;;
36
37 class type g_eq_status =
38  object
39    method eq_cache : unit_eq_cache 
40  end
41
42 class eq_status =
43  object(self)
44   val eq_cache = NCicParamod.empty_state
45   method eq_cache = eq_cache
46   method set_eq_cache v = {< eq_cache = v >}
47   method set_eq_status
48    : 'status. #g_eq_status as 'status -> 'self
49    = fun o -> self#set_eq_cache o#eq_cache
50  end
51
52 class type g_auto_status =
53  object
54    method auto_cache : automation_cache
55  end
56
57 class auto_status =
58  object(self)
59   val auto_cache = NDiscriminationTree.DiscriminationTree.empty
60   method auto_cache = auto_cache
61   method set_auto_cache v = {< auto_cache = v >}
62   method set_auto_status
63    : 'status. #g_auto_status as 'status -> 'self
64    = fun o -> self#set_auto_cache o#auto_cache
65  end
66
67 class type g_pstatus =
68  object
69   inherit GrafiteDisambiguate.g_status
70   inherit g_auto_status
71   inherit g_eq_status
72   method obj: NCic.obj
73  end
74
75 class pstatus =
76  fun (o: NCic.obj) ->
77  object (self)
78    inherit GrafiteDisambiguate.status
79    inherit auto_status
80    inherit eq_status
81    val obj = o
82    method obj = obj
83    method set_obj o = {< obj = o >}
84    method set_pstatus : 'status. #g_pstatus as 'status -> 'self
85    = fun o ->
86     (((self#set_disambiguate_status o)#set_obj o#obj)#set_auto_status o)#set_eq_status o
87   end
88
89 type tactic_term = NotationPt.term Disambiguate.disambiguator_input
90 type tactic_pattern = GrafiteAst.npattern Disambiguate.disambiguator_input
91
92 let pp_tac_status status = 
93   prerr_endline (NCicPp.ppobj status#obj);
94   prerr_endline ("STACK:\n" ^ Continuationals.Stack.pp status#stack)
95 ;;
96
97 type cic_term = NCic.context * NCic.term
98 let ctx_of (c,_) = c ;;
99 let mk_cic_term c t = c,t ;;
100
101 let ppterm status t =
102  let uri,height,metasenv,subst,obj = status#obj in
103  let context,t = t in
104   NCicPp.ppterm ~metasenv ~subst ~context t
105 ;;
106
107 let ppcontext status c =
108  let uri,height,metasenv,subst,obj = status#obj in
109   NCicPp.ppcontext ~metasenv ~subst c
110 ;;
111
112 let ppterm_and_context status t =
113  let uri,height,metasenv,subst,obj = status#obj in
114  let context,t = t in
115   NCicPp.ppcontext ~metasenv ~subst context ^ "\n ⊢ "^ 
116   NCicPp.ppterm ~metasenv ~subst ~context t
117 ;;
118
119 let relocate status destination (source,t as orig) =
120  pp(lazy("relocate:\n" ^ ppterm_and_context status orig));
121  pp(lazy("relocate in:\n" ^ ppcontext status destination));
122  let rc = 
123    if source == destination then status, orig else
124     let _, _, metasenv, subst, _ = status#obj in
125     let rec compute_ops ctx = function (* destination, source *)
126       | (n1, NCic.Decl t1 as e)::cl1 as ex, (n2, NCic.Decl t2)::cl2 ->
127           if n1 = n2 && 
128              NCicReduction.are_convertible ctx ~subst ~metasenv t1 t2 then
129             compute_ops (e::ctx) (cl1,cl2)
130           else
131             [ `Delift ctx; `Lift (List.rev ex) ]
132       | (n1, NCic.Def (b1,t1) as e)::cl1 as ex, (n2, NCic.Def (b2,t2))::cl2 ->
133           if n1 = n2 && 
134              NCicReduction.are_convertible ctx ~subst ~metasenv t1 t2 &&
135              NCicReduction.are_convertible ctx ~subst ~metasenv b1 b2 then
136             compute_ops (e::ctx) (cl1,cl2)
137           else
138             [ `Delift ctx; `Lift (List.rev ex) ]
139       | (n1, NCic.Def (b1,t1) as e)::cl1 as ex, (n2, NCic.Decl t2)::cl2 ->
140           if n1 = n2 && 
141              NCicReduction.are_convertible ctx ~subst ~metasenv t1 t2 then
142             compute_ops (e::ctx) (cl1,cl2)
143           else
144             [ `Delift ctx; `Lift (List.rev ex) ]
145       | (n1, NCic.Decl _)::cl1 as ex, (n2, NCic.Def _)::cl2 -> 
146             [ `Delift ctx; `Lift (List.rev ex) ]
147       | _::_ as ex, [] -> [ `Lift (List.rev ex) ]
148       | [], _::_ -> [ `Delift ctx ]
149       | [],[] -> []
150     in
151     let ops = compute_ops [] (List.rev destination, List.rev source) in
152     let rec mk_irl i j = if i > j then [] else NCic.Rel i :: mk_irl (i+1) j in
153     List.fold_left 
154      (fun (status, (source,t)) -> function 
155       | `Lift extra_ctx -> 
156            let len = List.length extra_ctx in
157            status, (extra_ctx@source, NCicSubstitution.lift len t)
158       | `Delift ctx -> 
159             let len_ctx = List.length ctx in
160             let irl = mk_irl 1 (List.length ctx) in
161             let lc = List.length source - len_ctx, NCic.Ctx irl in
162             let u, d, metasenv, subst, o = status#obj in
163             pp(lazy("delifting as " ^ 
164               NCicPp.ppterm ~metasenv ~subst ~context:source 
165                (NCic.Meta (0,lc))));
166             let (metasenv, subst), t =
167               NCicMetaSubst.delift 
168                  ~unify:(fun m s c t1 t2 -> 
169                    try Some (NCicUnification.unify status m s c t1 t2)
170                    with 
171                     | NCicUnification.UnificationFailure _ 
172                     | NCicUnification.Uncertain _ -> None) 
173                metasenv subst source 0 lc t
174             in
175             let status = status#set_obj (u, d, metasenv, subst, o) in
176             status, (ctx,t))
177        (status,orig) ops
178  in
179  pp(lazy("relocated: " ^ ppterm (fst rc) (snd rc)));
180  rc
181 ;;
182 let relocate a b c = wrap "relocate" (relocate a b) c;;
183
184 let term_of_cic_term s t c = 
185   let s, (_,t) = relocate s c t in
186   s, t
187 ;;
188
189 let disambiguate status context t ty =
190  let status, expty = 
191    match ty with 
192    | None -> status, None 
193    | Some ty -> 
194        let status, (_,x) = relocate status context ty in status, Some x 
195  in
196  let uri,height,metasenv,subst,obj = status#obj in
197  let metasenv, subst, status, t = 
198    GrafiteDisambiguate.disambiguate_nterm status expty context metasenv subst t 
199  in
200  let new_pstatus = uri,height,metasenv,subst,obj in
201   status#set_obj new_pstatus, (context, t) 
202 ;;
203 let disambiguate a b c d = wrap "disambiguate" (disambiguate a b c) d;;
204
205 let typeof status ctx t =
206   let status, (_,t) = relocate status ctx t in
207   let _,_,metasenv,subst,_ = status#obj in
208   let ty = NCicTypeChecker.typeof ~subst ~metasenv ctx t in
209   status, (ctx, ty)
210 ;;
211 let typeof a b c = wrap "typeof" (typeof a b) c;;
212
213 let saturate status ?delta (ctx,t) =
214   let n,h,metasenv,subst,k = status#obj in
215   let t,metasenv,args = NCicMetaSubst.saturate ?delta metasenv subst ctx t 0 in
216   let status = status#set_obj (n,h,metasenv,subst,k) in
217   status, (ctx,t), List.map (fun x -> ctx,x) args
218 ;;
219 let saturate a ?delta b = wrap "saturate" (saturate a ?delta) b;;
220   
221 let whd status ?delta ctx t =
222   let status, (_,t) = relocate status ctx t in
223   let _,_,_,subst,_ = status#obj in
224   let t = NCicReduction.whd ~subst ?delta ctx t in
225   status, (ctx, t)
226 ;;
227   
228 let normalize status ?delta ctx t =
229   let status, (_,t) = relocate status ctx t in
230   let _,_,_,subst,_ = status#obj in
231   let t = NCicTacReduction.normalize ~subst ?delta ctx t in
232   status, (ctx, t)
233 ;;
234   
235 let unify status ctx a b =
236   let status, (_,a) = relocate status ctx a in
237   let status, (_,b) = relocate status ctx b in
238   let n,h,metasenv,subst,o = status#obj in
239   let metasenv, subst = NCicUnification.unify status metasenv subst ctx a b in
240    status#set_obj (n,h,metasenv,subst,o)
241 ;;
242 let unify a b c d = wrap "unify" (unify a b c) d;;
243
244 let fix_sorts status (ctx,t) =
245  let f () =
246   let name,height,metasenv,subst,obj = status#obj in
247   let metasenv, t = 
248     NCicUnification.fix_sorts metasenv subst t in
249   let status = status#set_obj (name,height,metasenv,subst,obj) in
250    status, (ctx,t)
251  in
252   wrap "fix_sorts" f ()
253 ;;
254
255 let refine status ctx term expty =
256   let status, (_,term) = relocate status ctx term in
257   let status, expty = 
258     match expty with
259       None -> status, None 
260     | Some e -> 
261         let status, (_, e) = relocate status ctx e in status, Some e
262   in
263   let name,height,metasenv,subst,obj = status#obj in
264   let metasenv,subst,t,ty = 
265    NCicRefiner.typeof status metasenv subst ctx term expty
266   in
267    status#set_obj (name,height,metasenv,subst,obj), (ctx,t), (ctx,ty)
268 ;;
269 let refine a b c d = wrap "refine" (refine a b c) d;;
270
271 let get_goalty status g =
272  let _,_,metasenv,_,_ = status#obj in
273  try
274    let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
275    ctx, ty
276  with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_goalty")
277 ;;
278
279 let get_subst status =
280   let _,_,_,subst,_ = status#obj in subst
281 ;;
282
283 let to_subst status i entry =
284  let name,height,metasenv,subst,obj = status#obj in
285  let metasenv = List.filter (fun j,_ -> j <> i) metasenv in
286  let subst = (i, entry) :: subst in
287   status#set_obj (name,height,metasenv,subst,obj)
288 ;;
289
290 let instantiate status ?refine:(dorefine=true) i t =
291  let _,_,metasenv,_,_ = status#obj in
292  let gname, context, gty = List.assoc i metasenv in
293   if dorefine then
294    let status, (_,t), (_,ty) = refine status context t (Some (context,gty)) in
295     to_subst status i (gname,context,t,ty)
296   else
297    let status,(_,ty) = typeof status context t in
298     to_subst status i (gname,context,snd t,ty)
299 ;;
300
301 let instantiate_with_ast status i t =
302  let _,_,metasenv,_,_ = status#obj in
303  let gname, context, gty = List.assoc i metasenv in
304  let ggty = mk_cic_term context gty in
305  let status, (_,t) = disambiguate status context t (Some ggty) in
306   to_subst status i (gname,context,t,gty)
307 ;;
308
309 let mk_meta status ?(attrs=[]) ctx bo_or_ty kind =
310   match bo_or_ty with
311   | `Decl ty ->
312       let status, (_,ty) = relocate status ctx ty in
313       let n,h,metasenv,subst,o = status#obj in
314       let metasenv, _, instance, _ = 
315         NCicMetaSubst.mk_meta ~attrs metasenv ctx ~with_type:ty kind
316       in
317       let status = status#set_obj (n,h,metasenv,subst,o) in
318       status, (ctx,instance)
319   | `Def bo ->
320       let status, (_,bo_ as bo) = relocate status ctx bo in
321       let status, (_,ty) = typeof status ctx bo in
322       let n,h,metasenv,subst,o = status#obj in
323       let metasenv, metano, instance, _ = 
324         NCicMetaSubst.mk_meta ~attrs metasenv ctx ~with_type:ty kind in
325       let attrs,_,_ = NCicUtils.lookup_meta metano metasenv in
326       let metasenv = List.filter (fun j,_ -> j <> metano) metasenv in
327       let subst = (metano, (attrs, ctx, bo_, ty)) :: subst in
328       let status = status#set_obj (n,h,metasenv,subst,o) in
329       status, (ctx,instance)
330 ;;
331
332 let mk_in_scope status t =
333   mk_meta status ~attrs:[`InScope] (ctx_of t) (`Def t) `IsTerm
334 ;;
335
336 let mk_out_scope n status t = 
337   mk_meta status ~attrs:[`OutScope n] (ctx_of t) (`Def t) `IsTerm
338 ;;
339
340 (* the following unification problem will be driven by 
341  *   select s ~found:mk_in_scope ~postprocess:(mk_out_scope argsno) t pattern
342  *
343  *   ? args = t
344  *
345  *   where argsn = length args and the pattern matches t
346  *
347  *  found is called on every selected term to map them
348  *  postprocess is called on the entire term after selection
349  *)
350 let select_term 
351   low_status ~found ~postprocess (context,term) (wanted,path) 
352 =
353   let is_found status ctx t wanted =
354     (* we could lift wanted step-by-step *)
355     pp(lazy("is_found: "^ppterm status (ctx,t)));
356     try true, unify status ctx (ctx, t) wanted
357     with 
358     | Error (_, Some (NCicUnification.UnificationFailure _))
359     | Error (_, Some (NCicUnification.Uncertain _)) -> false, status
360   in
361   let match_term status ctx (wanted : cic_term) t =
362     let rec aux ctx (status,already_found) t =
363       let b, status = is_found status ctx t wanted in
364       if b then
365          let status , (_,t) = found status (ctx, t) in 
366          (status,true),t
367       else
368         let _,_,_,subst,_ = status#obj in
369         match t with
370         | NCic.Meta (i,lc) when List.mem_assoc i subst ->
371             let _,_,t,_ = NCicUtils.lookup_subst i subst in
372             aux ctx (status,already_found) t
373         | NCic.Meta _ -> (status,already_found),t
374         | _ ->
375           NCicUntrusted.map_term_fold_a (fun e c -> e::c) ctx aux
376            (status,already_found) t
377      in 
378        aux ctx (status,false) t
379   in 
380   let _,_,_,subst,_ = low_status#obj in
381   let rec select status ctx pat cic = 
382     match pat, cic with
383     | _, NCic.Meta (i,lc) when List.mem_assoc i subst ->
384         let cic = 
385           let _,_,t,_ = NCicUtils.lookup_subst i subst in
386           NCicSubstitution.subst_meta lc t
387         in
388         select status ctx pat cic
389     | NCic.LetIn (_,t1,s1,b1), NCic.LetIn (n,t2,s2,b2) ->
390         let status, t = select status ctx t1 t2 in
391         let status, s = select status ctx s1 s2 in
392         let ctx = (n, NCic.Def (s2,t2)) :: ctx in
393         let status, b = select status ctx b1 b2 in
394         status, NCic.LetIn (n,t,s,b)
395     | NCic.Lambda (_,s1,t1), NCic.Lambda (n,s2,t2) ->
396         let status, s = select status ctx s1 s2 in
397         let ctx = (n, NCic.Decl s2) :: ctx in
398         let status, t = select status ctx t1 t2 in
399         status, NCic.Lambda (n,s,t)
400     | NCic.Prod (_,s1,t1), NCic.Prod (n,s2,t2) ->
401         let status, s = select status ctx s1 s2 in
402         let ctx = (n, NCic.Decl s2) :: ctx in
403         let status, t = select status ctx t1 t2 in
404         status, NCic.Prod (n,s,t)
405     | NCic.Appl l1, NCic.Appl l2 ->
406         let status, l = 
407            List.fold_left2
408              (fun (status,l) x y -> 
409               let status, x = select status ctx x y in
410               status, x::l)
411              (status,[]) l1 l2
412         in
413         status, NCic.Appl (List.rev l)
414     | NCic.Match (_,ot1,t1,pl1), NCic.Match (u,ot2,t2,pl2) ->
415         let status, t = select status ctx t1 t2 in
416         let status, ot = select status ctx ot1 ot2 in
417         let status, pl = 
418            List.fold_left2
419              (fun (status,l) x y -> 
420               let status, x = select status ctx x y in
421               status, x::l)
422              (status,[]) pl1 pl2
423         in
424         status, NCic.Match (u,ot,t,List.rev pl)
425     | NCic.Implicit `Hole, t -> 
426         (match wanted with
427         | Some wanted -> 
428              let status', wanted = disambiguate status ctx wanted None in
429              pp(lazy("wanted: "^ppterm status' wanted));
430              let (status',found), t' = match_term status' ctx wanted t in
431               if found then status',t' else status,t
432         | None ->
433            let (status,_),t = match_term status ctx (ctx,t) t in
434             status,t)
435     | NCic.Implicit _, t -> status, t
436     | _,t -> 
437         fail (lazy ("malformed pattern: " ^ NCicPp.ppterm ~metasenv:[]
438           ~context:[] ~subst:[] pat ^ " against " ^ 
439           NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))
440   in
441   pp(lazy ("select in: "^ppterm low_status (context,term)));
442   let status, term = select low_status context path term in
443   let term = (context, term) in
444   pp(lazy ("postprocess: "^ppterm low_status term));
445   postprocess status term
446 ;;
447
448 let analyse_indty status ty = 
449  let status, reduct = whd status (ctx_of ty) ty in
450  let ref, args =
451   match reduct with
452    | _,NCic.Const ref -> ref, []
453    | _,NCic.Appl (NCic.Const (NRef.Ref (_,(NRef.Ind _)) as ref) :: args) -> 
454          ref, args
455    | _,_ -> fail (lazy ("not an inductive type: " ^ ppterm status ty)) in
456  let _,lno,tl,_,i = NCicEnvironment.get_checked_indtys ref in
457  let _,_,_,cl = List.nth tl i in
458  let consno = List.length cl in
459  let left, right = HExtlib.split_nth lno args in
460  status, (ref, consno, left, right)
461 ;;
462
463 let apply_subst status ctx t =
464  let status, (_,t) = relocate status ctx t in
465  let _,_,_,subst,_ = status#obj in
466   status, (ctx, NCicUntrusted.apply_subst subst ctx t)
467 ;;
468
469 let apply_subst_context status ~fix_projections ctx =
470  let _,_,_,subst,_ = status#obj in
471   NCicUntrusted.apply_subst_context ~fix_projections subst ctx
472 ;;
473
474 let metas_of_term status (context,t) =
475  let _,_,_,subst,_ = status#obj in
476  NCicUntrusted.metas_of_term subst context t
477 ;;
478
479 (* ============= move this elsewhere ====================*)
480
481 class type ['stack] g_status =
482  object
483   inherit g_pstatus
484   method stack: 'stack
485  end
486
487 class ['stack] status =
488  fun (o: NCic.obj) (s: 'stack) ->
489  object (self)
490    inherit (pstatus o)
491    val stack = s
492    method stack = stack
493    method set_stack s = {< stack = s >}
494    method set_status : 'status. 'stack #g_status as 'status -> 'self
495    = fun o -> (self#set_pstatus o)#set_stack o#stack
496   end
497
498 class type lowtac_status = [unit] status
499
500 type 'status lowtactic = #lowtac_status as 'status -> int -> 'status
501
502 class type tac_status = [Continuationals.Stack.t] status
503
504 type 'status tactic = #tac_status as 'status -> 'status
505
506 module NCicInverseRelIndexable : Discrimination_tree.Indexable
507 with type input = cic_term and type constant_name = NUri.uri = struct
508
509 open Discrimination_tree
510
511 type input = cic_term
512 type constant_name = NUri.uri
513
514 let ppelem = function
515   | Constant (uri,arity) -> 
516       "("^NUri.name_of_uri uri ^ "," ^ string_of_int arity^")"
517   | Bound (i,arity) -> 
518       "("^string_of_int i ^ "," ^ string_of_int arity^")"
519   | Variable -> "?"
520   | Proposition -> "Prop"
521   | Datatype -> "Type"
522   | Dead -> "Dead"
523 ;;
524
525 let string_of_path l = String.concat "." (List.map ppelem l) ;;
526
527 let path_string_of (ctx,t) =
528   let len_ctx = List.length ctx in
529   let rec aux arity = function
530     | NCic.Appl ((NCic.Meta _|NCic.Implicit _)::_) -> [Variable]
531     | NCic.Appl (NCic.Lambda _ :: _) -> [Variable] (* maybe we should b-reduce *)
532     | NCic.Appl [] -> assert false
533     | NCic.Appl (hd::tl) ->
534         aux (List.length tl) hd @ List.flatten (List.map (aux 0) tl) 
535     | NCic.Lambda _ | NCic.Prod _ -> [Variable]
536         (* I think we should CicSubstitution.subst Implicit t *)
537     | NCic.LetIn _ -> [Variable] (* z-reduce? *)
538     | NCic.Meta _ | NCic.Implicit _ -> assert (arity = 0); [Variable]
539     | NCic.Rel i -> [Bound (len_ctx - i, arity)]
540     | NCic.Sort (NCic.Prop) -> assert (arity=0); [Proposition]
541     | NCic.Sort _ -> assert (arity=0); [Datatype]
542     | NCic.Const (NReference.Ref (u,_)) -> [Constant (u, arity)]
543     | NCic.Match _ -> [Dead]
544   in 
545   let path = aux 0 t in
546 (*   prerr_endline (string_of_path path); *)
547   path
548 ;;
549
550 let compare e1 e2 =
551   match e1,e2 with
552   | Constant (u1,a1),Constant (u2,a2) -> 
553        let x = NUri.compare u1 u2 in
554        if x = 0 then Pervasives.compare a1 a2 else x
555   | e1,e2 -> Pervasives.compare e1 e2
556 ;;
557
558
559 end
560
561 module Ncic_termOT : Set.OrderedType with type t = cic_term =
562  struct
563    type t = cic_term
564    let compare = Pervasives.compare
565  end
566
567 module Ncic_termSet : Set.S with type elt = cic_term = Set.Make(Ncic_termOT)
568
569 module InvRelDiscriminationTree = 
570    Discrimination_tree.Make(NCicInverseRelIndexable)(Ncic_termSet)
571