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