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