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