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