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