]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/oCic2NCic.ml
Grave bug fixed: Ce that point to definitions were handled as those that point
[helm.git] / helm / software / components / ng_kernel / oCic2NCic.ml
1 module Ref = NReference
2
3 let cn_to_s = function
4   | Cic.Anonymous -> "_"
5   | Cic.Name s -> s
6 ;;
7
8 type ctx = 
9   | Ce of NCic.hypothesis 
10   | Fix of Ref.reference * string * NCic.term
11
12 let splat mk_pi ctx t =
13   List.fold_left
14     (fun t c -> 
15       match c with
16       | Ce (name, NCic.Def (bo,ty)) -> NCic.LetIn (name, ty, bo, t)
17       | Ce (name, NCic.Decl ty) when mk_pi -> NCic.Prod (name, ty, t)
18       | Ce (name, NCic.Decl ty) -> NCic.Lambda (name, ty, t)
19       | Fix (_,name,ty) when mk_pi -> NCic.Prod (name, ty, t)
20       | Fix (_,name,ty) -> NCic.Lambda (name,ty,t))
21     t ctx
22 ;;
23
24 let context_tassonomy ctx = 
25     let rec split inner acc acc1 = function 
26       | Ce _ :: tl when inner -> split inner (acc+1) (acc1+1) tl
27       | Fix _ ::tl -> split false acc (acc1+1) tl
28       | _ as l ->
29         let only_decl =
30          List.filter (function Ce (_, NCic.Decl _) | Fix _ -> true | _ -> false)
31           l
32         in
33          acc, List.length l, List.length only_decl, acc1
34     in
35       split true 0 1 ctx
36 ;;
37
38 let splat_args_for_rel ctx t = 
39   let bound, free, _, primo_ce_dopo_fix = context_tassonomy ctx in
40   if free = 0 then t 
41   else
42     let rec aux = function
43       | 0 -> []
44       | n -> 
45          match List.nth ctx (n+bound) with
46          | Fix (refe, _, _) when (n+bound) < primo_ce_dopo_fix ->
47             NCic.Const refe :: aux (n-1)
48          | Fix _ | Ce (_, NCic.Decl _) -> NCic.Rel (n+bound)::aux (n-1)
49          | Ce (_, NCic.Def _) -> aux (n-1)
50     in
51     NCic.Appl (t:: aux free)
52 ;;
53
54 let splat_args ctx t n_fix = 
55   let bound, free, _, primo_ce_dopo_fix = context_tassonomy ctx in
56   if ctx = [] then t
57   else
58    let rec aux = function
59      | 0 -> []
60      | n -> 
61         (match List.nth ctx (n-1) with
62          | Ce (_, NCic.Decl _) when n <= bound -> NCic.Rel n:: aux (n-1)
63          | Fix (refe, _, _) when n < primo_ce_dopo_fix ->
64             splat_args_for_rel ctx (NCic.Const refe):: aux (n-1)
65          | Fix _ | Ce (_, NCic.Decl _) -> NCic.Rel (n - n_fix):: aux (n-1)
66          | Ce (_, NCic.Def _) -> aux (n - 1)
67         ) 
68    in
69    NCic.Appl (t:: aux (List.length ctx))
70 ;;
71
72 exception Nothing_to_do;;
73
74 let fix_outty curi tyno t context outty =
75  let leftno,rightno =
76   match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
77      Cic.InductiveDefinition (tyl,_,leftno,_) ->
78       let _,_,arity,_ = List.nth tyl tyno in
79       let rec count_prods leftno context arity =
80        match leftno, CicReduction.whd context arity with
81           0, Cic.Sort _ -> 0
82         | 0, Cic.Prod (name,so,ty) ->
83            1 + count_prods 0 (Some (name, Cic.Decl so)::context) ty
84         | n, Cic.Prod (name,so,ty) ->
85            count_prods (leftno - 1) (Some (name, Cic.Decl so)::context) ty
86         | _,_ -> assert false
87       in
88 (*prerr_endline (UriManager.string_of_uri curi);
89 prerr_endline ("LEFTNO: " ^ string_of_int leftno ^ "  " ^ CicPp.ppterm arity);*)
90        leftno, count_prods leftno [] arity
91    | _ -> assert false in
92  let ens,args =
93   let tty,_= CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
94   match CicReduction.whd context tty with
95      Cic.MutInd (_,_,ens) -> ens,[]
96    | Cic.Appl (Cic.MutInd (_,_,ens)::args) ->
97       ens,fst (HExtlib.split_nth leftno args)
98    | _ -> assert false
99  in
100   let rec aux n irl context outsort =
101    match n, CicReduction.whd context outsort with
102       0, Cic.Prod _ -> raise Nothing_to_do
103     | 0, _ ->
104        let irl = List.rev irl in
105        let ty = CicSubstitution.lift rightno (Cic.MutInd (curi,tyno,ens)) in
106        let ty =
107         if args = [] && irl = [] then ty
108         else
109          Cic.Appl (ty::(List.map (CicSubstitution.lift rightno) args)@irl) in
110        let he = CicSubstitution.lift (rightno + 1) outty in
111        let t =
112         if irl = [] then he
113         else Cic.Appl (he::List.map (CicSubstitution.lift 1) irl)
114        in
115         Cic.Lambda (Cic.Anonymous, ty, t)
116     | n, Cic.Prod (name,so,ty) ->
117        let ty' =
118         aux (n - 1) (Cic.Rel n::irl) (Some (name, Cic.Decl so)::context) ty
119        in
120         Cic.Lambda (name,so,ty')
121     | _,_ -> assert false
122   in
123 (*prerr_endline ("RIGHTNO = " ^ string_of_int rightno ^ " OUTTY = " ^ CicPp.ppterm outty);*)
124    let outsort =
125     fst (CicTypeChecker.type_of_aux' [] context outty CicUniv.oblivion_ugraph)
126    in
127     try aux rightno [] context outsort
128     with Nothing_to_do -> outty
129 (*prerr_endline (CicPp.ppterm outty ^ " <==> " ^ CicPp.ppterm outty');*)
130 ;;
131
132 let fix_outtype t =
133  let module C = Cic in
134  let rec aux context =
135   function
136      C.Rel _ as t -> t
137    | C.Var (uri,exp_named_subst) ->
138       let exp_named_subst' =
139        List.map (function i,t -> i, (aux context t)) exp_named_subst in
140         C.Var (uri,exp_named_subst')
141    | C.Implicit _
142    | C.Meta _ -> assert false
143    | C.Sort _ as t -> t
144    | C.Cast (v,t) -> C.Cast (aux context v, aux context t)
145    | C.Prod (n,s,t) ->
146         C.Prod (n, aux context s, aux ((Some (n, C.Decl s))::context) t)
147    | C.Lambda (n,s,t) ->
148        C.Lambda (n, aux context s, aux ((Some (n, C.Decl s))::context) t)
149    | C.LetIn (n,s,ty,t) ->
150       C.LetIn
151        (n, aux context s, aux context ty,
152         aux ((Some (n, C.Def(s,ty)))::context) t)
153    | C.Appl l -> C.Appl (List.map (aux context) l)
154    | C.Const (uri,exp_named_subst) ->
155       let exp_named_subst' =
156        List.map (function i,t -> i, (aux context t)) exp_named_subst
157       in
158        C.Const (uri,exp_named_subst')
159    | C.MutInd (uri,tyno,exp_named_subst) ->
160       let exp_named_subst' =
161        List.map (function i,t -> i, (aux context t)) exp_named_subst
162       in
163        C.MutInd (uri, tyno, exp_named_subst')
164    | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
165       let exp_named_subst' =
166        List.map (function i,t -> i, (aux context t)) exp_named_subst
167       in
168        C.MutConstruct (uri, tyno, consno, exp_named_subst')
169    | C.MutCase (uri, tyno, outty, term, patterns) ->
170       let outty = fix_outty uri tyno term context outty in
171        C.MutCase (uri, tyno, aux context outty,
172         aux context term, List.map (aux context) patterns)
173    | C.Fix (funno, funs) ->
174       let tys,_ =
175         List.fold_left
176           (fun (types,len) (n,_,ty,_) ->
177             ((Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))))::types,
178               len+1
179           ) ([],0) funs
180       in
181        C.Fix (funno,
182         List.map
183          (fun (name, indidx, ty, bo) ->
184            (name, indidx, aux context ty, aux (tys@context) bo)
185          ) funs
186       )
187    | C.CoFix (funno, funs) ->
188       let tys,_ =
189         List.fold_left
190           (fun (types,len) (n,ty,_) ->
191             ((Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))))::types,
192               len+1
193           ) ([],0) funs
194       in
195        C.CoFix (funno,
196         List.map
197          (fun (name, ty, bo) ->
198            (name, aux context ty, aux (tys@context) bo)
199          ) funs
200        )
201  in
202   aux [] t
203 ;;
204
205 let get_fresh,reset_seed =
206  let seed = ref 0 in
207   (function () ->
208    incr seed;
209    string_of_int !seed),
210   (function () -> seed := 0)
211 ;;
212
213 (* we are lambda-lifting also variables that do not occur *)
214 (* ctx does not distinguish successive blocks of cofix, since there may be no
215  *   lambda separating them *)
216 let convert_term uri t = 
217   let rec aux octx (ctx : ctx list) n_fix uri = function
218     | Cic.CoFix (k, fl) ->
219         let buri = 
220           UriManager.uri_of_string 
221            (UriManager.buri_of_uri uri^"/"^
222             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
223         in
224         let bctx, fixpoints_tys, tys, _ = 
225           List.fold_right 
226             (fun (name,ty,_) (bctx, fixpoints, tys, idx) -> 
227               let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
228               let r = Ref.reference_of_ouri buri(Ref.CoFix idx) in
229               Fix (r,name,ty) :: bctx, fixpoints_ty @ fixpoints,ty::tys,idx+1)
230             fl ([], [], [], 0)
231         in
232         let bctx = bctx @ ctx in
233         let n_fl = List.length fl in
234         let boctx,_ =
235          List.fold_left
236           (fun (types,len) (n,ty,_) ->
237              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
238               len+1)) (octx,0) fl
239         in
240         let fl, fixpoints =
241           List.fold_right2 
242             (fun (name,_,bo) ty  (l,fixpoints) -> 
243                let bo, fixpoints_bo = aux boctx bctx n_fl buri bo in
244                (([],name,~-1,splat true ctx ty, splat false ctx bo)::l),
245                fixpoints_bo @ fixpoints)
246             fl tys ([],fixpoints_tys)
247         in
248         let obj = 
249           NUri.nuri_of_ouri buri,0,[],[],
250             NCic.Fixpoint (false, fl, (`Generated, `Definition)) 
251         in
252         splat_args ctx 
253          (NCic.Const (Ref.reference_of_ouri buri (Ref.CoFix k)))
254          n_fix,
255         fixpoints @ [obj]
256     | Cic.Fix (k, fl) ->
257         let buri = 
258           UriManager.uri_of_string 
259            (UriManager.buri_of_uri uri^"/"^
260             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
261         in
262         let bad_bctx, fixpoints_tys, tys, _ = 
263           List.fold_right 
264             (fun (name,recno,ty,_) (bctx, fixpoints, tys, idx) -> 
265               let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
266               let r =  (* recno is dummy here, must be lifted by the ctx len *)
267                 Ref.reference_of_ouri buri (Ref.Fix (idx,recno)) 
268               in
269               Fix (r,name,ty) :: bctx, fixpoints_ty@fixpoints,ty::tys,idx+1)
270             fl ([], [], [], 0)
271         in
272         let _, _, free_decls, _ = context_tassonomy (bad_bctx @ ctx) in
273         let bctx = 
274           List.map (function 
275             | Fix (Ref.Ref (_,_,Ref.Fix (idx, recno)),name, ty) ->
276               Fix (Ref.reference_of_ouri buri
277                     (Ref.Fix (idx,recno+free_decls)),name,ty)
278             | _ -> assert false) bad_bctx @ ctx
279         in
280         let n_fl = List.length fl in
281         let boctx,_ =
282          List.fold_left
283           (fun (types,len) (n,_,ty,_) ->
284              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
285               len+1)) (octx,0) fl
286         in
287         let rno_k = ref 0 in
288         let fl, fixpoints,_ =
289           List.fold_right2 
290             (fun (name,rno,_,bo) ty (l,fixpoints,idx) -> 
291                let bo, fixpoints_bo = aux boctx bctx n_fl buri bo in
292                let rno = rno + free_decls in
293                if idx = k then rno_k := rno;
294                (([],name,rno,splat true ctx ty, splat false ctx bo)::l),
295                fixpoints_bo @ fixpoints,idx+1)
296             fl tys ([],fixpoints_tys,0)
297         in
298         let obj = 
299           NUri.nuri_of_ouri buri,max_int,[],[],
300             NCic.Fixpoint (true, fl, (`Generated, `Definition)) 
301         in
302         splat_args ctx
303           (NCic.Const 
304             (Ref.reference_of_ouri buri (Ref.Fix (k,!rno_k))))
305           n_fix,
306         fixpoints @ [obj]
307     | Cic.Rel n ->
308         let bound, _, _, primo_ce_dopo_fix = context_tassonomy ctx in
309         (match List.nth ctx (n-1) with
310         | Fix (r,_,_) when n < primo_ce_dopo_fix -> 
311             splat_args_for_rel ctx (NCic.Const r), []
312         | Ce _ when n <= bound -> NCic.Rel n, []
313         | Fix _ (* BUG 3 fix nested *) 
314         | Ce _ -> NCic.Rel (n-n_fix), [])
315     | Cic.Lambda (name, (s as old_s), t) ->
316         let s, fixpoints_s = aux octx ctx n_fix uri s in
317         let ctx = Ce (cn_to_s name, NCic.Decl s) :: ctx in
318         let octx = Some (name, Cic.Decl old_s) :: octx in
319         let t, fixpoints_t = aux octx ctx n_fix uri t in
320         NCic.Lambda (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
321     | Cic.Prod (name, (s as old_s), t) ->
322         let s, fixpoints_s = aux octx ctx n_fix uri s in
323         let ctx = Ce (cn_to_s name, NCic.Decl s) :: ctx in
324         let octx = Some (name, Cic.Decl old_s) :: octx in
325         let t, fixpoints_t = aux octx ctx n_fix uri t in
326         NCic.Prod (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
327     | Cic.LetIn (name, (te as old_te), (ty as old_ty), t) ->
328         let te, fixpoints_s = aux octx ctx n_fix uri te in
329         let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
330         let ctx = Ce (cn_to_s name, NCic.Def (te, ty)) :: ctx in
331         let octx = Some (name, Cic.Def (old_te, old_ty)) :: octx in
332         let t, fixpoints_t = aux octx ctx n_fix uri t in
333         NCic.LetIn (cn_to_s name, ty, te, t), 
334         fixpoints_s @ fixpoints_t @ fixpoints_ty
335     | Cic.Cast (t,ty) ->
336         let t, fixpoints_t = aux octx ctx n_fix uri t in
337         let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
338         NCic.LetIn ("cast", ty, t, NCic.Rel 1), fixpoints_t @ fixpoints_ty
339     | Cic.Sort Cic.Prop -> NCic.Sort NCic.Prop,[]
340     | Cic.Sort Cic.CProp -> NCic.Sort NCic.CProp,[]
341     | Cic.Sort (Cic.Type _) -> NCic.Sort (NCic.Type 0),[] 
342     | Cic.Sort Cic.Set -> NCic.Sort (NCic.Type 0),[] 
343        (* calculate depth in the univ_graph*)
344     | Cic.Appl l -> 
345         let l, fixpoints =
346           List.fold_right 
347              (fun t (l,acc) -> 
348                let t, fixpoints = aux octx ctx n_fix uri t in 
349                (t::l,fixpoints@acc))
350              l ([],[])
351         in
352         (match l with
353         | (NCic.Appl l1)::l2 -> NCic.Appl (l1@l2), fixpoints
354         | _ -> NCic.Appl l, fixpoints)
355     | Cic.Const (curi, ens) -> 
356        aux_ens curi octx ctx n_fix uri ens
357         (match fst(CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
358         | Cic.Constant (_,Some _,_,_,_) ->
359                NCic.Const (Ref.reference_of_ouri curi Ref.Def)
360         | Cic.Constant (_,None,_,_,_) ->
361                NCic.Const (Ref.reference_of_ouri curi Ref.Decl)
362         | _ -> assert false)
363     | Cic.MutInd (curi, tyno, ens) -> 
364        aux_ens curi octx ctx n_fix uri ens
365         (NCic.Const (Ref.reference_of_ouri curi (Ref.Ind tyno)))
366     | Cic.MutConstruct (curi, tyno, consno, ens) -> 
367        aux_ens curi octx ctx n_fix uri ens
368         (NCic.Const (Ref.reference_of_ouri curi (Ref.Con (tyno,consno))))
369     | Cic.Var (curi, ens) ->
370        (match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
371            Cic.Variable (_,Some bo,_,_,_) ->
372             aux octx ctx n_fix uri (CicSubstitution.subst_vars ens bo)
373          | _ -> assert false)
374     | Cic.MutCase (curi, tyno, outty, t, branches) ->
375         let r = Ref.reference_of_ouri curi (Ref.Ind tyno) in
376         let outty, fixpoints_outty = aux octx ctx n_fix uri outty in
377         let t, fixpoints_t = aux octx ctx n_fix uri t in
378         let branches, fixpoints =
379           List.fold_right 
380              (fun t (l,acc) -> 
381                let t, fixpoints = aux octx ctx n_fix uri t in 
382                (t::l,fixpoints@acc))
383              branches ([],[])
384         in
385         NCic.Match (r,outty,t,branches), fixpoints_outty@fixpoints_t@fixpoints
386     | Cic.Implicit _ | Cic.Meta _ -> assert false
387   and aux_ens curi octx ctx n_fix uri ens he =
388    match ens with
389       [] -> he,[]
390     | _::_ ->
391       let params =
392        match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
393           Cic.Constant (_,_,_,params,_)
394         | Cic.InductiveDefinition (_,params,_,_) -> params
395         | Cic.Variable _
396         | Cic.CurrentProof _ -> assert false
397       in
398       let ens,objs =
399        List.fold_right
400         (fun luri (l,objs) ->
401           match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph luri) with
402              Cic.Variable (_,Some _,_,_,_) -> l, objs
403            | Cic.Variable (_,None,_,_,_) ->
404               let t = List.assoc luri ens in
405               let t,o = aux octx ctx n_fix uri t in
406                t::l, o@objs
407            | _ -> assert false
408         ) params ([],[])
409       in
410        NCic.Appl (he::ens),objs
411   in
412    aux [] [] 0 uri t
413 ;;
414
415 let cook mode vars t =
416  let t = fix_outtype t in
417  let varsno = List.length vars in
418  let t = CicSubstitution.lift varsno t in
419  let rec aux n acc l =
420   let subst =
421    snd(List.fold_left (fun (i,res) uri -> i+1,(uri,Cic.Rel i)::res) (1,[]) acc)
422   in
423   match l with
424      [] -> CicSubstitution.subst_vars subst t
425    | uri::uris ->
426     let bo,ty =
427      match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph uri) with
428         Cic.Variable (_,bo,ty,_,_) ->
429          HExtlib.map_option fix_outtype bo, fix_outtype ty
430       | _ -> assert false in
431     let ty = CicSubstitution.subst_vars subst ty in
432     let bo = HExtlib.map_option (CicSubstitution.subst_vars subst) bo in
433     let id = Cic.Name (UriManager.name_of_uri uri) in
434     let t = aux (n-1) (uri::acc) uris in
435      match bo,ty,mode with
436         None,ty,`Lambda -> Cic.Lambda (id,ty,t)
437       | None,ty,`Pi -> Cic.Prod (id,ty,t)
438       | Some bo,ty,_ -> Cic.LetIn (id,bo,ty,t)
439  in
440   aux varsno [] vars
441 ;;
442
443 let convert_obj_aux uri = function
444  | Cic.Constant (name, None, ty, vars, _) ->
445      let ty = cook `Pi vars ty in
446      let nty, fixpoints = convert_term uri ty in
447      assert(fixpoints = []);
448      NCic.Constant ([], name, None, nty, (`Provided,`Theorem,`Regular)),
449      fixpoints
450  | Cic.Constant (name, Some bo, ty, vars, _) ->
451      let bo = cook `Lambda vars bo in
452      let ty = cook `Pi vars ty in
453      let nbo, fixpoints_bo = convert_term uri bo in
454      let nty, fixpoints_ty = convert_term uri ty in
455      assert(fixpoints_ty = []);
456      NCic.Constant ([], name, Some nbo, nty, (`Provided,`Theorem,`Regular)),
457      fixpoints_bo @ fixpoints_ty
458  | Cic.InductiveDefinition (itl,vars,leftno,_) -> 
459      let ind = let _,x,_,_ = List.hd itl in x in
460      let itl, fix_itl = 
461        List.fold_right
462          (fun (name, _, ty, cl) (itl,acc) ->
463             let ty = cook `Pi vars ty in
464             let ty, fix_ty = convert_term uri ty in
465             let cl, fix_cl = 
466               List.fold_right
467                (fun (name, ty) (cl,acc) -> 
468                  let ty = cook `Pi vars ty in
469                  let ty, fix_ty = convert_term uri ty in
470                  ([], name, ty)::cl, acc @ fix_ty)
471                cl ([],[])
472             in
473             ([], name, ty, cl)::itl, fix_ty @ fix_cl @ acc)
474          itl ([],[])
475      in
476      NCic.Inductive(ind, leftno + List.length vars, itl, (`Provided, `Regular)),
477      fix_itl
478  | Cic.Variable _ 
479  | Cic.CurrentProof _ -> assert false
480 ;;
481
482 let convert_obj uri obj = 
483   reset_seed ();
484   let o, fixpoints = convert_obj_aux uri obj in
485   let obj = NUri.nuri_of_ouri uri,max_int, [], [], o in
486   fixpoints @ [obj]
487 ;;