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