]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/oCic2NCic.ml
Use seed to avoid further name clashes.
[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 =
198  let seed = ref 0 in
199   function () ->
200    incr seed;
201    string_of_int !seed
202 ;;
203
204 (* we are lambda-lifting also variables that do not occur *)
205 (* ctx does not distinguish successive blocks of cofix, since there may be no
206  *   lambda separating them *)
207 let convert_term uri t = 
208   let rec aux octx (ctx : ctx list) n_fix uri = function
209     | Cic.CoFix (k, fl) ->
210         let buri = 
211           UriManager.uri_of_string 
212            (UriManager.buri_of_uri uri^"/"^
213             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
214         in
215         let bctx, fixpoints_tys, tys, _ = 
216           List.fold_right 
217             (fun (name,ty,_) (ctx, fixpoints, tys, idx) -> 
218               let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
219               let r = Ref.reference_of_ouri buri(Ref.CoFix idx) in
220               Fix (r,name,ty) :: ctx, fixpoints_ty @ fixpoints,ty::tys,idx+1)
221             fl ([], [], [], 0)
222         in
223         let bctx = bctx @ ctx in
224         let n_fl = List.length fl in
225         let boctx,_ =
226          List.fold_left
227           (fun (types,len) (n,ty,_) ->
228              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
229               len+1)) (octx,0) fl
230         in
231         let fl, fixpoints =
232           List.fold_right2 
233             (fun (name,_,bo) ty  (l,fixpoints) -> 
234                let bo, fixpoints_bo = aux boctx bctx n_fl buri bo in
235                (([],name,~-1,splat true ctx ty, splat false ctx bo)::l),
236                fixpoints_bo @ fixpoints)
237             fl tys ([],fixpoints_tys)
238         in
239         let obj = 
240           NUri.nuri_of_ouri buri,0,[],[],
241             NCic.Fixpoint (false, fl, (`Generated, `Definition)) 
242         in
243         splat_args ctx 
244          (NCic.Const (Ref.reference_of_ouri buri (Ref.CoFix k)))
245          n_fix,
246         fixpoints @ [obj]
247     | Cic.Fix (k, fl) ->
248         let buri = 
249           UriManager.uri_of_string 
250            (UriManager.buri_of_uri uri^"/"^
251             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
252         in
253         let bad_bctx, fixpoints_tys, tys, _ = 
254           List.fold_right 
255             (fun (name,recno,ty,_) (bctx, fixpoints, tys, idx) -> 
256               let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
257               let r =  (* recno is dummy here, must be lifted by the ctx len *)
258                 Ref.reference_of_ouri buri (Ref.Fix (idx,recno)) 
259               in
260               Fix (r,name,ty) :: bctx, fixpoints_ty@fixpoints,ty::tys,idx+1)
261             fl ([], [], [], 0)
262         in
263         let _, free, _ = context_tassonomy (bad_bctx @ ctx) in
264         let bctx = 
265           List.map (function 
266             | Fix (Ref.Ref (_,_,Ref.Fix (idx, recno)),name, ty) ->
267               Fix (Ref.reference_of_ouri buri(Ref.Fix (idx,recno+free)),name,ty)
268             | _ -> assert false) bad_bctx @ ctx
269         in
270         let n_fl = List.length fl in
271         let boctx,_ =
272          List.fold_left
273           (fun (types,len) (n,_,ty,_) ->
274              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
275               len+1)) (octx,0) fl
276         in
277         let rno_k = ref 0 in
278         let fl, fixpoints,_ =
279           List.fold_right2 
280             (fun (name,rno,_,bo) ty (l,fixpoints,idx) -> 
281                let bo, fixpoints_bo = aux boctx bctx n_fl buri bo in
282                let rno = rno + free in
283                if idx = k then rno_k := rno;
284                (([],name,rno,splat true ctx ty, splat false ctx bo)::l),
285                fixpoints_bo @ fixpoints,idx+1)
286             fl tys ([],fixpoints_tys,0)
287         in
288         let obj = 
289           NUri.nuri_of_ouri buri,max_int,[],[],
290             NCic.Fixpoint (true, fl, (`Generated, `Definition)) 
291         in
292         splat_args ctx
293           (NCic.Const 
294             (Ref.reference_of_ouri buri (Ref.Fix (k,!rno_k))))
295           n_fix,
296         fixpoints @ [obj]
297     | Cic.Rel n ->
298         let bound, _, primo_ce_dopo_fix = context_tassonomy ctx in
299         (match List.nth ctx (n-1) with
300         | Fix (r,_,_) when n < primo_ce_dopo_fix -> 
301             splat_args_for_rel ctx (NCic.Const r), []
302         | Ce _ when n <= bound -> NCic.Rel n, []
303         | Fix _ (* BUG 3 fix nested *) 
304         | Ce _ -> NCic.Rel (n-n_fix), [])
305     | Cic.Lambda (name, (s as old_s), t) ->
306         let s, fixpoints_s = aux octx ctx n_fix uri s in
307         let ctx = Ce (cn_to_s name, NCic.Decl s) :: ctx in
308         let octx = Some (name, Cic.Decl old_s) :: octx in
309         let t, fixpoints_t = aux octx ctx n_fix uri t in
310         NCic.Lambda (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
311     | Cic.Prod (name, (s as old_s), t) ->
312         let s, fixpoints_s = aux octx ctx n_fix uri s in
313         let ctx = Ce (cn_to_s name, NCic.Decl s) :: ctx in
314         let octx = Some (name, Cic.Decl old_s) :: octx in
315         let t, fixpoints_t = aux octx ctx n_fix uri t in
316         NCic.Prod (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
317     | Cic.LetIn (name, (te as old_te), (ty as old_ty), t) ->
318         let te, fixpoints_s = aux octx ctx n_fix uri te in
319         let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
320         let ctx = Ce (cn_to_s name, NCic.Def (te, ty)) :: ctx in
321         let octx = Some (name, Cic.Def (old_te, old_ty)) :: octx in
322         let t, fixpoints_t = aux octx ctx n_fix uri t in
323         NCic.LetIn (cn_to_s name, ty, te, t), 
324         fixpoints_s @ fixpoints_t @ fixpoints_ty
325     | Cic.Cast (t,ty) ->
326         let t, fixpoints_t = aux octx ctx n_fix uri t in
327         let ty, fixpoints_ty = aux octx ctx n_fix uri ty in
328         NCic.LetIn ("cast", ty, t, NCic.Rel 1), fixpoints_t @ fixpoints_ty
329     | Cic.Sort Cic.Prop -> NCic.Sort NCic.Prop,[]
330     | Cic.Sort Cic.CProp -> NCic.Sort NCic.CProp,[]
331     | Cic.Sort (Cic.Type _) -> NCic.Sort (NCic.Type 0),[] 
332     | Cic.Sort Cic.Set -> NCic.Sort (NCic.Type 0),[] 
333        (* calculate depth in the univ_graph*)
334     | Cic.Appl l -> 
335         let l, fixpoints =
336           List.fold_right 
337              (fun t (l,acc) -> 
338                let t, fixpoints = aux octx ctx n_fix uri t in 
339                (t::l,fixpoints@acc))
340              l ([],[])
341         in
342         (match l with
343         | (NCic.Appl l1)::l2 -> NCic.Appl (l1@l2), fixpoints
344         | _ -> NCic.Appl l, fixpoints)
345     | Cic.Const (curi, ens) -> 
346        aux_ens curi octx ctx n_fix uri ens
347         (match fst(CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
348         | Cic.Constant (_,Some _,_,_,_) ->
349                NCic.Const (Ref.reference_of_ouri curi Ref.Def)
350         | Cic.Constant (_,None,_,_,_) ->
351                NCic.Const (Ref.reference_of_ouri curi Ref.Decl)
352         | _ -> assert false)
353     | Cic.MutInd (curi, tyno, ens) -> 
354        aux_ens curi octx ctx n_fix uri ens
355         (NCic.Const (Ref.reference_of_ouri curi (Ref.Ind tyno)))
356     | Cic.MutConstruct (curi, tyno, consno, ens) -> 
357        aux_ens curi octx ctx n_fix uri ens
358         (NCic.Const (Ref.reference_of_ouri curi (Ref.Con (tyno,consno))))
359     | Cic.MutCase (curi, tyno, outty, t, branches) ->
360         let r = Ref.reference_of_ouri curi (Ref.Ind tyno) in
361         let outty, fixpoints_outty = aux octx ctx n_fix uri outty in
362         let t, fixpoints_t = aux octx ctx n_fix uri t in
363         let branches, fixpoints =
364           List.fold_right 
365              (fun t (l,acc) -> 
366                let t, fixpoints = aux octx ctx n_fix uri t in 
367                (t::l,fixpoints@acc))
368              branches ([],[])
369         in
370         NCic.Match (r,outty,t,branches), fixpoints_outty@fixpoints_t@fixpoints
371     | Cic.Implicit _ | Cic.Meta _ | Cic.Var _ -> assert false
372   and aux_ens curi octx ctx n_fix uri ens he =
373    match ens with
374       [] -> he,[]
375     | _::_ ->
376       let params =
377        match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
378           Cic.Constant (_,_,_,params,_)
379         | Cic.InductiveDefinition (_,params,_,_) -> params
380         | Cic.Variable _
381         | Cic.CurrentProof _ -> assert false
382       in
383       let ens,objs =
384        List.fold_right
385         (fun uri (l,objs) ->
386           let t = List.assoc uri ens in
387           let t,o = aux octx ctx n_fix uri t in
388            t::l, o@objs
389         ) params ([],[])
390       in
391        NCic.Appl (he::ens),objs
392   in
393    aux [] [] 0 uri t
394 ;;
395
396 let cook mode vars t =
397  let t = fix_outtype t in
398  let varsno = List.length vars in
399  let t = CicSubstitution.lift varsno t in
400  let rec aux n acc l =
401   let subst =
402    snd(List.fold_left (fun (i,res) uri -> i+1,(uri,Cic.Rel i)::res) (1,[]) acc)
403   in
404   match l with
405      [] -> CicSubstitution.subst_vars subst t
406    | uri::uris ->
407     let bo,ty =
408      match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph uri) with
409         Cic.Variable (_,bo,ty,_,_) ->
410          HExtlib.map_option fix_outtype bo, fix_outtype ty
411       | _ -> assert false in
412     let ty = CicSubstitution.subst_vars subst ty in
413     let bo = HExtlib.map_option (CicSubstitution.subst_vars subst) bo in
414     let id = Cic.Name (UriManager.name_of_uri uri) in
415     let t = aux (n-1) (uri::acc) uris in
416      match bo,ty,mode with
417         None,ty,`Lambda -> Cic.Lambda (id,ty,t)
418       | None,ty,`Pi -> Cic.Prod (id,ty,t)
419       | Some bo,ty,_ -> Cic.LetIn (id,bo,ty,t)
420  in
421   aux varsno [] vars
422 ;;
423
424 let convert_obj_aux uri = function
425  | Cic.Constant (name, None, ty, vars, _) ->
426      let ty = cook `Pi vars ty in
427      let nty, fixpoints = convert_term uri ty in
428      assert(fixpoints = []);
429      NCic.Constant ([], name, None, nty, (`Provided,`Theorem,`Regular)),
430      fixpoints
431  | Cic.Constant (name, Some bo, ty, vars, _) ->
432      let bo = cook `Lambda vars bo in
433      let ty = cook `Pi vars ty in
434      let nbo, fixpoints_bo = convert_term uri bo in
435      let nty, fixpoints_ty = convert_term uri ty in
436      assert(fixpoints_ty = []);
437      NCic.Constant ([], name, Some nbo, nty, (`Provided,`Theorem,`Regular)),
438      fixpoints_bo @ fixpoints_ty
439  | Cic.InductiveDefinition (itl,vars,leftno,_) -> 
440      let ind = let _,x,_,_ = List.hd itl in x in
441      let itl, fix_itl = 
442        List.fold_right
443          (fun (name, _, ty, cl) (itl,acc) ->
444             let ty = cook `Pi vars ty in
445             let ty, fix_ty = convert_term uri ty in
446             let cl, fix_cl = 
447               List.fold_right
448                (fun (name, ty) (cl,acc) -> 
449                  let ty = cook `Pi vars ty in
450                  let ty, fix_ty = convert_term uri ty in
451                  ([], name, ty)::cl, acc @ fix_ty)
452                cl ([],[])
453             in
454             ([], name, ty, cl)::itl, fix_ty @ fix_cl @ acc)
455          itl ([],[])
456      in
457      NCic.Inductive(ind, leftno + List.length vars, itl, (`Provided, `Regular)),
458      fix_itl
459  | Cic.Variable _ 
460  | Cic.CurrentProof _ -> assert false
461 ;;
462
463 let convert_obj uri obj = 
464   let o, fixpoints = convert_obj_aux uri obj in
465   let obj = NUri.nuri_of_ouri uri,max_int, [], [], o in
466   fixpoints @ [obj]
467 ;;