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