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