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