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