]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicMetaSubst.ml
snapshot for CSC
[helm.git] / helm / software / components / ng_refiner / nCicMetaSubst.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$ *)
13
14 exception MetaSubstFailure of string Lazy.t
15 exception Uncertain of string Lazy.t
16
17 let newmeta,maxmeta = 
18   let maxmeta = ref 0 in
19   (fun () -> incr maxmeta; !maxmeta),
20   (fun () -> !maxmeta)
21 ;;
22
23 exception NotInTheList;;
24
25 let position to_skip n (shift, lc) =
26   match lc with
27   | NCic.Irl _ when to_skip > 0 -> assert false  (* unclear to me *)
28   | NCic.Irl len when n <= shift || n > shift + len -> raise NotInTheList
29   | NCic.Irl _ -> n - shift
30   | NCic.Ctx tl ->
31       let rec aux to_skip k = function 
32          | [] -> raise NotInTheList
33          | _ :: tl when to_skip > 0 -> aux (to_skip - 1) (k+1) tl
34          | (NCic.Rel m)::_ when m + shift = n -> k
35          | _::tl -> aux to_skip (k+1) tl 
36       in
37        aux to_skip 1 tl
38 ;;
39
40 let pack_lc orig = 
41   let rec are_contiguous k = function
42     | [] -> true
43     | (NCic.Rel j) :: tl when j = k+1 -> are_contiguous j tl
44     | _ -> false
45   in
46   match orig with
47   | _, NCic.Ctx [] -> 0, NCic.Irl 0
48   | shift, NCic.Ctx (NCic.Rel k::tl as l) when are_contiguous k tl ->
49       shift+k-1, NCic.Irl (List.length l)
50   | _ -> orig
51 ;;
52
53
54
55 let mk_perforated_irl shift len restrictions =
56   let rec aux n =
57     if n = 0 then [] else
58      if List.mem (n+shift) restrictions then aux (n-1)
59      else (NCic.Rel n) :: aux (n-1)
60   in
61     pack_lc (shift, NCic.Ctx (List.rev (aux len)))
62 ;;
63
64 exception Occur;;
65
66 let rec force_does_not_occur metasenv subst restrictions t =
67  let rec aux k ms = function
68     | NCic.Rel r when List.mem (r - k) restrictions -> raise Occur
69     | NCic.Rel r as orig ->
70         let amount = 
71           List.length (List.filter (fun x -> x < r - k) restrictions) 
72         in
73         if amount > 0 then ms, NCic.Rel (r - amount) else ms, orig
74     | NCic.Meta (n, (shift,lc as l)) as orig ->
75        let meta_chain =
76         try
77          Some (NCicUtils.lookup_subst n subst)
78         with
79          NCicUtils.Subst_not_found _ -> None
80        in
81         (match meta_chain with
82             Some (_,_,bo,_) ->
83              aux k ms (NCicSubstitution.subst_meta l bo)
84           | None ->
85              (* we ignore the subst since restrict will take care of already
86               * instantiated/restricted metavariabels *)
87              let (metasenv,subst as ms), restrictions_for_n, l' =
88                let l = NCicUtils.expand_local_context lc in
89          
90                let ms, _, restrictions_for_n, l =
91                 List.fold_right
92                   (fun t (ms, i, restrictions_for_n, l) ->
93                     try 
94                       let ms, t = aux (k-shift) ms t in
95                       ms, i-1, restrictions_for_n, t::l
96                     with Occur ->
97                       ms, i-1, i::restrictions_for_n, l)
98                   l (ms, List.length l, [], [])
99                in
100                    
101                 ms, restrictions_for_n, pack_lc (shift, NCic.Ctx l)
102              in
103              if restrictions_for_n = [] then
104                ms, if l = l' then orig else NCic.Meta (n, l')
105              else
106                let metasenv, subst, newmeta = 
107                  restrict metasenv subst n restrictions_for_n 
108                in
109                  (metasenv, subst), NCic.Meta (newmeta, l'))
110     | t -> NCicUntrusted.map_term_fold_a (fun _ k -> k+1) k aux ms t
111  in
112    aux 0 (metasenv,subst) t 
113
114 and force_does_not_occur_in_context metasenv subst restrictions = function
115   | name, NCic.Decl t as orig ->
116       let (metasenv, subst), t' =
117         force_does_not_occur metasenv subst restrictions t in
118       metasenv, subst, (if t == t' then orig else (name,NCic.Decl t'))
119   | name, NCic.Def (bo, ty) as orig ->
120       let (metasenv, subst), bo' =
121         force_does_not_occur metasenv subst restrictions bo in
122       let (metasenv, subst), ty' =
123         force_does_not_occur metasenv subst restrictions ty in
124       metasenv, subst, 
125        (if bo == bo' && ty == ty' then orig else (name, NCic.Def (bo', ty')))
126
127 and erase_in_context metasenv subst pos restrictions = function
128   | [] -> metasenv, subst, restrictions, []
129   | hd::tl as orig ->
130       let metasenv, subst, restricted, tl' = 
131         erase_in_context metasenv subst (pos+1) restrictions tl in
132       if List.mem pos restricted then
133         metasenv, subst, restricted, tl'
134       else
135         try
136           let metasenv, subst, hd' =
137             let delifted_restricted = 
138               List.map ((+) ~-pos) (List.filter ((<=) pos) restricted) in
139             force_does_not_occur_in_context 
140               metasenv subst delifted_restricted hd
141           in
142            metasenv, subst, restricted, 
143             (if hd' == hd && tl' == tl then orig else (hd' :: tl'))
144         with Occur ->
145             metasenv, subst, (pos :: restricted), tl'
146
147 and restrict metasenv subst i restrictions =
148   assert (restrictions <> []);
149   try 
150     let name, ctx, bo, ty = NCicUtils.lookup_subst i subst in
151       try 
152         let metasenv, subst, restrictions, newctx = 
153           erase_in_context metasenv subst 1 restrictions ctx in
154         let (metasenv, subst), newty =  
155           force_does_not_occur metasenv subst restrictions ty in
156         let (metasenv, subst), newbo =  
157           force_does_not_occur metasenv subst restrictions bo in
158         let j = newmeta () in
159         let subst_entry_j = j, (name, newctx, newbo, newty) in
160         let reloc_irl = mk_perforated_irl 0 (List.length ctx) restrictions in
161         let subst_entry_i = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
162         let new_subst = 
163           subst_entry_j :: List.map 
164             (fun (n,_) as orig -> if i = n then subst_entry_i else orig) subst
165         in
166 (*
167     prerr_endline ("restringo nella subst: " ^string_of_int i ^ " -> " ^ 
168       string_of_int j ^ "\n" ^ 
169       NCicPp.ppsubst ~metasenv [subst_entry_j] ^ "\n\n" ^
170       NCicPp.ppsubst ~metasenv [subst_entry_i] ^ "\n" ^
171       NCicPp.ppterm ~metasenv ~subst ~context:ctx bo ^ " ---- " ^
172       NCicPp.ppterm ~metasenv ~subst ~context:newctx newbo
173             );
174 *)
175         metasenv, new_subst, j
176       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
177             ("Cannot restrict the context of the metavariable ?%d over "^^
178             "the hypotheses %s since ?%d is already instantiated "^^
179             "with %s and at least one of the hypotheses occurs in "^^
180             "the substituted term") i  (String.concat ", " 
181             (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)) i
182             (NCicPp.ppterm ~metasenv ~subst ~context:ctx bo))))
183   with NCicUtils.Subst_not_found _ -> 
184     try 
185       let name, ctx, ty = NCicUtils.lookup_meta i metasenv in
186       try
187         let metasenv, subst, restrictions, newctx = 
188           erase_in_context metasenv subst 1 restrictions ctx in
189         let (metasenv, subst), newty =  
190           force_does_not_occur metasenv subst restrictions ty in
191         let j = newmeta () in
192         let metasenv_entry = j, (name, newctx, newty) in
193         let reloc_irl = 
194           mk_perforated_irl 0 (List.length ctx) restrictions in
195         let subst_entry = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
196         List.map 
197           (fun (n,_) as orig -> if i = n then metasenv_entry else orig) 
198           metasenv,
199         subst_entry :: subst, j
200       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
201           ("Cannot restrict the context of the metavariable ?%d "^^
202           "over the hypotheses %s since metavariable's type depends "^^
203           "on at least one of them") i (String.concat ", " 
204           (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)))))
205     with 
206     | NCicUtils.Meta_not_found _ -> assert false
207 ;;
208
209 let rec flexible_arg subst = function 
210   | NCic.Meta (i,_) | NCic.Appl (NCic.Meta (i,_) :: _)-> 
211       (try 
212         let _,_,t,_ = List.assoc i subst in
213         flexible_arg subst t
214       with Not_found -> true)
215   | _ -> false
216 ;;
217
218 let in_scope_tag  = "tag:in_scope" ;;
219 let out_scope_tag_prefix = "tag:out_scope:" 
220 let out_scope_tag n = out_scope_tag_prefix ^ string_of_int n ;;
221 let is_out_scope_tag tag =
222    String.length tag > String.length out_scope_tag_prefix &&
223    String.sub tag 0 (String.length out_scope_tag_prefix) = out_scope_tag_prefix 
224 ;;
225 let int_of_out_scope_tag tag = 
226   int_of_string
227    (String.sub tag (String.length out_scope_tag_prefix)
228      (String.length tag - (String.length out_scope_tag_prefix)))
229 ;;
230
231
232 exception Found;;
233
234 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
235    otherwise the occur check does not make sense in case of unification
236    of ?n with ?n *)
237 let delift ~unify metasenv subst context n l t =
238   let is_in_scope_meta subst = function
239     | NCic.Meta (i,_) ->
240         (try 
241            let tag, _, _, _ = NCicUtils.lookup_subst i subst in 
242            tag = Some in_scope_tag 
243         with NCicUtils.Subst_not_found _ -> false)
244     | _ -> false
245   in
246   let contains_in_scope subst t = 
247     let rec aux _ () = function
248       | NCic.Meta _ as t ->
249           if is_in_scope_meta subst t then raise Found
250           else ()
251       | t -> 
252           if is_in_scope_meta subst t then raise Found
253           else NCicUtils.fold (fun _ () -> ()) () aux () t
254     in
255     try aux () () t; false with Found -> true
256   in
257   let unify_list in_scope = 
258     match l with
259     | _, NCic.Irl _ -> fun _ _ _ _ _ -> None
260     | shift, NCic.Ctx l -> fun metasenv subst context k t ->
261        if flexible_arg subst t || contains_in_scope subst t then None else
262          let lb = List.map (fun t -> t, flexible_arg subst t) l in
263          HExtlib.list_findopt
264           (fun (li,flexible) i ->
265             if flexible || i < in_scope then None else
266              let li = NCicSubstitution.lift (k+shift) li in
267              match unify metasenv subst context li t with
268              | Some (metasenv,subst) -> 
269                  Some ((metasenv, subst), NCic.Rel (i+1+k))
270              | None -> None)
271           lb
272   in
273   let rec aux (context,k,in_scope) (metasenv, subst as ms) t = 
274    match unify_list in_scope metasenv subst context k t with
275    | Some x -> x
276    | None -> 
277     match t with 
278     | NCic.Rel n as t when n <= k -> ms, t
279     | NCic.Rel n -> 
280         (try
281           match List.nth context (n-k-1) with
282           | _,NCic.Def (bo,_) -> 
283                 (try ms, NCic.Rel ((position in_scope (n-k) l) + k)
284                  with NotInTheList ->
285                 (* CSC: This bit of reduction hurts performances since it is
286                  * possible to  have an exponential explosion of the size of the
287                  * proof. required for nat/nth_prime.ma *)
288                   aux (context,k,in_scope) ms (NCicSubstitution.lift n bo))
289           | _,NCic.Decl _ -> ms, NCic.Rel ((position in_scope (n-k) l) + k)
290         with Failure _ -> assert false) (*Unbound variable found in delift*)
291     | NCic.Meta (i,_) when i=n ->
292          raise (MetaSubstFailure (lazy (Printf.sprintf (
293            "Cannot unify the metavariable ?%d with a term that has "^^
294            "as subterm %s in which the same metavariable "^^
295            "occurs (occur check)") i 
296             (NCicPp.ppterm ~context ~metasenv ~subst t))))
297     | NCic.Meta (i,l1) as orig ->
298         (try
299            let tag,c,t,ty = NCicUtils.lookup_subst i subst in
300            let in_scope, clear = 
301              match tag with 
302              | Some tag when tag = in_scope_tag -> 0, true
303              | Some tag when is_out_scope_tag tag->int_of_out_scope_tag tag,true
304              | _ -> in_scope, false
305            in
306            let ms = 
307              if not clear then ms
308              else 
309                metasenv, 
310                (i,(None,c,t,ty)) :: List.filter (fun j,_ -> i <> j) subst
311            in
312            aux (context,k,in_scope) ms (NCicSubstitution.subst_meta l1 t)
313          with NCicUtils.Subst_not_found _ ->
314            if snd l1 = NCic.Irl 0 || snd l1 = NCic.Ctx [] then ms, orig
315            else
316               let shift1,lc1 = l1 in
317               let shift,lc = l in
318               let shift = shift + k in
319               match lc, lc1 with
320               | NCic.Irl len, NCic.Irl len1 
321                 when shift1 + len1 < shift || shift1 > shift + len ->
322                   let restrictions = HExtlib.list_seq 1 (len1 + 1) in
323                   let metasenv, subst, newmeta = 
324                      restrict metasenv subst i restrictions 
325                   in
326                   (metasenv, subst), 
327                     NCic.Meta (newmeta, (0,NCic.Irl (max 0 (k-shift1))))
328               | NCic.Irl len, NCic.Irl len1 ->
329                   let low_restrictions, new_shift = 
330                     if k <= shift1 && shift1 < shift then 
331                       HExtlib.list_seq 1 (shift - shift1 + 1), k
332                     else if shift1 < k (* <= shift *) then
333                       let save_below = k - shift1 in
334                       HExtlib.list_seq (save_below + 1) (shift - shift1 + 1),
335                       shift1
336                     else [], shift1 - shift + k
337                   in
338                   let high_restrictions = 
339                     let last = shift + len in
340                     let last1 = shift1 + len1 in
341                     if last1 > last then
342                       let high_gap = last1 - last in
343                       HExtlib.list_seq (len1 - high_gap + 1) (len1 + 1)
344                     else []
345                   in
346                   let restrictions = low_restrictions @ high_restrictions in
347                   if restrictions = [] then
348                     if shift = k then ms, orig
349                     else ms, NCic.Meta (i, (new_shift, lc1))
350                   else
351                     let metasenv, subst, newmeta = 
352                        restrict metasenv subst i restrictions
353                     in
354 (* {{{
355                   prerr_endline ("RESTRICTIONS FOR: " ^ 
356                     NCicPp.ppterm ~metasenv ~subst ~context:[] 
357                     (NCic.Meta (i,l1))^" that was part of a term unified with "
358                     ^ NCicPp.ppterm ~metasenv ~subst ~context:[] (NCic.Meta
359                     (n,l)) ^ " ====> " ^ String.concat "," (List.map
360                     string_of_int restrictions) ^ "\nMENV:\n" ^
361                     NCicPp.ppmetasenv ~subst metasenv ^ "\nSUBST:\n" ^
362                     NCicPp.ppsubst subst ~metasenv);
363 }}} *)
364                     let newlc_len = len1 - List.length restrictions in 
365                     let meta = 
366                        NCic.Meta(newmeta,(new_shift, NCic.Irl newlc_len))
367                     in
368                     assert (
369                       let _, cctx, _ = NCicUtils.lookup_meta newmeta metasenv in
370                       List.length cctx = newlc_len);
371                     (metasenv, subst), meta
372
373               | _ ->
374                   let lc1 = NCicUtils.expand_local_context lc1 in
375                   let lc1 = List.map (NCicSubstitution.lift shift1) lc1 in
376                   let rec deliftl tbr j ms = function
377                     | [] -> ms, tbr, []
378                     | t::tl ->
379                         let ms, tbr, tl = deliftl tbr (j+1) ms tl in
380                         try 
381                           let ms, t = aux (context,k,in_scope) ms t in 
382                           ms, tbr, t::tl
383                         with
384                         | NotInTheList | MetaSubstFailure _ -> ms, j::tbr, tl
385                   in
386                   let (metasenv, subst), to_be_r, lc1' = deliftl [] 1 ms lc1 in
387 (*
388                   prerr_endline ("TO BE RESTRICTED: " ^ 
389                    (String.concat "," (List.map string_of_int to_be_r)));
390 *)
391                   let l1 = pack_lc (0, NCic.Ctx lc1') in
392 (*
393                   prerr_endline ("newmeta:" ^ NCicPp.ppterm
394                    ~metasenv ~subst ~context (NCic.Meta (999,l1)));
395 *)
396                   if to_be_r = [] then
397                     (metasenv, subst), 
398                     (if lc1' = lc1 then orig else NCic.Meta (i,l1))
399                   else
400                     let metasenv, subst, newmeta = 
401                       restrict metasenv subst i to_be_r in
402                     (metasenv, subst), NCic.Meta(newmeta,l1))
403
404     | t -> 
405         NCicUntrusted.map_term_fold_a 
406           (fun e (c,k,s) -> (e::c,k+1,s)) (context,k,in_scope) aux ms t
407   in
408    try aux (context,0,0) (metasenv,subst) t
409    with NotInTheList ->
410       (* This is the case where we fail even first order unification. *)
411       (* The reason is that our delift function is weaker than first  *)
412       (* order (in the sense of alpha-conversion). See comment above  *)
413       (* related to the delift function.                              *)
414       let msg = (lazy (Printf.sprintf
415         ("Error trying to abstract %s over [%s]: the algorithm only tried to "^^
416         "abstract over bound variables") (NCicPp.ppterm ~metasenv ~subst
417         ~context t) (String.concat "; " (List.map (NCicPp.ppterm ~metasenv
418         ~subst ~context) (let shift, lc = l in List.map (NCicSubstitution.lift
419         shift) (NCicUtils.expand_local_context lc))))))
420       in
421       let shift, lc = l in
422       let lc = NCicUtils.expand_local_context lc in
423       let l = List.map (NCicSubstitution.lift shift) lc in
424        if
425         List.exists (fun t-> NCicUntrusted.metas_of_term subst context t <> [])l
426        then
427         raise (Uncertain msg)
428        else
429         raise (MetaSubstFailure msg)
430 ;;
431
432 let mk_meta ?name metasenv context ty = 
433   let tyof = function Some s -> Some ("typeof_"^s) | None -> None in
434   let rec mk_meta name n metasenv context = function
435   | `WithType ty ->
436     let len = List.length context in
437     let menv_entry = (n, (name, context, ty)) in
438     menv_entry :: metasenv, n, NCic.Meta (n, (0,NCic.Irl len)), ty
439   | `Sort ->
440     let ty = NCic.Implicit (`Typeof n) in
441     mk_meta (tyof name) n metasenv [] (`WithType ty)
442   | `Type ->
443     let metasenv, _, ty, _ = 
444       mk_meta (tyof name) (newmeta ()) metasenv context `Sort in
445     mk_meta name n metasenv context (`WithType ty)
446   | `Term ->
447     let metasenv, _, ty, _ = 
448       mk_meta (tyof name) (newmeta ()) metasenv context `Type in
449     mk_meta name n metasenv context (`WithType ty)
450   in
451     mk_meta name (newmeta ()) metasenv context ty
452 ;;
453
454 let saturate ?(delta=0) metasenv subst context ty goal_arity =
455  assert (goal_arity >= 0);
456   let rec aux metasenv = function
457    | NCic.Prod (name,s,t) as ty ->
458        let metasenv1, _, arg,_ = 
459           mk_meta ~name:name metasenv context (`WithType s) in            
460        let t, metasenv1, args, pno = 
461            aux metasenv1 (NCicSubstitution.subst arg t) 
462        in
463        if pno + 1 = goal_arity then
464          ty, metasenv, [], goal_arity+1
465        else
466          t, metasenv1, arg::args, pno+1
467    | ty ->
468         match NCicReduction.whd ~subst context ty ~delta with
469         | NCic.Prod _ as ty -> aux metasenv ty
470         | ty -> ty, metasenv, [], 0
471   in
472   let res, newmetasenv, arguments, _ = aux metasenv ty in
473   res, newmetasenv, arguments
474 ;;