]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicMetaSubst.ml
psubst for metas fixed again
[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 let mk_restricted_irl shift len restrictions =
183   let rec aux n =
184     if n = 0 then 0 else
185      if List.mem (n+shift) restrictions then aux (n-1)
186      else 1+aux (n-1)
187   in
188     pack_lc (shift, NCic.Irl (aux len))
189 ;;
190
191
192 let mk_perforated_irl shift len restrictions =
193   let rec aux n =
194     if n = 0 then [] else
195      if List.mem (n+shift) restrictions then aux (n-1)
196      else (NCic.Rel n) :: aux (n-1)
197   in
198     pack_lc (shift, NCic.Ctx (List.rev (aux len)))
199 ;;
200
201 exception Occur;;
202
203 let rec force_does_not_occur metasenv subst restrictions t =
204  let rec aux k ms = function
205     | NCic.Rel r when List.mem (r - k) restrictions -> raise Occur
206     | NCic.Rel r as orig ->
207         let amount = 
208           List.length (List.filter (fun x -> x < r - k) restrictions) 
209         in
210         if amount > 0 then ms, NCic.Rel (r - amount) else ms, orig
211     | NCic.Meta (n, l) as orig ->
212        (* we ignore the subst since restrict will take care of already
213         * instantiated/restricted metavariabels *)
214        let (metasenv,subst as ms), restrictions_for_n, l' =
215          match l with
216          | shift, NCic.Irl len -> 
217              let restrictions = 
218                List.filter 
219                 (fun i -> i > shift && i <= shift + len) restrictions in
220              ms, restrictions, mk_restricted_irl shift len restrictions
221          | shift, NCic.Ctx l ->
222             let ms, _, restrictions_for_n, l =
223              List.fold_right
224                (fun t (ms, i, restrictions_for_n, l) ->
225                  try 
226                    let ms, t = aux (k-shift) ms t in
227                    ms, i-1, restrictions_for_n, t::l
228                  with Occur ->
229                    ms, i-1, i::restrictions_for_n, l)
230                l (ms, List.length l, [], [])
231             in
232              ms, restrictions_for_n, pack_lc (shift, NCic.Ctx l)
233        in
234        if restrictions_for_n = [] then
235          ms, if l = l' then orig else NCic.Meta (n, l')
236        else
237          let metasenv, subst, newmeta = 
238            restrict metasenv subst n restrictions_for_n 
239          in
240            (metasenv, subst), NCic.Meta (newmeta, l')
241     | t -> NCicUntrusted.map_term_fold_a (fun _ k -> k+1) k aux ms t
242  in
243    aux 0 (metasenv,subst) t 
244
245 and force_does_not_occur_in_context metasenv subst restrictions = function
246   | name, NCic.Decl t as orig ->
247       let (metasenv, subst), t' =
248         force_does_not_occur metasenv subst restrictions t in
249       metasenv, subst, (if t == t' then orig else (name,NCic.Decl t'))
250   | name, NCic.Def (bo, ty) as orig ->
251       let (metasenv, subst), bo' =
252         force_does_not_occur metasenv subst restrictions bo in
253       let (metasenv, subst), ty' =
254         force_does_not_occur metasenv subst restrictions ty in
255       metasenv, subst, 
256        (if bo == bo' && ty == ty' then orig else (name, NCic.Def (bo', ty')))
257
258 and erase_in_context metasenv subst pos restrictions = function
259   | [] -> metasenv, subst, restrictions, []
260   | hd::tl as orig ->
261       let metasenv, subst, restricted, tl' = 
262         erase_in_context metasenv subst (pos+1) restrictions tl in
263       if List.mem pos restricted then
264         metasenv, subst, restricted, tl'
265       else
266         try
267           let metasenv, subst, hd' =
268             let delifted_restricted = 
269               List.map ((+) ~-pos) (List.filter ((<=) pos) restricted) in
270             force_does_not_occur_in_context 
271               metasenv subst delifted_restricted hd
272           in
273            metasenv, subst, restricted, 
274             (if hd' == hd && tl' == tl then orig else (hd' :: tl'))
275         with Occur ->
276             metasenv, subst, (pos :: restricted), tl'
277
278 and restrict metasenv subst i restrictions =
279   assert (restrictions <> []);
280   try 
281     let name, ctx, bo, ty = NCicUtils.lookup_subst i subst in
282       try 
283         let metasenv, subst, restrictions, newctx = 
284           erase_in_context metasenv subst 1 restrictions ctx in
285         let (metasenv, subst), newty =  
286           force_does_not_occur metasenv subst restrictions ty in
287         let (metasenv, subst), newbo =  
288           force_does_not_occur metasenv subst restrictions bo in
289         let j = newmeta () in
290         let subst_entry_j = j, (name, newctx, newty, newbo) in
291         let reloc_irl = mk_perforated_irl 0 (List.length ctx) restrictions in
292         let subst_entry_i = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
293         metasenv,
294         subst_entry_j :: List.map 
295           (fun (n,_) as orig -> if i = n then subst_entry_i else orig) subst,
296         j
297       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
298             ("Cannot restrict the context of the metavariable ?%d over "^^
299             "the hypotheses %s since ?%d is already instantiated "^^
300             "with %s and at least one of the hypotheses occurs in "^^
301             "the substituted term") i  (String.concat ", " 
302             (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)) i
303             (NCicPp.ppterm ~metasenv ~subst ~context:ctx bo))))
304   with NCicUtils.Subst_not_found _ -> 
305     try 
306       let name, ctx, ty = NCicUtils.lookup_meta i metasenv in
307       try
308         let metasenv, subst, restrictions, newctx = 
309           erase_in_context metasenv subst 1 restrictions ctx in
310         let (metasenv, subst), newty =  
311           force_does_not_occur metasenv subst restrictions ty in
312         let j = newmeta () in
313         let metasenv_entry = j, (name, newctx, newty) in
314         let reloc_irl = 
315           mk_perforated_irl 0 (List.length ctx) restrictions in
316         let subst_entry = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
317         List.map 
318           (fun (n,_) as orig -> if i = n then metasenv_entry else orig) 
319           metasenv,
320         subst_entry :: subst, j
321       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
322           ("Cannot restrict the context of the metavariable ?%d "^^
323           "over the hypotheses %s since metavariable's type depends "^^
324           "on at least one of them") i (String.concat ", " 
325           (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)))))
326     with 
327     | NCicUtils.Meta_not_found _ -> assert false
328 ;;
329
330 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
331    otherwise the occur check does not make sense in case of unification
332    of ?n with ?n *)
333 let delift metasenv subst context n l t =
334   let rec aux k (metasenv, subst as ms) = function
335     | NCic.Rel n as t when n <= k -> ms, t
336     | NCic.Rel n -> 
337         (try
338           match List.nth context (n-k-1) with
339           | _,NCic.Def (bo,_) -> 
340                 (try ms, NCic.Rel ((position (n-k) l) + k)
341                  with NotInTheList ->
342                 (* CSC: This bit of reduction hurts performances since it is
343                  * possible to  have an exponential explosion of the size of the
344                  * proof. required for nat/nth_prime.ma *)
345                   aux k ms (NCicSubstitution.lift n bo))
346           | _,NCic.Decl _ -> ms, NCic.Rel ((position (n-k) l) + k)
347         with Failure _ -> assert false) (*Unbound variable found in delift*)
348     | NCic.Meta (_,(_,(NCic.Irl 0| NCic.Ctx []))) as orig -> ms, orig
349     | NCic.Meta (i,l1) as orig ->
350         (try
351            let _,_,t,_ = NCicUtils.lookup_subst i subst in
352            aux k ms (NCicSubstitution.subst_meta l1 t)
353          with NCicUtils.Subst_not_found _ ->
354            (* see the top level invariant *)
355            if (i = n) then 
356             raise (MetaSubstFailure (lazy (Printf.sprintf (
357               "Cannot unify the metavariable ?%d with a term that has "^^
358               "as subterm %s in which the same metavariable "^^
359               "occurs (occur check)") i 
360                (NCicPp.ppterm ~context ~metasenv ~subst t))))
361            else
362               let shift1,lc1 = l1 in
363               let shift,lc = l in
364               let shift = shift + k in
365               let _ = prerr_endline ("XXX restringo " ^ string_of_int i) in
366               match lc, lc1 with
367               | NCic.Irl len, NCic.Irl len1 
368                 when shift1 + len1 < shift || shift1 > shift + len ->
369                         prerr_endline "WWW 1";
370                   let restrictions = HExtlib.list_seq 1 (len1 + 1) in
371                   let metasenv, subst, newmeta = 
372                      restrict metasenv subst i restrictions 
373                   in
374                   (metasenv, subst), 
375                     NCic.Meta (newmeta, (0,NCic.Irl (max 0 (k-shift1))))
376               | NCic.Irl len, NCic.Irl len1 
377                 when shift1 < shift || len1 + shift1 > len + shift ->
378                   (* C. Hoare. Premature optimization is the root of all evil*)
379                         prerr_endline ("WWW 2 : " ^ string_of_int i);
380                   let stop = shift + len in
381                   let stop1 = shift1 + len1 in
382                   let low_gap = max 0 (shift - shift1) in
383                   let high_gap = max 0 (stop1 - stop) in
384                   let restrictions = 
385                      HExtlib.list_seq (k+1-shift1) (low_gap + 1) @
386                      HExtlib.list_seq (len1 - high_gap + 1) (len1 + 1)
387                   in
388                     let metasenv, subst, newmeta = 
389                        restrict metasenv subst i restrictions 
390                     in
391                   prerr_endline ("RESTRICTIONS FOR: " ^ 
392                   NCicPp.ppterm ~metasenv ~subst ~context:[] 
393                     (NCic.Meta (i,l1)) ^ 
394                     " that was part of a term unified with " ^
395                     NCicPp.ppterm ~metasenv ~subst ~context:[] 
396                     (NCic.Meta (n,l)) ^ " ====> " ^ 
397                     String.concat "," (List.map string_of_int restrictions)
398                     ^ "\nMENV:\n" ^ NCicPp.ppmetasenv ~subst metasenv
399                     ^ "\nSUBST:\n" ^ NCicPp.ppsubst subst ~metasenv
400                     );
401                   let newlc = 
402                     assert (if shift1 > k then shift1 + low_gap - shift = 0 else
403                     true);
404                     NCic.Irl (len1 - low_gap - high_gap + max 0 (k - shift1)) in
405                   let meta = 
406                      NCic.Meta(newmeta,(shift1 + low_gap - shift, newlc))
407                   in
408                     (metasenv, subst), meta
409                   
410               | NCic.Irl _, NCic.Irl _ when shift = 0 -> ms, orig
411               | NCic.Irl _, NCic.Irl _ ->
412                    ms, NCic.Meta (i, (max 0 (shift1 - shift), lc1))
413               | _ ->
414                   let lc1 = NCicUtils.expand_local_context lc1 in
415                   let rec deliftl tbr j ms = function
416                     | [] -> ms, tbr, []
417                     | t::tl ->
418                         let ms, tbr, tl = deliftl tbr (j+1) ms tl in
419                         try 
420                           let ms, t = aux (k-shift1) ms t in 
421                           ms, tbr, t::tl
422                         with
423                         | NotInTheList | MetaSubstFailure _ -> ms, j::tbr, tl
424                   in
425                   let (metasenv, subst), to_be_r, lc1' = deliftl [] 1 ms lc1 in
426 (*
427                   prerr_endline ("TO BE RESTRICTED: " ^ 
428                    (String.concat "," (List.map string_of_int to_be_r)));
429 *)
430                   let l1 = pack_lc (shift, NCic.Ctx lc1') in
431                   if to_be_r = [] then
432                     (metasenv, subst), 
433                     (if lc1' = lc1 then orig else NCic.Meta (i,l1))
434                   else
435                     let metasenv, subst, newmeta = 
436                       restrict metasenv subst i to_be_r in
437                     (metasenv, subst), NCic.Meta(newmeta,l1))
438     | t -> NCicUntrusted.map_term_fold_a (fun _ k -> k+1) k aux ms t
439   in
440    try aux 0 (metasenv,subst) t
441    with NotInTheList ->
442       (* This is the case where we fail even first order unification. *)
443       (* The reason is that our delift function is weaker than first  *)
444       (* order (in the sense of alpha-conversion). See comment above  *)
445       (* related to the delift function.                              *)
446       let msg = (lazy (Printf.sprintf
447         ("Error trying to abstract %s over [%s]: the algorithm only tried to "^^
448         "abstract over bound variables") (NCicPp.ppterm ~metasenv ~subst
449         ~context t) (String.concat "; " (List.map (NCicPp.ppterm ~metasenv
450         ~subst ~context) (let shift, lc = l in List.map (NCicSubstitution.lift
451         shift) (NCicUtils.expand_local_context lc))))))
452       in
453       let shift, lc = l in
454       let lc = NCicUtils.expand_local_context lc in
455       let l = List.map (NCicSubstitution.lift shift) lc in
456        if
457          List.exists
458           (fun t -> NCicUntrusted.metas_of_term subst context t = [])
459             l
460        then
461         raise (Uncertain msg)
462        else
463         raise (MetaSubstFailure msg)
464 ;;
465
466 (*
467 (* delifts a term t of n levels strating from k, that is changes (Rel m)
468  * to (Rel (m - n)) when m > (k + n). if k <= m < k + n delift fails
469  *)
470 let delift_rels_from subst metasenv k n =
471  let rec liftaux subst metasenv k =
472   let module C = Cic in
473    function
474       C.Rel m as t ->
475        if m < k then
476         t, subst, metasenv
477        else if m < k + n then
478          raise DeliftingARelWouldCaptureAFreeVariable
479        else
480         C.Rel (m - n), subst, metasenv
481     | C.Var (uri,exp_named_subst) ->
482        let exp_named_subst',subst,metasenv = 
483         List.fold_right
484          (fun (uri,t) (l,subst,metasenv) ->
485            let t',subst,metasenv = liftaux subst metasenv k t in
486             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
487        in
488         C.Var (uri,exp_named_subst'),subst,metasenv
489     | C.Meta (i,l) ->
490         (try
491           let (_, t,_) = lookup_subst i subst in
492            liftaux subst metasenv k (CicSubstitution.subst_meta l t)
493          with CicUtil.Subst_not_found _ -> 
494           let l',to_be_restricted,subst,metasenv =
495            let rec aux con l subst metasenv =
496             match l with
497                [] -> [],[],subst,metasenv
498              | he::tl ->
499                 let tl',to_be_restricted,subst,metasenv =
500                  aux (con + 1) tl subst metasenv in
501                 let he',more_to_be_restricted,subst,metasenv =
502                  match he with
503                     None -> None,[],subst,metasenv
504                   | Some t ->
505                      try
506                       let t',subst,metasenv = liftaux subst metasenv k t in
507                        Some t',[],subst,metasenv
508                      with
509                       DeliftingARelWouldCaptureAFreeVariable ->
510                        None,[i,con],subst,metasenv
511                 in
512                  he'::tl',more_to_be_restricted@to_be_restricted,subst,metasenv
513            in
514             aux 1 l subst metasenv in
515           let metasenv,subst = restrict subst to_be_restricted metasenv in
516            C.Meta(i,l'),subst,metasenv)
517     | C.Sort _ as t -> t,subst,metasenv
518     | C.Implicit _ as t -> t,subst,metasenv
519     | C.Cast (te,ty) ->
520        let te',subst,metasenv = liftaux subst metasenv k te in
521        let ty',subst,metasenv = liftaux subst metasenv k ty in
522         C.Cast (te',ty'),subst,metasenv
523     | C.Prod (n,s,t) ->
524        let s',subst,metasenv = liftaux subst metasenv k s in
525        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
526         C.Prod (n,s',t'),subst,metasenv
527     | C.Lambda (n,s,t) ->
528        let s',subst,metasenv = liftaux subst metasenv k s in
529        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
530         C.Lambda (n,s',t'),subst,metasenv
531     | C.LetIn (n,s,ty,t) ->
532        let s',subst,metasenv = liftaux subst metasenv k s in
533        let ty',subst,metasenv = liftaux subst metasenv k ty in
534        let t',subst,metasenv = liftaux subst metasenv (k+1) t in
535         C.LetIn (n,s',ty',t'),subst,metasenv
536     | C.Appl l ->
537        let l',subst,metasenv =
538         List.fold_right
539          (fun t (l,subst,metasenv) ->
540            let t',subst,metasenv = liftaux subst metasenv k t in
541             t'::l,subst,metasenv) l ([],subst,metasenv) in
542        C.Appl l',subst,metasenv
543     | C.Const (uri,exp_named_subst) ->
544        let exp_named_subst',subst,metasenv = 
545         List.fold_right
546          (fun (uri,t) (l,subst,metasenv) ->
547            let t',subst,metasenv = liftaux subst metasenv k t in
548             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
549        in
550         C.Const (uri,exp_named_subst'),subst,metasenv
551     | C.MutInd (uri,tyno,exp_named_subst) ->
552        let exp_named_subst',subst,metasenv = 
553         List.fold_right
554          (fun (uri,t) (l,subst,metasenv) ->
555            let t',subst,metasenv = liftaux subst metasenv k t in
556             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
557        in
558         C.MutInd (uri,tyno,exp_named_subst'),subst,metasenv
559     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
560        let exp_named_subst',subst,metasenv = 
561         List.fold_right
562          (fun (uri,t) (l,subst,metasenv) ->
563            let t',subst,metasenv = liftaux subst metasenv k t in
564             (uri,t')::l,subst,metasenv) exp_named_subst ([],subst,metasenv)
565        in
566         C.MutConstruct (uri,tyno,consno,exp_named_subst'),subst,metasenv
567     | C.MutCase (sp,i,outty,t,pl) ->
568        let outty',subst,metasenv = liftaux subst metasenv k outty in
569        let t',subst,metasenv = liftaux subst metasenv k t in
570        let pl',subst,metasenv =
571         List.fold_right
572          (fun t (l,subst,metasenv) ->
573            let t',subst,metasenv = liftaux subst metasenv k t in
574             t'::l,subst,metasenv) pl ([],subst,metasenv)
575        in
576         C.MutCase (sp,i,outty',t',pl'),subst,metasenv
577     | C.Fix (i, fl) ->
578        let len = List.length fl in
579        let liftedfl,subst,metasenv =
580         List.fold_right
581          (fun (name, i, ty, bo) (l,subst,metasenv) ->
582            let ty',subst,metasenv = liftaux subst metasenv k ty in
583            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
584             (name,i,ty',bo')::l,subst,metasenv
585          ) fl ([],subst,metasenv)
586        in
587         C.Fix (i, liftedfl),subst,metasenv
588     | C.CoFix (i, fl) ->
589        let len = List.length fl in
590        let liftedfl,subst,metasenv =
591         List.fold_right
592          (fun (name, ty, bo) (l,subst,metasenv) ->
593            let ty',subst,metasenv = liftaux subst metasenv k ty in
594            let bo',subst,metasenv = liftaux subst metasenv (k+len) bo in
595             (name,ty',bo')::l,subst,metasenv
596          ) fl ([],subst,metasenv)
597        in
598         C.CoFix (i, liftedfl),subst,metasenv
599  in
600   liftaux subst metasenv k
601
602 let delift_rels subst metasenv n t =
603   delift_rels_from subst metasenv 1 n t
604 *) 
605
606 let mk_meta ?name metasenv context ty = 
607   match ty with
608   | `Typeless ->
609     let n = newmeta () in
610     let ty = NCic.Implicit (`Typeof n) in
611     let menv_entry = (n, (name, context, ty)) in
612     menv_entry :: metasenv,NCic.Meta (n, (0,NCic.Irl (List.length context))), ty
613   | `Type 
614   | `Term ->
615     let context_for_ty = if ty = `Type then [] else context in
616     let n = newmeta () in
617     let ty_menv_entry = (n, (name,context_for_ty, NCic.Implicit (`Typeof n))) in
618     let m = newmeta () in
619     let ty = NCic.Meta (n, (0,NCic.Irl (List.length context_for_ty))) in
620     let menv_entry = (m, (name, context, ty)) in
621     menv_entry :: ty_menv_entry :: metasenv, 
622       NCic.Meta (m, (0,NCic.Irl (List.length context))), ty
623   | `WithType ty ->
624     let n = newmeta () in
625     let len = List.length context in
626     let menv_entry = (n, (name, context, ty)) in
627     menv_entry :: metasenv, NCic.Meta (n, (0,NCic.Irl len)), ty
628 ;;
629
630 let saturate ?(delta=0) metasenv context ty goal_arity =
631  assert (goal_arity >= 0);
632   let rec aux metasenv = function
633    | NCic.Prod (name,s,t) ->
634        let metasenv1, arg,_ = 
635           mk_meta ~name:name metasenv context (`WithType s) in            
636        let t, metasenv1, args, pno = 
637            aux metasenv1 (NCicSubstitution.subst arg t) 
638        in
639        if pno + 1 = goal_arity then
640          ty, metasenv, [], goal_arity+1
641        else
642          t, metasenv1, arg::args, pno+1
643    | ty ->
644         match NCicReduction.whd context ty ~delta with
645         | NCic.Prod _ as ty -> aux metasenv ty
646         | ty -> ty, metasenv, [], 0
647   in
648   let res, newmetasenv, arguments, _ = aux metasenv ty in
649   res, newmetasenv, arguments
650 ;;