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