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