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