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