]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/oCic2NCic.ml
Fixed serious bug that occurred only in the following situation:
[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 * NCic.obj list
10   | Fix of Ref.reference * string * NCic.term
11
12 let splat mk_pi ctx t =
13   List.fold_left
14     (fun (t,l) c -> 
15       match c with
16       | Ce ((name, NCic.Def (bo,ty)),l') -> NCic.LetIn (name, ty, bo, t),l@l'
17       | Ce ((name, NCic.Decl ty),l') when mk_pi -> NCic.Prod (name, ty, t),l@l'
18       | Ce ((name, NCic.Decl ty),l') -> NCic.Lambda (name, ty, t),l@l'
19       | Fix (_,name,ty) when mk_pi -> NCic.Prod (name, ty, t),l
20       | Fix (_,name,ty) -> NCic.Lambda (name,ty,t),l)
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
31           (function Ce ((_, NCic.Decl _),_) | Fix _ -> true | _ -> false) 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   (* k=true if we are converting a term to be pushed in a ctx or if we are
218             converting the type of a fix;
219      k=false if we are converting a term to be put in the body of a fix;
220      in the latter case, we must permute Rels since the Fix abstraction will
221      preceed its lefts parameters; in the former case, there is nothing to
222      permute *)
223   let rec aux k octx (ctx : ctx list) n_fix uri = function
224     | Cic.CoFix (cofixno, fl) ->
225         let buri = 
226           UriManager.uri_of_string 
227            (UriManager.buri_of_uri uri^"/"^
228             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
229         in
230         let bctx, fixpoints_tys, tys, _ = 
231           List.fold_right 
232             (fun (name,ty,_) (bctx, fixpoints, tys, idx) -> 
233               let ty, fixpoints_ty = aux true octx ctx n_fix uri ty in
234               let r = Ref.reference_of_ouri buri(Ref.CoFix idx) in
235               Fix (r,name,ty) :: bctx, fixpoints_ty @ fixpoints,ty::tys,idx+1)
236             fl ([], [], [], 0)
237         in
238         let bctx = bctx @ ctx in
239         let n_fl = List.length fl in
240         let boctx,_ =
241          List.fold_left
242           (fun (types,len) (n,ty,_) ->
243              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
244               len+1)) (octx,0) fl
245         in
246         let fl, fixpoints =
247           List.fold_right2 
248             (fun (name,_,bo) ty  (l,fixpoints) -> 
249                let bo, fixpoints_bo = aux false boctx bctx n_fl buri bo in
250                let splty,fixpoints_splty = splat true ctx ty in
251                let splbo,fixpoints_splbo = splat false ctx bo in
252                (([],name,~-1,splty,splbo)::l),
253                fixpoints_bo @ fixpoints_splty @ fixpoints_splbo @ fixpoints)
254             fl tys ([],fixpoints_tys)
255         in
256         let obj = 
257           NUri.nuri_of_ouri buri,0,[],[],
258             NCic.Fixpoint (false, fl, (`Generated, `Definition)) 
259         in
260         splat_args ctx 
261          (NCic.Const (Ref.reference_of_ouri buri (Ref.CoFix cofixno)))
262          n_fix,
263         fixpoints @ [obj]
264     | Cic.Fix (fixno, fl) ->
265         let buri = 
266           UriManager.uri_of_string 
267            (UriManager.buri_of_uri uri^"/"^
268             UriManager.name_of_uri uri ^ "___" ^ get_fresh () ^ ".con")
269         in
270         let bad_bctx, fixpoints_tys, tys, _ = 
271           List.fold_right 
272             (fun (name,recno,ty,_) (bctx, fixpoints, tys, idx) -> 
273               let ty, fixpoints_ty = aux true octx ctx n_fix uri ty in
274               let r =  (* recno is dummy here, must be lifted by the ctx len *)
275                 Ref.reference_of_ouri buri (Ref.Fix (idx,recno)) 
276               in
277               Fix (r,name,ty) :: bctx, fixpoints_ty@fixpoints,ty::tys,idx+1)
278             fl ([], [], [], 0)
279         in
280         let _, _, free_decls, _ = context_tassonomy (bad_bctx @ ctx) in
281         let bctx = 
282           List.map (function 
283             | Fix (Ref.Ref (_,_,Ref.Fix (idx, recno)),name, ty) ->
284               Fix (Ref.reference_of_ouri buri
285                     (Ref.Fix (idx,recno+free_decls)),name,ty)
286             | _ -> assert false) bad_bctx @ ctx
287         in
288         let n_fl = List.length fl in
289         let boctx,_ =
290          List.fold_left
291           (fun (types,len) (n,_,ty,_) ->
292              (Some (Cic.Name n,(Cic.Decl (CicSubstitution.lift len ty)))::types,
293               len+1)) (octx,0) fl
294         in
295         let rno_fixno = ref 0 in
296         let fl, fixpoints,_ =
297           List.fold_right2 
298             (fun (name,rno,_,bo) ty (l,fixpoints,idx) -> 
299                let bo, fixpoints_bo = aux false boctx bctx n_fl buri bo in
300                let splty,fixpoints_splty = splat true ctx ty in
301                let splbo,fixpoints_splbo = splat false ctx bo in
302                let rno = rno + free_decls in
303                if idx = fixno then rno_fixno := rno;
304                (([],name,rno,splty,splbo)::l),
305                fixpoints_bo@fixpoints_splty@fixpoints_splbo@fixpoints,idx+1)
306             fl tys ([],fixpoints_tys,0)
307         in
308         let obj = 
309           NUri.nuri_of_ouri buri,max_int,[],[],
310             NCic.Fixpoint (true, fl, (`Generated, `Definition)) 
311         in
312         splat_args ctx
313           (NCic.Const 
314             (Ref.reference_of_ouri buri (Ref.Fix (fixno,!rno_fixno))))
315           n_fix,
316         fixpoints @ [obj]
317     | Cic.Rel n ->
318         let bound, _, _, primo_ce_dopo_fix = context_tassonomy ctx in
319         (match List.nth ctx (n-1) with
320         | Fix (r,_,_) when n < primo_ce_dopo_fix -> 
321             splat_args_for_rel ctx (NCic.Const r), []
322         | Ce _ when n <= bound -> NCic.Rel n, []
323         | Fix _ when n <= bound -> assert false
324         | Fix _ | Ce _ when k = true -> NCic.Rel n, []
325         | Fix _ | Ce _ -> NCic.Rel (n-n_fix), [])
326     | Cic.Lambda (name, (s as old_s), t) ->
327         let s, fixpoints_s = aux k octx ctx n_fix uri s in
328         let s', fixpoints_s' = aux true octx ctx n_fix uri old_s in
329         let ctx = Ce ((cn_to_s name, NCic.Decl s'),fixpoints_s') :: ctx in
330         let octx = Some (name, Cic.Decl old_s) :: octx in
331         let t, fixpoints_t = aux k octx ctx n_fix uri t in
332         NCic.Lambda (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
333     | Cic.Prod (name, (s as old_s), t) ->
334         let s, fixpoints_s = aux k octx ctx n_fix uri s in
335         let s', fixpoints_s' = aux true octx ctx n_fix uri old_s in
336         let ctx = Ce ((cn_to_s name, NCic.Decl s'),fixpoints_s') :: ctx in
337         let octx = Some (name, Cic.Decl old_s) :: octx in
338         let t, fixpoints_t = aux k octx ctx n_fix uri t in
339         NCic.Prod (cn_to_s name, s, t), fixpoints_s @ fixpoints_t
340     | Cic.LetIn (name, (te as old_te), (ty as old_ty), t) ->
341         let te, fixpoints_s = aux k octx ctx n_fix uri te in
342         let te', fixpoints_s' = aux true octx ctx n_fix uri old_te in
343         let ty, fixpoints_ty = aux k octx ctx n_fix uri ty in
344         let ty', fixpoints_ty' = aux true octx ctx n_fix uri old_ty in
345         let fixpoints' = fixpoints_s' @ fixpoints_ty' in
346         let ctx = Ce ((cn_to_s name, NCic.Def (te', ty')),fixpoints') :: ctx in
347         let octx = Some (name, Cic.Def (old_te, old_ty)) :: octx in
348         let t, fixpoints_t = aux k octx ctx n_fix uri t in
349         NCic.LetIn (cn_to_s name, ty, te, t), 
350         fixpoints_s @ fixpoints_t @ fixpoints_ty
351     | Cic.Cast (t,ty) ->
352         let t, fixpoints_t = aux k octx ctx n_fix uri t in
353         let ty, fixpoints_ty = aux k octx ctx n_fix uri ty in
354         NCic.LetIn ("cast", ty, t, NCic.Rel 1), fixpoints_t @ fixpoints_ty
355     | Cic.Sort Cic.Prop -> NCic.Sort NCic.Prop,[]
356     | Cic.Sort Cic.CProp -> NCic.Sort NCic.CProp,[]
357     | Cic.Sort (Cic.Type _) -> NCic.Sort (NCic.Type 0),[] 
358     | Cic.Sort Cic.Set -> NCic.Sort (NCic.Type 0),[] 
359        (* calculate depth in the univ_graph*)
360     | Cic.Appl l -> 
361         let l, fixpoints =
362           List.fold_right 
363              (fun t (l,acc) -> 
364                let t, fixpoints = aux k octx ctx n_fix uri t in 
365                (t::l,fixpoints@acc))
366              l ([],[])
367         in
368         (match l with
369         | (NCic.Appl l1)::l2 -> NCic.Appl (l1@l2), fixpoints
370         | _ -> NCic.Appl l, fixpoints)
371     | Cic.Const (curi, ens) -> 
372        aux_ens k curi octx ctx n_fix uri ens
373         (match fst(CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
374         | Cic.Constant (_,Some _,_,_,_) ->
375                NCic.Const (Ref.reference_of_ouri curi Ref.Def)
376         | Cic.Constant (_,None,_,_,_) ->
377                NCic.Const (Ref.reference_of_ouri curi Ref.Decl)
378         | _ -> assert false)
379     | Cic.MutInd (curi, tyno, ens) -> 
380        aux_ens k curi octx ctx n_fix uri ens
381         (NCic.Const (Ref.reference_of_ouri curi (Ref.Ind tyno)))
382     | Cic.MutConstruct (curi, tyno, consno, ens) -> 
383        aux_ens k curi octx ctx n_fix uri ens
384         (NCic.Const (Ref.reference_of_ouri curi (Ref.Con (tyno,consno))))
385     | Cic.Var (curi, ens) ->
386        (match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
387            Cic.Variable (_,Some bo,_,_,_) ->
388             aux k octx ctx n_fix uri (CicSubstitution.subst_vars ens bo)
389          | _ -> assert false)
390     | Cic.MutCase (curi, tyno, outty, t, branches) ->
391         let r = Ref.reference_of_ouri curi (Ref.Ind tyno) in
392         let outty, fixpoints_outty = aux k octx ctx n_fix uri outty in
393         let t, fixpoints_t = aux k octx ctx n_fix uri t in
394         let branches, fixpoints =
395           List.fold_right 
396              (fun t (l,acc) -> 
397                let t, fixpoints = aux k octx ctx n_fix uri t in 
398                (t::l,fixpoints@acc))
399              branches ([],[])
400         in
401         NCic.Match (r,outty,t,branches), fixpoints_outty@fixpoints_t@fixpoints
402     | Cic.Implicit _ | Cic.Meta _ -> assert false
403   and aux_ens k curi octx ctx n_fix uri ens he =
404    match ens with
405       [] -> he,[]
406     | _::_ ->
407       let params =
408        match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
409           Cic.Constant (_,_,_,params,_)
410         | Cic.InductiveDefinition (_,params,_,_) -> params
411         | Cic.Variable _
412         | Cic.CurrentProof _ -> assert false
413       in
414       let ens,objs =
415        List.fold_right
416         (fun luri (l,objs) ->
417           match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph luri) with
418              Cic.Variable (_,Some _,_,_,_) -> l, objs
419            | Cic.Variable (_,None,_,_,_) ->
420               let t = List.assoc luri ens in
421               let t,o = aux k octx ctx n_fix uri t in
422                t::l, o@objs
423            | _ -> assert false
424         ) params ([],[])
425       in
426        NCic.Appl (he::ens),objs
427   in
428    aux false [] [] 0 uri t
429 ;;
430
431 let cook mode vars t =
432  let t = fix_outtype t in
433  let varsno = List.length vars in
434  let t = CicSubstitution.lift varsno t in
435  let rec aux n acc l =
436   let subst =
437    snd(List.fold_left (fun (i,res) uri -> i+1,(uri,Cic.Rel i)::res) (1,[]) acc)
438   in
439   match l with
440      [] -> CicSubstitution.subst_vars subst t
441    | uri::uris ->
442     let bo,ty =
443      match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph uri) with
444         Cic.Variable (_,bo,ty,_,_) ->
445          HExtlib.map_option fix_outtype bo, fix_outtype ty
446       | _ -> assert false in
447     let ty = CicSubstitution.subst_vars subst ty in
448     let bo = HExtlib.map_option (CicSubstitution.subst_vars subst) bo in
449     let id = Cic.Name (UriManager.name_of_uri uri) in
450     let t = aux (n-1) (uri::acc) uris in
451      match bo,ty,mode with
452         None,ty,`Lambda -> Cic.Lambda (id,ty,t)
453       | None,ty,`Pi -> Cic.Prod (id,ty,t)
454       | Some bo,ty,_ -> Cic.LetIn (id,bo,ty,t)
455  in
456   aux varsno [] vars
457 ;;
458
459 let convert_obj_aux uri = function
460  | Cic.Constant (name, None, ty, vars, _) ->
461      let ty = cook `Pi vars ty in
462      let nty, fixpoints = convert_term uri ty in
463      assert(fixpoints = []);
464      NCic.Constant ([], name, None, nty, (`Provided,`Theorem,`Regular)),
465      fixpoints
466  | Cic.Constant (name, Some bo, ty, vars, _) ->
467      let bo = cook `Lambda vars bo in
468      let ty = cook `Pi vars ty in
469      let nbo, fixpoints_bo = convert_term uri bo in
470      let nty, fixpoints_ty = convert_term uri ty in
471      assert(fixpoints_ty = []);
472      NCic.Constant ([], name, Some nbo, nty, (`Provided,`Theorem,`Regular)),
473      fixpoints_bo @ fixpoints_ty
474  | Cic.InductiveDefinition (itl,vars,leftno,_) -> 
475      let ind = let _,x,_,_ = List.hd itl in x in
476      let itl, fix_itl = 
477        List.fold_right
478          (fun (name, _, ty, cl) (itl,acc) ->
479             let ty = cook `Pi vars ty in
480             let ty, fix_ty = convert_term uri ty in
481             let cl, fix_cl = 
482               List.fold_right
483                (fun (name, ty) (cl,acc) -> 
484                  let ty = cook `Pi vars ty in
485                  let ty, fix_ty = convert_term uri ty in
486                  ([], name, ty)::cl, acc @ fix_ty)
487                cl ([],[])
488             in
489             ([], name, ty, cl)::itl, fix_ty @ fix_cl @ acc)
490          itl ([],[])
491      in
492      NCic.Inductive(ind, leftno + List.length vars, itl, (`Provided, `Regular)),
493      fix_itl
494  | Cic.Variable _ 
495  | Cic.CurrentProof _ -> assert false
496 ;;
497
498 let convert_obj uri obj = 
499   reset_seed ();
500   let o, fixpoints = convert_obj_aux uri obj in
501   let obj = NUri.nuri_of_ouri uri,max_int, [], [], o in
502   fixpoints @ [obj]
503 ;;