]> matita.cs.unibo.it Git - helm.git/blob - components/ng_kernel/oCic2NCic.ml
tagged 0.5.0-rc1
[helm.git] / components / ng_kernel / oCic2NCic.ml
1 module Ref = NReference
2
3 type ctx = 
4   | Ce of (NCic.hypothesis * NCic.obj list) Lazy.t
5   | Fix of (Ref.reference * string * NCic.term) Lazy.t
6
7 let strictify =
8  function
9     Ce l -> `Ce (Lazy.force l)
10   | Fix l -> `Fix (Lazy.force l)
11 ;;
12
13 (***** A function to restrict the context of a term getting rid of unsed
14        variables *******)
15
16 let restrict octx ctx ot =
17  let odummy = Cic.Implicit None in
18  let dummy = NCic.Meta (~-1,(0,NCic.Irl 0)) in
19  let rec aux m acc ot t =
20   function
21      [],[] -> (ot,t),acc
22    | ohe::otl as octx,he::tl ->
23       if CicTypeChecker.does_not_occur octx 0 1 ot then
24        aux (m+1) acc (CicSubstitution.subst odummy ot)
25         (NCicSubstitution.subst dummy t) (otl,tl)
26       else
27        (match ohe,strictify he with
28            None,_ -> assert false
29          | Some (name,Cic.Decl oty),`Ce ((name', NCic.Decl ty),objs) ->
30             aux (m+1) ((m+1,objs,None)::acc) (Cic.Lambda (name,oty,ot))
31              (NCic.Lambda (name',ty,t)) (otl,tl)
32          | Some (name,Cic.Decl oty),`Fix (ref,name',ty) ->
33             aux (m+1) ((m+1,[],Some ref)::acc) (Cic.Lambda (name,oty,ot))
34              (NCic.Lambda (name',ty,t)) (otl,tl)
35          | Some (name,Cic.Def (obo,oty)),`Ce ((name', NCic.Def (bo,ty)),objs) ->
36             aux (m+1) ((m+1,objs,None)::acc) (Cic.LetIn (name,obo,oty,ot))
37              (NCic.LetIn (name',bo,ty,t)) (otl,tl)
38          | _,_ -> assert false)
39    | _,_ -> assert false in
40  let rec split_lambdas_and_letins octx ctx infos (ote,te) =
41   match infos, ote, te with
42      ([], _, _) -> octx,ctx,ote
43    | ((_,objs,None)::tl, Cic.Lambda(name,oso,ota), NCic.Lambda(name',so,ta)) ->
44        split_lambdas_and_letins ((Some(name,(Cic.Decl oso)))::octx)
45         (Ce (lazy ((name',NCic.Decl so),objs))::ctx) tl (ota,ta)
46    | ((_,objs,Some r)::tl,Cic.Lambda(name,oso,ota),NCic.Lambda(name',so,ta)) ->
47        split_lambdas_and_letins ((Some(name,(Cic.Decl oso)))::octx)
48         (Fix (lazy (r,name',so))::ctx) tl (ota,ta)
49    | ((_,objs,None)::tl,Cic.LetIn(name,obo,oty,ota),NCic.LetIn(nam',bo,ty,ta))->
50        split_lambdas_and_letins ((Some (name,(Cic.Def (obo,oty))))::octx)
51         (Ce (lazy ((nam',NCic.Def (bo,ty)),objs))::ctx) tl (ota,ta)
52    | (_, _, _) -> assert false
53  in
54   let long_t,infos = aux 0 [] ot dummy (octx,ctx) in
55   let clean_octx,clean_ctx,clean_ot= split_lambdas_and_letins [] [] infos long_t
56   in
57 (*prerr_endline ("RESTRICT PRIMA: " ^ CicPp.pp ot (List.map (function None -> None | Some (name,_) -> Some name) octx));
58 prerr_endline ("RESTRICT DOPO: " ^ CicPp.pp clean_ot (List.map (function None -> None | Some (name,_) -> Some name) clean_octx));
59 *)
60    clean_octx,clean_ctx,clean_ot, List.map (fun (rel,_,_) -> rel) infos
61 ;;
62
63
64 (**** The translation itself ****)
65
66 let cn_to_s = function
67   | Cic.Anonymous -> "_"
68   | Cic.Name s -> s
69 ;;
70
71 let splat mk_pi ctx t =
72   List.fold_left
73     (fun (t,l) c -> 
74       match strictify c with
75       | `Ce ((name, NCic.Def (bo,ty)),l') -> NCic.LetIn (name, ty, bo, t),l@l'
76       | `Ce ((name, NCic.Decl ty),l') when mk_pi -> NCic.Prod (name, ty, t),l@l'
77       | `Ce ((name, NCic.Decl ty),l') -> NCic.Lambda (name, ty, t),l@l'
78       | `Fix (_,name,ty) when mk_pi -> NCic.Prod (name, ty, t),l
79       | `Fix (_,name,ty) -> NCic.Lambda (name,ty,t),l)
80     (t,[]) ctx
81 ;;
82
83 let context_tassonomy ctx = 
84     let rec split inner acc acc1 = function 
85       | Ce _ :: tl when inner -> split inner (acc+1) (acc1+1) tl
86       | Fix _ ::tl -> split false acc (acc1+1) tl
87       | _ as l ->
88         let only_decl () =
89          List.filter
90           (function
91               Ce _ as ce ->
92                (match strictify ce with
93                    `Ce ((_, NCic.Decl _),_) -> true
94                  | _ -> false)
95             | Fix _ -> true) l
96         in
97          acc, List.length l, lazy (List.length (only_decl ())), acc1
98     in
99       split true 0 1 ctx
100 ;;
101
102 let splat_args_for_rel ctx t ?rels n_fix =
103   let rels =
104    match rels with
105       Some rels -> rels
106     | None ->
107        let rec mk_irl = function 0 -> [] | n -> n::mk_irl (n - 1) in
108         mk_irl (List.length ctx)
109   in
110   let bound, free, _, primo_ce_dopo_fix = context_tassonomy ctx in
111   if free = 0 then t 
112   else
113     let rec aux = function
114       | n,_ when n = bound + n_fix -> []
115       | n,he::tl -> 
116          (match strictify (List.nth ctx (n-1)) with
117           | `Fix (refe, _, _) when n < primo_ce_dopo_fix ->
118              NCic.Const refe :: aux (n-1,tl)
119           | `Fix _ | `Ce ((_, NCic.Decl _),_) ->
120               NCic.Rel (he - n_fix)::aux(n-1,tl)
121           | `Ce ((_, NCic.Def _),_) -> aux (n-1,tl))
122       | _,_ -> assert false
123     in
124     NCic.Appl (t:: aux (List.length ctx,rels))
125 ;;
126
127 let splat_args ctx t n_fix rels =
128   let bound, free, _, primo_ce_dopo_fix = context_tassonomy ctx in
129   if ctx = [] then t
130   else
131    let rec aux = function
132      | 0,[] -> []
133      | n,he::tl -> 
134         (match strictify (List.nth ctx (n-1)) with
135          | `Ce ((_, NCic.Decl _),_) when n <= bound ->
136              NCic.Rel he:: aux (n-1,tl)
137          | `Fix (refe, _, _) when n < primo_ce_dopo_fix ->
138             splat_args_for_rel ctx (NCic.Const refe) ~rels n_fix :: aux (n-1,tl)
139          | `Fix _ | `Ce((_, NCic.Decl _),_)-> NCic.Rel (he - n_fix)::aux(n-1,tl)
140          | `Ce ((_, NCic.Def _),_) -> aux (n - 1,tl)
141         ) 
142      | _,_ -> assert false
143    in
144    NCic.Appl (t:: aux ((List.length ctx,rels)))
145 ;;
146
147 exception Nothing_to_do;;
148
149 let fix_outty curi tyno t context outty =
150  let leftno,rightno =
151   match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
152      Cic.InductiveDefinition (tyl,_,leftno,_) ->
153       let _,_,arity,_ = List.nth tyl tyno in
154       let rec count_prods leftno context arity =
155        match leftno, CicReduction.whd context arity with
156           0, Cic.Sort _ -> 0
157         | 0, Cic.Prod (name,so,ty) ->
158            1 + count_prods 0 (Some (name, Cic.Decl so)::context) ty
159         | n, Cic.Prod (name,so,ty) ->
160            count_prods (leftno - 1) (Some (name, Cic.Decl so)::context) ty
161         | _,_ -> assert false
162       in
163 (*prerr_endline (UriManager.string_of_uri curi);
164 prerr_endline ("LEFTNO: " ^ string_of_int leftno ^ "  " ^ CicPp.ppterm arity);*)
165        leftno, count_prods leftno [] arity
166    | _ -> assert false in
167  let ens,args =
168   let tty,_= CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
169   match CicReduction.whd context tty with
170      Cic.MutInd (_,_,ens) -> ens,[]
171    | Cic.Appl (Cic.MutInd (_,_,ens)::args) ->
172       ens,fst (HExtlib.split_nth leftno args)
173    | _ -> assert false
174  in
175   let rec aux n irl context outsort =
176    match n, CicReduction.whd context outsort with
177       0, Cic.Prod _ -> raise Nothing_to_do
178     | 0, _ ->
179        let irl = List.rev irl in
180        let ty = CicSubstitution.lift rightno (Cic.MutInd (curi,tyno,ens)) in
181        let ty =
182         if args = [] && irl = [] then ty
183         else
184          Cic.Appl (ty::(List.map (CicSubstitution.lift rightno) args)@irl) in
185        let he = CicSubstitution.lift (rightno + 1) outty in
186        let t =
187         if irl = [] then he
188         else Cic.Appl (he::List.map (CicSubstitution.lift 1) irl)
189        in
190         Cic.Lambda (Cic.Anonymous, ty, t)
191     | n, Cic.Prod (name,so,ty) ->
192        let ty' =
193         aux (n - 1) (Cic.Rel n::irl) (Some (name, Cic.Decl so)::context) ty
194        in
195         Cic.Lambda (name,so,ty')
196     | _,_ -> assert false
197   in
198 (*prerr_endline ("RIGHTNO = " ^ string_of_int rightno ^ " OUTTY = " ^ CicPp.ppterm outty);*)
199    let outsort =
200     fst (CicTypeChecker.type_of_aux' [] context outty CicUniv.oblivion_ugraph)
201    in
202     try aux rightno [] context outsort
203     with Nothing_to_do -> outty
204 (*prerr_endline (CicPp.ppterm outty ^ " <==> " ^ CicPp.ppterm outty');*)
205 ;;
206
207 let fix_outtype t =
208  let module C = Cic in
209  let rec aux context =
210   function
211      C.Rel _ as t -> t
212    | C.Var (uri,exp_named_subst) ->
213       let exp_named_subst' =
214        List.map (function i,t -> i, (aux context t)) exp_named_subst in
215         C.Var (uri,exp_named_subst')
216    | C.Implicit _
217    | C.Meta _ -> assert false
218    | C.Sort _ as t -> t
219    | C.Cast (v,t) -> C.Cast (aux context v, aux context t)
220    | C.Prod (n,s,t) ->
221         C.Prod (n, aux context s, aux ((Some (n, C.Decl s))::context) t)
222    | C.Lambda (n,s,t) ->
223        C.Lambda (n, aux context s, aux ((Some (n, C.Decl s))::context) t)
224    | C.LetIn (n,s,ty,t) ->
225       C.LetIn
226        (n, aux context s, aux context ty,
227         aux ((Some (n, C.Def(s,ty)))::context) t)
228    | C.Appl l -> C.Appl (List.map (aux context) l)
229    | C.Const (uri,exp_named_subst) ->
230       let exp_named_subst' =
231        List.map (function i,t -> i, (aux context t)) exp_named_subst
232       in
233        C.Const (uri,exp_named_subst')
234    | C.MutInd (uri,tyno,exp_named_subst) ->
235       let exp_named_subst' =
236        List.map (function i,t -> i, (aux context t)) exp_named_subst
237       in
238        C.MutInd (uri, tyno, exp_named_subst')
239    | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
240       let exp_named_subst' =
241        List.map (function i,t -> i, (aux context t)) exp_named_subst
242       in
243        C.MutConstruct (uri, tyno, consno, exp_named_subst')
244    | C.MutCase (uri, tyno, outty, term, patterns) ->
245       let outty = fix_outty uri tyno term context outty in
246        C.MutCase (uri, tyno, aux context outty,
247         aux context term, List.map (aux context) patterns)
248    | C.Fix (funno, funs) ->
249       let tys,_ =
250         List.fold_left
251           (fun (types,len) (n,_,ty,_) ->
252             ((Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))))::types,
253               len+1
254           ) ([],0) funs
255       in
256        C.Fix (funno,
257         List.map
258          (fun (name, indidx, ty, bo) ->
259            (name, indidx, aux context ty, aux (tys@context) bo)
260          ) funs
261       )
262    | C.CoFix (funno, funs) ->
263       let tys,_ =
264         List.fold_left
265           (fun (types,len) (n,ty,_) ->
266             ((Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))))::types,
267               len+1
268           ) ([],0) funs
269       in
270        C.CoFix (funno,
271         List.map
272          (fun (name, ty, bo) ->
273            (name, aux context ty, aux (tys@context) bo)
274          ) funs
275        )
276  in
277   aux [] t
278 ;;
279
280 let get_fresh,reset_seed =
281  let seed = ref 0 in
282   (function () ->
283    incr seed;
284    string_of_int !seed),
285   (function () -> seed := 0)
286 ;;
287
288 exception NotSimilar 
289 let alpha t1 t2 ref ref' =
290   let rec aux t1 t2 = match t1,t2 with
291     | NCic.Rel n, NCic.Rel m when n=m -> ()
292     | NCic.Appl l1, NCic.Appl l2 -> List.iter2 aux l1 l2
293     | NCic.Lambda (_,s1,t1), NCic.Lambda (_,s2,t2) 
294     | NCic.Prod (_,s1,t1), NCic.Prod (_,s2,t2) -> aux s1 s2; aux t1 t2
295     | NCic.LetIn (_,s1,ty1,t1), NCic.LetIn (_,s2,ty2,t2) -> 
296          aux s1 s2; aux ty1 ty2; aux t1 t2
297     | NCic.Const (NReference.Ref (_,uu1,xp1)), 
298       NCic.Const (NReference.Ref (_,uu2,xp2))  when 
299          let NReference.Ref (_,u1,_) = ref in
300          let NReference.Ref (_,u2,_) = ref' in
301            NUri.eq uu1 u1 && NUri.eq uu2 u2 && xp1 = xp2
302       -> ()
303     | NCic.Const r1, NCic.Const r2 when NReference.eq r1 r2 -> ()
304     | NCic.Meta _,NCic.Meta _ -> ()
305     | NCic.Implicit _,NCic.Implicit _ -> ()
306     | NCic.Sort x,NCic.Sort y when x=y -> ()
307     | NCic.Match (_,t1,t11,tl1), NCic.Match (_,t2,t22,tl2) -> 
308          aux t1 t2;aux t11 t22;List.iter2 aux tl1 tl2 
309     | _-> raise NotSimilar
310   in
311   try aux t1 t2; true  with NotSimilar -> false
312 ;;
313
314 exception Found of NReference.reference;;
315 let cache = Hashtbl.create 313;; 
316 let same_obj ref ref' =
317  function
318   | (_,_,_,_,NCic.Fixpoint (_,l1,_)), (_,_,_,_,NCic.Fixpoint (_,l2,_))
319     when List.for_all2 (fun (_,_,_,ty1,bo1) (_,_,_,ty2,bo2) -> 
320        alpha ty1 ty2 ref ref' && alpha bo1 bo2 ref ref') l1 l2 ->
321      true
322   | _ -> false
323 ;;
324 let find_in_cache name obj ref =
325  try
326   List.iter
327    (function (ref',obj') ->
328      let recno, fixno =
329       match ref with
330          NReference.Ref (_,_,NReference.Fix (fixno,recno)) -> recno,fixno
331        | _ -> assert false in
332      let recno',fixno' =
333       match ref' with
334          NReference.Ref (_,_,NReference.Fix (fixno',recno)) -> recno,fixno'
335        | _ -> assert false in
336      if recno = recno' && fixno = fixno' && same_obj ref ref' (obj,obj') then (
337 (*
338 prerr_endline ("!!!!!!!!!!! CACHE HIT !!!!!!!!!!\n" ^
339 NReference.string_of_reference ref ^ "\n" ^
340 NReference.string_of_reference ref' ^ "\n"); 
341  *)
342        raise (Found ref'));
343 (*
344 prerr_endline ("CACHE SAME NAME: " ^ NReference.string_of_reference ref ^ " <==> " ^ NReference.string_of_reference ref');
345  *)
346   ) (Hashtbl.find_all cache name);
347 (*   prerr_endline "<<< CACHE MISS >>>";   *)
348   begin
349     match obj, ref with 
350     | (_,_,_,_,NCic.Fixpoint (true,fl,_)) , NReference.Ref (x,y,NReference.Fix _) ->
351        ignore(List.fold_left (fun i (_,name,rno,_,_) ->
352          let ref = NReference.mk_fix i rno ref in
353          Hashtbl.add cache name (ref,obj);
354          i+1
355        ) 0 fl)
356     | _ -> assert false
357   end;
358   None
359  with Found ref -> Some ref
360 ;;
361
362 (* we are lambda-lifting also variables that do not occur *)
363 (* ctx does not distinguish successive blocks of cofix, since there may be no
364  *   lambda separating them *)
365 let convert_term uri t = 
366   (* k=true if we are converting a term to be pushed in a ctx or if we are
367             converting the type of a fix;
368      k=false if we are converting a term to be put in the body of a fix;
369      in the latter case, we must permute Rels since the Fix abstraction will
370      preceed its lefts parameters; in the former case, there is nothing to
371      permute *)
372   let rec aux k octx (ctx : ctx list) n_fix uri = function
373     | Cic.CoFix _ as cofix ->
374         let octx,ctx,fix,rels = restrict octx ctx cofix in
375         let cofixno,fl =
376          match fix with Cic.CoFix (cofixno,fl)->cofixno,fl | _-> assert false in
377         let buri = 
378           UriManager.uri_of_string 
379            (UriManager.buri_of_uri uri^"/"^
380             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
381         in
382         let bctx, fixpoints_tys, tys, _ = 
383           List.fold_right 
384             (fun (name,ty,_) (bctx, fixpoints, tys, idx) -> 
385               let ty, fixpoints_ty = aux true octx ctx n_fix uri ty in
386               let r = Ref.reference_of_ouri buri(Ref.CoFix idx) in
387               bctx @ [Fix (lazy (r,name,ty))],
388                fixpoints_ty @ fixpoints,ty::tys,idx-1)
389             fl ([], [], [], List.length fl-1)
390         in
391         let bctx = bctx @ ctx in
392         let n_fl = List.length fl in
393         let boctx,_ =
394          List.fold_left
395           (fun (types,len) (n,ty,_) ->
396              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
397               len+1)) (octx,0) fl
398         in
399         let fl, fixpoints =
400           List.fold_right2 
401             (fun (name,_,bo) ty  (l,fixpoints) -> 
402                let bo, fixpoints_bo = aux false boctx bctx n_fl buri bo in
403                let splty,fixpoints_splty = splat true ctx ty in
404                let splbo,fixpoints_splbo = splat false ctx bo in
405                (([],name,~-1,splty,splbo)::l),
406                fixpoints_bo @ fixpoints_splty @ fixpoints_splbo @ fixpoints)
407             fl tys ([],fixpoints_tys)
408         in
409         let obj = 
410           NUri.nuri_of_ouri buri,0,[],[],
411             NCic.Fixpoint (false, fl, (`Generated, `Definition)) 
412         in
413         splat_args ctx 
414          (NCic.Const (Ref.reference_of_ouri buri (Ref.CoFix cofixno)))
415          n_fix rels,
416         fixpoints @ [obj]
417     | Cic.Fix _ as fix ->
418         let octx,ctx,fix,rels = restrict octx ctx fix in
419         let fixno,fl =
420          match fix with Cic.Fix (fixno,fl) -> fixno,fl | _ -> assert false in
421         let buri = 
422           UriManager.uri_of_string 
423            (UriManager.buri_of_uri uri^"/"^
424             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
425         in
426         let bad_bctx, fixpoints_tys, tys, _ = 
427           List.fold_right 
428             (fun (name,recno,ty,_) (bctx, fixpoints, tys, idx) -> 
429               let ty, fixpoints_ty = aux true octx ctx n_fix uri ty in
430               let r =  (* recno is dummy here, must be lifted by the ctx len *)
431                 Ref.reference_of_ouri buri (Ref.Fix (idx,recno)) 
432               in
433               bctx @ [Fix (lazy (r,name,ty))],
434                fixpoints_ty@fixpoints,ty::tys,idx-1)
435             fl ([], [], [], List.length fl-1)
436         in
437         let _, _, free_decls, _ = context_tassonomy (bad_bctx @ ctx) in
438         let free_decls = Lazy.force free_decls in
439         let bctx = 
440           List.map (function ce -> match strictify ce with
441             | `Fix (Ref.Ref (_,_,Ref.Fix (idx, recno)),name, ty) ->
442               Fix (lazy (Ref.reference_of_ouri buri
443                     (Ref.Fix (idx,recno+free_decls)),name,ty))
444             | _ -> assert false) bad_bctx @ ctx
445         in
446         let n_fl = List.length fl in
447         let boctx,_ =
448          List.fold_left
449           (fun (types,len) (n,_,ty,_) ->
450              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
451               len+1)) (octx,0) fl
452         in
453         let rno_fixno = ref 0 in
454         let fl, fixpoints,_ =
455           List.fold_right2 
456             (fun (name,rno,_,bo) ty (l,fixpoints,idx) -> 
457                let bo, fixpoints_bo = aux false boctx bctx n_fl buri bo in
458                let splty,fixpoints_splty = splat true ctx ty in
459                let splbo,fixpoints_splbo = splat false ctx bo in
460                let rno = rno + free_decls in
461                if idx = fixno then rno_fixno := rno;
462                (([],name,rno,splty,splbo)::l),
463                fixpoints_bo@fixpoints_splty@fixpoints_splbo@fixpoints,idx+1)
464             fl tys ([],fixpoints_tys,0)
465         in
466         let obj = 
467           NUri.nuri_of_ouri buri,max_int,[],[],
468             NCic.Fixpoint (true, fl, (`Generated, `Definition)) in
469         let r = Ref.reference_of_ouri buri (Ref.Fix (fixno,!rno_fixno)) in
470         let obj,r =
471          let _,name,_,_,_ = List.nth fl fixno in
472          match find_in_cache name obj r with
473             Some r' -> [],r'
474           | None -> [obj],r
475         in
476         splat_args ctx (NCic.Const r) n_fix rels, fixpoints @ obj
477     | Cic.Rel n ->
478         let bound, _, _, primo_ce_dopo_fix = context_tassonomy ctx in
479         (match List.nth ctx (n-1) with
480         | Fix l when n < primo_ce_dopo_fix -> 
481            let r,_,_ = Lazy.force l in
482             splat_args_for_rel ctx (NCic.Const r) n_fix, []
483         | Ce _ when n <= bound -> NCic.Rel n, []
484         | Fix _ when n <= bound -> assert false
485         | Fix _ | Ce _ when k = true -> NCic.Rel n, []
486         | Fix _ | Ce _ -> NCic.Rel (n-n_fix), [])
487     | Cic.Lambda (name, (s as old_s), t) ->
488         let s, fixpoints_s = aux k octx ctx n_fix uri s in
489         let s'_and_fixpoints_s' = lazy (aux true octx ctx n_fix uri old_s) in
490         let ctx =
491          Ce (lazy
492           let s',fixpoints_s' = Lazy.force s'_and_fixpoints_s' in
493            ((cn_to_s name, NCic.Decl s'),fixpoints_s'))::ctx in
494         let octx = Some (name, Cic.Decl old_s) :: octx in
495         let t, fixpoints_t = aux k octx ctx n_fix uri t in
496         NCic.Lambda (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
497     | Cic.Prod (name, (s as old_s), t) ->
498         let s, fixpoints_s = aux k octx ctx n_fix uri s in
499         let s'_and_fixpoints_s' = lazy (aux true octx ctx n_fix uri old_s) in
500         let ctx =
501          Ce (lazy
502           let s',fixpoints_s' = Lazy.force s'_and_fixpoints_s' in
503            ((cn_to_s name, NCic.Decl s'),fixpoints_s'))::ctx in
504         let octx = Some (name, Cic.Decl old_s) :: octx in
505         let t, fixpoints_t = aux k octx ctx n_fix uri t in
506         NCic.Prod (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
507     | Cic.LetIn (name, (te as old_te), (ty as old_ty), t) ->
508         let te, fixpoints_s = aux k octx ctx n_fix uri te in
509         let te_and_fixpoints_s' = lazy (aux true octx ctx n_fix uri old_te) in
510         let ty, fixpoints_ty = aux k octx ctx n_fix uri ty in
511         let ty_and_fixpoints_ty' = lazy (aux true octx ctx n_fix uri old_ty) in
512         let ctx =
513          Ce (lazy
514           let te',fixpoints_s' = Lazy.force te_and_fixpoints_s' in
515           let ty',fixpoints_ty' = Lazy.force ty_and_fixpoints_ty' in
516           let fixpoints' = fixpoints_s' @ fixpoints_ty' in
517            ((cn_to_s name, NCic.Def (te', ty')),fixpoints'))::ctx in
518         let octx = Some (name, Cic.Def (old_te, old_ty)) :: octx in
519         let t, fixpoints_t = aux k octx ctx n_fix uri t in
520         NCic.LetIn (cn_to_s name, ty, te, t), 
521         fixpoints_s @ fixpoints_t @ fixpoints_ty
522     | Cic.Cast (t,ty) ->
523         let t, fixpoints_t = aux k octx ctx n_fix uri t in
524         let ty, fixpoints_ty = aux k octx ctx n_fix uri ty in
525         NCic.LetIn ("cast", ty, t, NCic.Rel 1), fixpoints_t @ fixpoints_ty
526     | Cic.Sort Cic.Prop -> NCic.Sort NCic.Prop,[]
527     | Cic.Sort Cic.CProp -> NCic.Sort NCic.CProp,[]
528     | Cic.Sort (Cic.Type u) -> 
529           NCic.Sort (NCic.Type (CicUniv.get_rank u)),[] 
530     | Cic.Sort Cic.Set -> NCic.Sort (NCic.Type 0),[] 
531        (* calculate depth in the univ_graph*)
532     | Cic.Appl l -> 
533         let l, fixpoints =
534           List.fold_right 
535              (fun t (l,acc) -> 
536                let t, fixpoints = aux k octx ctx n_fix uri t in 
537                (t::l,fixpoints@acc))
538              l ([],[])
539         in
540         (match l with
541         | (NCic.Appl l1)::l2 -> NCic.Appl (l1@l2), fixpoints
542         | _ -> NCic.Appl l, fixpoints)
543     | Cic.Const (curi, ens) -> 
544        aux_ens k curi octx ctx n_fix uri ens
545         (match fst(CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
546         | Cic.Constant (_,Some _,_,_,_) ->
547                NCic.Const (Ref.reference_of_ouri curi Ref.Def)
548         | Cic.Constant (_,None,_,_,_) ->
549                NCic.Const (Ref.reference_of_ouri curi Ref.Decl)
550         | _ -> assert false)
551     | Cic.MutInd (curi, tyno, ens) -> 
552        aux_ens k curi octx ctx n_fix uri ens
553         (NCic.Const (Ref.reference_of_ouri curi (Ref.Ind tyno)))
554     | Cic.MutConstruct (curi, tyno, consno, ens) -> 
555        aux_ens k curi octx ctx n_fix uri ens
556         (NCic.Const (Ref.reference_of_ouri curi (Ref.Con (tyno,consno))))
557     | Cic.Var (curi, ens) ->
558        (match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
559            Cic.Variable (_,Some bo,_,_,_) ->
560             aux k octx ctx n_fix uri (CicSubstitution.subst_vars ens bo)
561          | _ -> assert false)
562     | Cic.MutCase (curi, tyno, outty, t, branches) ->
563         let r = Ref.reference_of_ouri curi (Ref.Ind tyno) in
564         let outty, fixpoints_outty = aux k octx ctx n_fix uri outty in
565         let t, fixpoints_t = aux k octx ctx n_fix uri t in
566         let branches, fixpoints =
567           List.fold_right 
568              (fun t (l,acc) -> 
569                let t, fixpoints = aux k octx ctx n_fix uri t in 
570                (t::l,fixpoints@acc))
571              branches ([],[])
572         in
573         NCic.Match (r,outty,t,branches), fixpoints_outty@fixpoints_t@fixpoints
574     | Cic.Implicit _ | Cic.Meta _ -> assert false
575   and aux_ens k curi octx ctx n_fix uri ens he =
576    match ens with
577       [] -> he,[]
578     | _::_ ->
579       let params =
580        match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
581           Cic.Constant (_,_,_,params,_)
582         | Cic.InductiveDefinition (_,params,_,_) -> params
583         | Cic.Variable _
584         | Cic.CurrentProof _ -> assert false
585       in
586       let ens,objs =
587        List.fold_right
588         (fun luri (l,objs) ->
589           match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph luri) with
590              Cic.Variable (_,Some _,_,_,_) -> l, objs
591            | Cic.Variable (_,None,_,_,_) ->
592               let t = List.assoc luri ens in
593               let t,o = aux k octx ctx n_fix uri t in
594                t::l, o@objs
595            | _ -> assert false
596         ) params ([],[])
597       in
598        match ens with
599           [] -> he,objs
600         | _::_ -> NCic.Appl (he::ens),objs
601   in
602    aux false [] [] 0 uri t
603 ;;
604
605 let cook mode vars t =
606  let t = fix_outtype t in
607  let varsno = List.length vars in
608  let t = CicSubstitution.lift varsno t in
609  let rec aux n acc l =
610   let subst =
611    snd(List.fold_left (fun (i,res) uri -> i+1,(uri,Cic.Rel i)::res) (1,[]) acc)
612   in
613   match l with
614      [] -> CicSubstitution.subst_vars subst t
615    | uri::uris ->
616     let bo,ty =
617      match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph uri) with
618         Cic.Variable (_,bo,ty,_,_) ->
619          HExtlib.map_option fix_outtype bo, fix_outtype ty
620       | _ -> assert false in
621     let ty = CicSubstitution.subst_vars subst ty in
622     let bo = HExtlib.map_option (CicSubstitution.subst_vars subst) bo in
623     let id = Cic.Name (UriManager.name_of_uri uri) in
624     let t = aux (n-1) (uri::acc) uris in
625      match bo,ty,mode with
626         None,ty,`Lambda -> Cic.Lambda (id,ty,t)
627       | None,ty,`Pi -> Cic.Prod (id,ty,t)
628       | Some bo,ty,_ -> Cic.LetIn (id,bo,ty,t)
629  in
630   aux varsno [] vars
631 ;;
632
633 let convert_obj_aux uri = function
634  | Cic.Constant (name, None, ty, vars, _) ->
635      let ty = cook `Pi vars ty in
636      let nty, fixpoints = convert_term uri ty in
637      assert(fixpoints = []);
638      NCic.Constant ([], name, None, nty, (`Provided,`Theorem,`Regular)),
639      fixpoints
640  | Cic.Constant (name, Some bo, ty, vars, _) ->
641      let bo = cook `Lambda vars bo in
642      let ty = cook `Pi vars ty in
643      let nbo, fixpoints_bo = convert_term uri bo in
644      let nty, fixpoints_ty = convert_term uri ty in
645      assert(fixpoints_ty = []);
646      NCic.Constant ([], name, Some nbo, nty, (`Provided,`Theorem,`Regular)),
647      fixpoints_bo @ fixpoints_ty
648  | Cic.InductiveDefinition (itl,vars,leftno,_) -> 
649      let ind = let _,x,_,_ = List.hd itl in x in
650      let itl, fix_itl = 
651        List.fold_right
652          (fun (name, _, ty, cl) (itl,acc) ->
653             let ty = cook `Pi vars ty in
654             let ty, fix_ty = convert_term uri ty in
655             let cl, fix_cl = 
656               List.fold_right
657                (fun (name, ty) (cl,acc) -> 
658                  let ty = cook `Pi vars ty in
659                  let ty, fix_ty = convert_term uri ty in
660                  ([], name, ty)::cl, acc @ fix_ty)
661                cl ([],[])
662             in
663             ([], name, ty, cl)::itl, fix_ty @ fix_cl @ acc)
664          itl ([],[])
665      in
666      NCic.Inductive(ind, leftno + List.length 
667        (List.filter (fun v -> 
668           match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph v) with
669              Cic.Variable (_,Some _,_,_,_) -> false
670            | Cic.Variable (_,None,_,_,_) -> true
671            | _ -> assert false)
672           vars)
673        , itl, (`Provided, `Regular)),
674      fix_itl
675  | Cic.Variable _ 
676  | Cic.CurrentProof _ -> assert false
677 ;;
678
679 let convert_obj uri obj = 
680   reset_seed ();
681   let o, fixpoints = convert_obj_aux uri obj in
682   let obj = NUri.nuri_of_ouri uri,max_int, [], [], o in
683   fixpoints @ [obj]
684 ;;