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