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