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