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