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