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