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