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