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