]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_refiner/nCicMetaSubst.ml
Delift used to produce not well typed substitutions. In turn, this
[helm.git] / matita / 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 let debug = ref false;;
15 let indent = ref "";;
16 let times = ref [];;
17 let pp s =
18  if !debug then
19   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
20 ;;
21 let inside c =
22  if !debug then
23   begin
24    let time1 = Unix.gettimeofday () in
25    indent := !indent ^ String.make 1 c;
26    times := time1 :: !times;
27    prerr_endline ("{{{" ^ !indent ^ " ")
28   end
29 ;;
30 let outside exc_opt =
31  if !debug then
32   begin
33    let time2 = Unix.gettimeofday () in
34    let time1 =
35     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
36    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
37    (match exc_opt with
38    | Some e ->  prerr_endline ("exception raised: " ^ Printexc.to_string e)
39    | None -> ());
40    try
41     indent := String.sub !indent 0 (String.length !indent -1)
42    with
43     Invalid_argument _ -> indent := "??"; ()
44   end
45 ;;
46
47 exception MetaSubstFailure of string Lazy.t
48 exception Uncertain of string Lazy.t
49
50 let newmeta,maxmeta = 
51   let maxmeta = ref 0 in
52   (fun () -> incr maxmeta; !maxmeta),
53   (fun () -> !maxmeta)
54 ;;
55
56 exception NotFound of [`NotInTheList | `NotWellTyped];;
57
58 let position to_skip n (shift, lc) =
59   match lc with
60   | NCic.Irl _ when to_skip > 0 -> assert false  (* unclear to me *)
61   | NCic.Irl len when n <= shift || n > shift + len ->
62      raise (NotFound `NotInTheList)
63   | NCic.Irl _ -> n - shift
64   | NCic.Ctx tl ->
65       let rec aux to_skip k = function 
66          | [] -> raise (NotFound `NotInTheList)
67          | _ :: tl when to_skip > 0 -> aux (to_skip - 1) (k+1) tl
68          | (NCic.Rel m)::_ when m + shift = n -> k
69          | _::tl -> aux to_skip (k+1) tl 
70       in
71        aux to_skip 1 tl
72 ;;
73
74 let pack_lc orig = 
75   let rec are_contiguous k = function
76     | [] -> true
77     | (NCic.Rel j) :: tl when j = k+1 -> are_contiguous j tl
78     | _ -> false
79   in
80   match orig with
81   | _, NCic.Ctx [] -> 0, NCic.Irl 0
82   | shift, NCic.Ctx (NCic.Rel k::tl as l) when are_contiguous k tl ->
83       shift+k-1, NCic.Irl (List.length l)
84   | _ -> orig
85 ;;
86
87
88
89 let mk_perforated_irl shift len restrictions =
90   let rec aux n =
91     if n = 0 then [] else
92      if List.mem (n+shift) restrictions then aux (n-1)
93      else (NCic.Rel n) :: aux (n-1)
94   in
95     pack_lc (shift, NCic.Ctx (List.rev (aux len)))
96 ;;
97
98 exception Occur;;
99
100 let purge_restricted restrictions more_restrictions l =
101  if more_restrictions = [] then l
102  else
103   begin
104    pp (lazy ("TO BE RESTRICTED: " ^ 
105     (String.concat "," (List.map string_of_int restrictions))));
106    pp (lazy ("MORE RESTRICTIONS: " ^ 
107     (String.concat "," (List.map string_of_int more_restrictions))));
108    let shift,lc = l in
109    let lc = NCicUtils.expand_local_context lc in
110     let rec aux n lc =
111      match lc with
112         [] -> []
113       | _ when List.mem n restrictions -> aux (n+1) lc
114       | _::tl when List.mem n more_restrictions -> aux (n+1) tl
115       | he::tl -> he::aux (n+1) tl
116     in
117     pack_lc (shift, NCic.Ctx (aux 1 lc))
118   end
119 ;;
120
121 let rec force_does_not_occur status metasenv subst restrictions t =
122  let rec aux k ms = function
123     | NCic.Rel r when List.mem (r - k) restrictions -> raise Occur
124     | NCic.Rel r as orig ->
125         let amount = 
126           List.length (List.filter (fun x -> x < r - k) restrictions) 
127         in
128         if amount > 0 then ms, NCic.Rel (r - amount) else ms, orig
129     | NCic.Meta (n, (shift,lc as l)) as orig ->
130        (try
131          let _,_,bo,_ = NCicUtils.lookup_subst n subst in
132           aux k ms (NCicSubstitution.subst_meta status l bo)
133         with
134          NCicUtils.Subst_not_found _ ->
135           (* we ignore the subst since restrict will take care of already
136            * instantiated/restricted metavariabels *)
137           let l = NCicUtils.expand_local_context lc in
138           let sl = List.map (NCicSubstitution.lift status shift) l in 
139           let (metasenv,subst as ms), _, restrictions_for_n, l' =
140              List.fold_right
141                (fun t (ms, i, restrictions_for_n, l) ->
142                  try 
143               (*pp (lazy ("L'ORLO DELLA FOSSA: k= " ^ string_of_int k ^ " shift=" ^
144                string_of_int shift ^ " t=" ^ status#ppterm ~metasenv ~subst ~context:[] t));*)
145                    let ms, t = aux k ms t in
146               (*pp (lazy ("LA FOSSA: " ^ status#ppterm ~metasenv ~subst ~context:[] t));*)
147                    ms, i-1, restrictions_for_n, t::l
148                  with Occur ->
149                    ms, i-1, i::restrictions_for_n, l)
150                sl (ms, List.length l, [], [])
151           in
152           if restrictions_for_n = [] then
153             ms, if sl = l' then orig else (
154                 (*pp (lazy ("FINITO: " ^ status#ppterm ~metasenv:[] ~subst:[]
155                   ~context:[] (NCic.Meta (n,pack_lc (0, NCic.Ctx l')))));*)
156               NCic.Meta (n, pack_lc (0, NCic.Ctx l'))
157             )
158           else
159             let l' = pack_lc (0, NCic.Ctx l') in
160             let _ = pp (lazy ("restrictions for n are:" ^ String.concat "," (List.map string_of_int restrictions_for_n))) in
161             let metasenv, subst, newmeta, more_restricted = 
162               restrict status metasenv subst n restrictions_for_n in
163             let _ = pp (lazy ("more restricted: " ^String.concat "," (List.map string_of_int more_restricted))) in
164             let l' = purge_restricted restrictions more_restricted l' in
165               (metasenv, subst), NCic.Meta (newmeta, l'))
166     | t -> NCicUntrusted.map_term_fold_a status (fun _ k -> k+1) k aux ms t
167  in
168    aux 0 (metasenv,subst) t 
169
170 and force_does_not_occur_in_context status metasenv subst restrictions = function
171   | name, NCic.Decl t as orig ->
172       (* pp (lazy ("CCC: hd is" ^ status#ppterm ~metasenv:[] ~subst:[] ~context:[] t ^
173       "\nCCC: restrictions are:" ^ String.concat "," (List.map string_of_int restrictions)));*)
174       let (metasenv, subst), t' =
175         force_does_not_occur status metasenv subst restrictions t in
176       metasenv, subst, (if t == t' then orig else (name,NCic.Decl t'))
177   | name, NCic.Def (bo, ty) as orig ->
178       let (metasenv, subst), bo' =
179         force_does_not_occur status metasenv subst restrictions bo in
180       let (metasenv, subst), ty' =
181         force_does_not_occur status metasenv subst restrictions ty in
182       metasenv, subst, 
183        (if bo == bo' && ty == ty' then orig else (name, NCic.Def (bo', ty')))
184
185 and erase_in_context status metasenv subst pos restrictions = function
186   | [] -> metasenv, subst, restrictions, []
187   | hd::tl as orig ->
188       let metasenv, subst, restricted, tl' = 
189         erase_in_context status metasenv subst (pos+1) restrictions tl in
190       if List.mem pos restricted then
191         metasenv, subst, restricted, tl'
192       else
193         try
194           let metasenv, subst, hd' =
195             let delifted_restricted = 
196               List.map ((+) ~-pos) (List.filter ((<=) pos) restricted) in
197             force_does_not_occur_in_context 
198               status metasenv subst delifted_restricted hd
199           in
200            metasenv, subst, restricted, 
201             (if hd' == hd && tl' == tl then orig else (hd' :: tl'))
202         with Occur ->
203             metasenv, subst, (pos :: restricted), tl'
204
205 and restrict status metasenv subst i (restrictions as orig) =
206   assert (restrictions <> []);
207   try 
208     let name, ctx, bo, ty = NCicUtils.lookup_subst i subst in
209       try 
210         let metasenv, subst, restrictions, newctx = 
211           erase_in_context status metasenv subst 1 restrictions ctx in
212         let (metasenv, subst), newty =  
213           force_does_not_occur status metasenv subst restrictions ty in
214         let (metasenv, subst), newbo =  
215           force_does_not_occur status metasenv subst restrictions bo in
216         let j = newmeta () in
217         let subst_entry_j = j, (name, newctx, newbo, newty) in
218         let reloc_irl = mk_perforated_irl 0 (List.length ctx) restrictions in
219         let subst_entry_i = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
220         let new_subst = 
221           subst_entry_j :: List.map 
222             (fun (n,_) as orig -> if i = n then subst_entry_i else orig) subst
223         in
224         let diff = List.filter (fun x -> not (List.mem x orig)) restrictions in
225         metasenv, new_subst, j, diff
226       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
227             ("Cannot restrict the context of the metavariable ?%d over "^^
228             "the hypotheses %s since ?%d is already instantiated "^^
229             "with %s and at least one of the hypotheses occurs in "^^
230             "the substituted term") i  (String.concat ", " 
231             (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)) i
232             (status#ppterm ~metasenv ~subst ~context:ctx bo))))
233   with NCicUtils.Subst_not_found _ -> 
234     try 
235       let name, ctx, ty = NCicUtils.lookup_meta i metasenv in
236       try
237         let metasenv, subst, restrictions, newctx = 
238           erase_in_context status metasenv subst 1 restrictions ctx in
239         let (metasenv, subst), newty =  
240           force_does_not_occur status metasenv subst restrictions ty in
241         let j = newmeta () in
242         let metasenv_entry = j, (name, newctx, newty) in
243         let reloc_irl = 
244           mk_perforated_irl 0 (List.length ctx) restrictions in
245         let subst_entry = i, (name, ctx, NCic.Meta (j, reloc_irl), ty) in
246          (* pp (lazy ("BBB: dopo1 \n" ^  NCicPp.ppsubst ~metasenv [subst_entry]));
247           pp (lazy ("BBB: dopo2 \n" ^  NCicPp.ppsubst ~metasenv (subst_entry::subst)));
248           pp (lazy ("BBB: dopo metasenv\n" ^  NCicPp.ppmetasenv ~subst [metasenv_entry]));*)
249         let diff = List.filter (fun x -> not (List.mem x orig)) restrictions in
250         List.map 
251           (fun (n,_) as orig -> if i = n then metasenv_entry else orig) 
252           metasenv,
253         subst_entry :: subst, j, diff
254       with Occur -> raise (MetaSubstFailure (lazy (Printf.sprintf
255           ("Cannot restrict the context of the metavariable ?%d "^^
256           "over the hypotheses %s since metavariable's type depends "^^
257           "on at least one of them") i (String.concat ", " 
258           (List.map (fun x -> fst (List.nth ctx (x-1))) restrictions)))))
259     with 
260     | NCicUtils.Meta_not_found _ -> assert false
261 ;;
262
263 let rec is_flexible status context ~subst = function 
264   | NCic.Meta (i,_) ->
265       (try 
266         let _,_,t,_ = List.assoc i subst in
267         is_flexible status context ~subst t
268       with Not_found -> true)
269   | NCic.Appl (NCic.Meta (i,_) :: args)-> 
270       (try 
271         let _,_,t,_ = List.assoc i subst in
272         is_flexible status context ~subst 
273           (NCicReduction.head_beta_reduce status ~delta:max_int 
274             (NCic.Appl (t :: args)))
275       with Not_found -> true)
276    (* this is a cheap whd, it only performs zeta-reduction.
277     * 
278     * it works when the **omissis** disambiguation algorithm
279     * is run on `let x := K a b in t`, K is substituted for a 
280     * ? and thus in t metavariables have a flexible Rel
281     *)
282   | NCic.Rel i ->
283       (try
284          match List.nth context (i-1)
285          with 
286          | _,NCic.Def (bo,_) ->
287                is_flexible status context ~subst
288                  (NCicSubstitution.lift status i bo)
289          | _ -> false
290       with 
291       | Failure _ -> 
292           prerr_endline (Printf.sprintf "Rel %d inside context:\n%s" i  
293             (status#ppcontext ~subst ~metasenv:[] context));
294           assert false
295       | Invalid_argument _ -> assert false)
296   | _ -> false
297 ;;
298
299 let is_out_scope = function `OutScope _ -> true | _ -> false;;
300 let is_out_scope_tag = List.exists is_out_scope;;
301 let int_of_out_scope_tag tag = 
302  match List.filter is_out_scope tag with [`OutScope n] -> n | _ -> assert false
303 ;;
304
305
306 exception Found;;
307 exception TypeNotGood;;
308
309 (* INVARIANT: we suppose that t is not another occurrence of Meta(n,_), 
310    otherwise the occur check does not make sense in case of unification
311    of ?n with ?n *)
312 let delift status ~unify metasenv subst context n l t =
313   (*D*)  inside 'D'; try let rc =  
314   let is_in_scope_meta subst = function
315     | NCic.Meta (i,_) ->
316         (try 
317            let tag, _, _, _ = NCicUtils.lookup_subst i subst in 
318             List.mem `InScope tag
319         with NCicUtils.Subst_not_found _ -> false)
320     | _ -> false
321   in
322   let contains_in_scope subst t = 
323     let rec aux _ () = function
324       | NCic.Meta _ as t ->
325           if is_in_scope_meta subst t then raise Found
326           else ()
327       | t -> 
328           if is_in_scope_meta subst t then raise Found
329           else NCicUtils.fold (fun _ () -> ()) () aux () t
330     in
331     try aux () () t; false with Found -> true
332   in
333   let unify_list in_scope = 
334     match l with
335     | _, NCic.Irl _ -> fun _ _ _ _ _ -> None
336     | shift, NCic.Ctx l -> fun metasenv subst context k t ->
337        if is_flexible status context ~subst t || contains_in_scope subst t then None else
338          let lb = 
339            List.map (fun t -> 
340             let t = NCicSubstitution.lift status (k+shift) t in
341             t, is_flexible status context ~subst t) 
342            l 
343          in
344          HExtlib.list_findopt
345           (fun (li,flexible) i ->
346             if flexible || i < in_scope then None else
347              match unify metasenv subst context li t with
348              | Some (metasenv,subst) -> 
349                  Some ((metasenv, subst), NCic.Rel (i+1+k))
350              | None -> None)
351           lb
352   in
353   let rec aux (context,k,in_scope) (metasenv, subst as ms) t = 
354    match unify_list in_scope metasenv subst context k t with
355    | Some x -> x
356    | None -> 
357     match t with 
358     | NCic.Rel n as t when n <= k -> ms, t
359     | NCic.Rel n -> 
360         (try
361           match List.nth context (n-1) with
362           | _,NCic.Def (bo,_) -> 
363                 (try ms, NCic.Rel ((position in_scope (n-k) l) + k)
364                  with (NotFound `NotInTheList) ->
365                 (* CSC: This bit of reduction hurts performances since it is
366                  * possible to  have an exponential explosion of the size of the
367                  * proof. required for nat/nth_prime.ma *)
368                   aux (context,k,in_scope) ms (NCicSubstitution.lift status n bo))
369           | _,NCic.Decl _ -> ms, NCic.Rel ((position in_scope (n-k) l) + k)
370         with Failure _ -> assert false) (*Unbound variable found in delift*)
371     | NCic.Meta (i,_) when i=n ->
372          raise (MetaSubstFailure (lazy (Printf.sprintf (
373            "Cannot unify the metavariable ?%d with a term that has "^^
374            "as subterm %s in which the same metavariable "^^
375            "occurs (occur check)") i 
376             (status#ppterm ~context ~metasenv ~subst t))))
377     | NCic.Meta (i,l1) as orig ->
378         (try
379            let tag,c,t,ty = NCicUtils.lookup_subst i subst in
380            let in_scope, clear = 
381             if List.mem `InScope tag then 0, true
382             else if is_out_scope_tag tag then int_of_out_scope_tag tag,true
383             else in_scope, false
384            in
385            let ms = 
386              if not clear then ms
387              else 
388                metasenv, 
389                (i,([],c,t,ty)) :: List.filter (fun j,_ -> i <> j) subst
390            in
391            aux (context,k,in_scope) ms (NCicSubstitution.subst_meta status l1 t)
392          with NCicUtils.Subst_not_found _ ->
393            if snd l1 = NCic.Irl 0 || snd l1 = NCic.Ctx [] then ms, orig
394            else
395               let shift1,lc1 = l1 in
396               let shift,lc = l in
397               let shift = shift + k in
398               match lc, lc1 with
399               | NCic.Irl len, NCic.Irl len1 
400                 when shift1 + len1 < shift || shift1 > shift + len ->
401                   let restrictions = HExtlib.list_seq 1 (len1 + 1) in
402                   let metasenv, subst, newmeta, more_restricted = 
403                    restrict status metasenv subst i restrictions in
404                   let l' = (0,NCic.Irl (max 0 (k-shift1))) in
405                   let l' = purge_restricted restrictions more_restricted l' in
406                   (metasenv, subst),NCic.Meta (newmeta,l')
407               | NCic.Irl len, NCic.Irl len1 ->
408                   let low_restrictions, new_shift = 
409                     if k <= shift1 && shift1 < shift then 
410                       HExtlib.list_seq 1 (shift - shift1 + 1), k
411                     else if shift1 < k (* <= shift *) then
412                       let save_below = k - shift1 in
413                       HExtlib.list_seq (save_below + 1) (shift - shift1 + 1),
414                       shift1
415                     else [], shift1 - shift + k
416                   in
417                   let high_restrictions = 
418                     let last = shift + len in
419                     let last1 = shift1 + len1 in
420                     if last1 > last then
421                       let high_gap = last1 - last in
422                       HExtlib.list_seq (len1 - high_gap + 1) (len1 + 1)
423                     else []
424                   in
425                   let restrictions = low_restrictions @ high_restrictions in
426                   if restrictions = [] then
427                     if shift = k then ms, orig
428                     else ms, NCic.Meta (i, (new_shift, lc1))
429                   else
430                     let metasenv, subst, newmeta, more_restricted = 
431                      restrict status metasenv subst i restrictions in
432                     let newlc_len = len1 - List.length restrictions in 
433                     let l' = new_shift, NCic.Irl newlc_len in
434                     let l' = purge_restricted restrictions more_restricted l' in
435                     (metasenv, subst),NCic.Meta(newmeta,l')
436
437               | _ ->
438                   let lc1 = NCicUtils.expand_local_context lc1 in
439                   let lc1 = List.map (NCicSubstitution.lift status shift1) lc1 in
440                   let rec deliftl tbr j ms = function
441                     | [] -> ms, tbr, []
442                     | t::tl ->
443                         let ms, tbr, tl = deliftl tbr (j+1) ms tl in
444                         try 
445                           let ms, t = aux (context,k,in_scope) ms t in 
446                           ms, tbr, t::tl
447                         with
448                         | (NotFound `NotInTheList) | MetaSubstFailure _ -> ms, j::tbr, tl
449                   in
450                   let (metasenv, subst), to_be_r, lc1' = deliftl [] 1 ms lc1 in
451                   pp (lazy ("TO BE RESTRICTED: " ^ 
452                    (String.concat "," (List.map string_of_int to_be_r))));
453                   let l1 = pack_lc (0, NCic.Ctx lc1') in
454                   pp (lazy ("newmeta:" ^ status#ppterm
455                    ~metasenv ~subst ~context (NCic.Meta (999,l1))));
456                   pp (lazy (status#ppmetasenv ~subst metasenv));
457                   if to_be_r = [] then
458                     (metasenv, subst), 
459                     (if lc1' = lc1 then orig else NCic.Meta (i,l1))
460                   else
461                     let metasenv, subst, newmeta, more_restricted = 
462                      restrict status metasenv subst i to_be_r in
463                     let l1 = purge_restricted to_be_r more_restricted l1 in
464                      (metasenv, subst), NCic.Meta(newmeta,l1))
465
466     | t -> 
467         NCicUntrusted.map_term_fold_a status
468           (fun e (c,k,s) -> (e::c,k+1,s)) (context,k,in_scope) aux ms t
469   in
470 (*
471   prerr_endline (
472     "DELIFTO " ^ status#ppterm ~metasenv ~subst ~context t ^ " w.r.t. " ^
473     status#ppterm ~metasenv ~subst ~context (NCic.Meta(n,l)) ^ " i.e. " ^
474     String.concat ", " (List.map (status#ppterm ~metasenv ~subst ~context) ( 
475       let shift, lc = l in
476       (List.map (NCicSubstitution.lift status shift) 
477         (NCicUtils.expand_local_context lc))
478   )));
479 *)
480    try
481 (*assert (try n = -1 or (ignore(NCicUtils.lookup_meta n metasenv); true) with NCicUtils.Meta_not_found _ -> false);*)
482     let ((metasenv,subst),t) as res = aux (context,0,0) (metasenv,subst) t in
483     if (try n <> -1 && (ignore(NCicUtils.lookup_meta n metasenv); false)
484         with NCicUtils.Meta_not_found _ -> true)
485     then
486      let _,context,bo,_ = NCicUtils.lookup_subst n subst in
487       match unify metasenv subst context bo t with
488          None -> raise (NotFound `NotWellTyped)
489        | Some (metasenv,subst) -> (metasenv,subst),t
490     else
491     (try
492       let _,context,ty = NCicUtils.lookup_meta n metasenv in
493       let ty' =
494        match t with
495           NCic.Sort _ -> (* could be algebraic *) NCic.Implicit `Closed
496         | _ -> NCicTypeChecker.typeof status ~subst ~metasenv context t in
497        (match ty,ty' with
498            NCic.Implicit _,_ ->
499             (match ty' with
500                 NCic.Sort _ | NCic.Meta _ | NCic.Implicit _ -> res
501               | _ -> raise TypeNotGood)
502          | _,NCic.Implicit _ ->
503             (match ty with
504                 NCic.Sort _ | NCic.Meta _ | NCic.Implicit _ -> res
505               | _ -> raise TypeNotGood)
506          | _ ->
507            if
508             NCicReduction.are_convertible status ~metasenv ~subst context ty' ty
509            then
510             res
511            else
512             raise TypeNotGood)
513      with
514         NCicUtils.Meta_not_found _ ->
515          (* Fake metavariable used in NTacStatus and NCicRefiner :-( *)
516          assert (n = -1); res
517       | TypeNotGood
518       | NCicTypeChecker.AssertFailure _
519       | NCicReduction.AssertFailure _
520       | NCicTypeChecker.TypeCheckerFailure _ ->
521          raise (NotFound `NotWellTyped))
522    with NotFound reason ->
523       (* This is the case where we fail even first order unification. *)
524       (* The reason is that our delift function is weaker than first  *)
525       (* order (in the sense of alpha-conversion). See comment above  *)
526       (* related to the delift function.                              *)
527       let reason =
528        match reason with
529           `NotInTheList -> "some variable cannot be delifted"
530         | `NotWellTyped -> "the unifier found is not well typed" in
531       let msg = (lazy (Printf.sprintf
532         ("Error trying to abstract %s over [%s]: %s")
533         (status#ppterm ~metasenv ~subst
534         ~context t) (String.concat "; " (List.map (status#ppterm ~metasenv
535         ~subst ~context) (let shift, lc = l in List.map (NCicSubstitution.lift
536         status shift) (NCicUtils.expand_local_context lc)))) reason))
537       in
538       let shift, lc = l in
539       let lc = NCicUtils.expand_local_context lc in
540       let l = List.map (NCicSubstitution.lift status shift) lc in
541        if
542         List.exists (fun t-> NCicUntrusted.metas_of_term status subst context t <> [])l
543        then
544         raise (Uncertain msg)
545        else
546         raise (MetaSubstFailure msg)
547  (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
548 ;;
549
550 let mk_meta ?(attrs=[]) metasenv context ?with_type kind = 
551   assert(kind <> `IsSort || context = []);
552   let n = newmeta () in
553   let ty= match with_type with None-> NCic.Implicit (`Typeof n)| Some x ->x in
554   let len = List.length context in
555   let attrs = NCicUntrusted.set_kind kind attrs in
556   let menv_entry = (n, (attrs, context, ty)) in
557   menv_entry :: metasenv, n, NCic.Meta (n, (0,NCic.Irl len)), ty
558 ;;
559
560 let extend_meta metasenv n =
561  try
562   let attrs,cc,ty = NCicUtils.lookup_meta n metasenv in 
563   (match ty with 
564   | NCic.Implicit (`Typeof _) -> 
565       let mk_meta context kind =
566         let metasenv, _, ty, _ = mk_meta metasenv context kind in
567         (n, (attrs, cc, ty)) :: List.filter (fun x,_ -> x <> n) metasenv, ty
568       in
569       (match NCicUntrusted.kind_of_meta attrs with
570        | `IsSort 
571        | `IsType -> mk_meta [] `IsSort
572        | `IsTerm -> mk_meta cc `IsType)
573   | ty -> metasenv, ty)
574  with NCicUtils.Meta_not_found _ -> assert false
575 ;;
576
577 let saturate status ?(delta=0) metasenv subst context ty goal_arity =
578  assert (goal_arity >= 0);
579   let rec aux metasenv = function
580    | NCic.Prod (name,s,t) as ty ->
581        let metasenv1, _, arg,_ = 
582           mk_meta ~attrs:[`Name name] metasenv context ~with_type:s `IsTerm in
583        let t, metasenv1, args, pno = 
584            aux metasenv1 (NCicSubstitution.subst status arg t) 
585        in
586        if pno + 1 = goal_arity then
587          ty, metasenv, [], goal_arity+1
588        else
589          t, metasenv1, arg::args, pno+1
590    | ty ->
591         match NCicReduction.whd status ~subst context ty ~delta with
592         | NCic.Prod _ as ty -> aux metasenv ty
593         | ty -> ty, metasenv, [], 0
594   in
595   let res, newmetasenv, arguments, _ = aux metasenv ty in
596   res, newmetasenv, arguments
597 ;;