]> matita.cs.unibo.it Git - helm.git/blob - components/cic/cicUtil.ml
tagged 0.5.0-rc1
[helm.git] / components / cic / cicUtil.ml
1 (* Copyright (C) 2004, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 module C = Cic
29
30 exception Meta_not_found of int
31 exception Subst_not_found of int
32
33 let lookup_meta index metasenv =
34   try
35     List.find (fun (index', _, _) -> index = index') metasenv
36   with Not_found -> raise (Meta_not_found index)
37
38 let lookup_subst n subst =
39   try
40     List.assoc n subst
41   with Not_found -> raise (Subst_not_found n)
42
43 let exists_meta index = List.exists (fun (index', _, _) -> (index = index'))
44
45 (* clean_up_meta take a substitution, a metasenv a meta_inex and a local
46 context l and clean up l with respect to the hidden hipothesis in the 
47 canonical context *)
48
49 let clean_up_local_context subst metasenv n l =
50   let cc =
51     (try
52        let (cc,_,_) = lookup_subst n subst in cc
53      with Subst_not_found _ ->
54        try
55          let (_,cc,_) = lookup_meta n metasenv in cc
56        with Meta_not_found _ -> assert false) in
57   (try 
58      List.map2
59        (fun t1 t2 ->
60           match t1,t2 with 
61               None , _ -> None
62             | _ , t -> t) cc l
63    with 
64        Invalid_argument _ -> 
65          assert false)
66
67 let is_closed =
68  let module C = Cic in
69  let rec is_closed k =
70   function
71       C.Rel m when m > k -> false
72     | C.Rel m -> true
73     | C.Meta (_,l) ->
74        List.fold_left
75         (fun i t -> i && (match t with None -> true | Some t -> is_closed k t)
76         ) true l
77     | C.Sort _ -> true
78     | C.Implicit _ -> assert false
79     | C.Cast (te,ty) -> is_closed k te && is_closed k ty
80     | C.Prod (name,so,dest) -> is_closed k so && is_closed (k+1) dest
81     | C.Lambda (_,so,dest) -> is_closed k so && is_closed (k+1) dest
82     | C.LetIn (_,so,ty,dest) ->
83        is_closed k so && is_closed k ty && is_closed (k+1) dest
84     | C.Appl l ->
85        List.fold_right (fun x i -> i && is_closed k x) l true
86     | C.Var (_,exp_named_subst)
87     | C.Const (_,exp_named_subst)
88     | C.MutInd (_,_,exp_named_subst)
89     | C.MutConstruct (_,_,_,exp_named_subst) ->
90        List.fold_right (fun (_,x) i -> i && is_closed k x)
91         exp_named_subst true
92     | C.MutCase (_,_,out,te,pl) ->
93        is_closed k out && is_closed k te &&
94         List.fold_right (fun x i -> i && is_closed k x) pl true
95     | C.Fix (_,fl) ->
96        let len = List.length fl in
97         let k_plus_len = k + len in
98          List.fold_right
99           (fun (_,_,ty,bo) i -> i && is_closed k ty && is_closed k_plus_len bo
100           ) fl true
101     | C.CoFix (_,fl) ->
102        let len = List.length fl in
103         let k_plus_len = k + len in
104          List.fold_right
105           (fun (_,ty,bo) i -> i && is_closed k ty && is_closed k_plus_len bo
106           ) fl true
107 in 
108  is_closed 0
109 ;;
110
111 let rec is_meta_closed =
112   function
113       C.Rel _ -> true
114     | C.Meta _ -> false
115     | C.Sort _ -> true
116     | C.Implicit _ -> assert false
117     | C.Cast (te,ty) -> is_meta_closed te && is_meta_closed ty
118     | C.Prod (name,so,dest) -> is_meta_closed so && is_meta_closed dest
119     | C.Lambda (_,so,dest) -> is_meta_closed so && is_meta_closed dest
120     | C.LetIn (_,so,ty,dest) ->
121        is_meta_closed so &&
122        is_meta_closed ty &&
123        is_meta_closed dest
124     | C.Appl l ->
125        not (List.exists (fun x -> not (is_meta_closed x)) l)
126     | C.Var (_,exp_named_subst)
127     | C.Const (_,exp_named_subst)
128     | C.MutInd (_,_,exp_named_subst)
129     | C.MutConstruct (_,_,_,exp_named_subst) ->
130        not (List.exists (fun (_,x) -> not (is_meta_closed x)) exp_named_subst)
131     | C.MutCase (_,_,out,te,pl) ->
132        is_meta_closed out && is_meta_closed te &&
133         not (List.exists (fun x -> not (is_meta_closed x)) pl)
134     | C.Fix (_,fl) ->
135         not (List.exists 
136               (fun (_,_,ty,bo) -> 
137                   not (is_meta_closed ty) || not (is_meta_closed bo)) 
138               fl)
139     | C.CoFix (_,fl) ->
140         not (List.exists 
141               (fun (_,ty,bo) -> 
142                   not (is_meta_closed ty) || not (is_meta_closed bo)) 
143               fl)
144 ;;
145
146 let xpointer_RE = Str.regexp "\\([^#]+\\)#xpointer(\\(.*\\))"
147 let slash_RE = Str.regexp "/"
148
149 let term_of_uri uri =
150   let s = UriManager.string_of_uri uri in
151   try
152     (if UriManager.uri_is_con uri then
153       C.Const (uri, [])
154     else if UriManager.uri_is_var uri then
155       C.Var (uri, [])
156     else if not (Str.string_match xpointer_RE s 0) then
157       raise (UriManager.IllFormedUri s)
158     else
159       let (baseuri,xpointer) = (Str.matched_group 1 s, Str.matched_group 2 s) in
160       let baseuri = UriManager.uri_of_string baseuri in
161       (match Str.split slash_RE xpointer with
162       | [_; tyno] -> C.MutInd (baseuri, int_of_string tyno - 1, [])
163       | [_; tyno; consno] ->
164           C.MutConstruct
165             (baseuri, int_of_string tyno - 1, int_of_string consno, [])
166       | _ -> raise Exit))
167   with
168   | Exit
169   | Failure _
170   | Not_found -> raise (UriManager.IllFormedUri s)
171
172 let uri_of_term = function
173   | C.Const (uri, _)
174   | C.Var (uri, _) -> uri
175   | C.MutInd (baseuri, tyno, _) ->
176      UriManager.uri_of_string
177       (Printf.sprintf "%s#xpointer(1/%d)" (UriManager.string_of_uri baseuri) (tyno+1))
178   | C.MutConstruct (baseuri, tyno, consno, _) ->
179      UriManager.uri_of_string
180       (Printf.sprintf "%s#xpointer(1/%d/%d)" (UriManager.string_of_uri baseuri)
181         (tyno + 1) consno)
182   | _ -> raise (Invalid_argument "uri_of_term")
183
184
185 (*
186 let pack terms =
187   List.fold_right
188     (fun term acc -> C.Prod (C.Anonymous, term, acc))
189     terms (C.Sort (C.Type (CicUniv.fresh ())))
190
191 let rec unpack = function
192   | C.Prod (C.Anonymous, term, C.Sort (C.Type _)) -> [term]
193   | C.Prod (C.Anonymous, term, tgt) -> term :: unpack tgt
194   | _ -> assert false
195 *)
196
197 let rec strip_prods n = function
198   | t when n = 0 -> t
199   | C.Prod (_, _, tgt) when n > 0 -> strip_prods (n-1) tgt
200   | _ -> failwith "not enough prods"
201
202 let params_of_obj = function
203   | C.Constant (_, _, _, params, _)
204   | C.Variable (_, _, _, params, _)
205   | C.CurrentProof (_, _, _, _, params, _)
206   | C.InductiveDefinition (_, params, _, _) ->
207       params
208
209 let attributes_of_obj = function
210   | C.Constant (_, _, _, _, attributes)
211   | C.Variable (_, _, _, _, attributes)
212   | C.CurrentProof (_, _, _, _, _, attributes)
213   | C.InductiveDefinition (_, _, _, attributes) ->
214       attributes
215
216 let is_generated obj = List.exists ((=) `Generated) (attributes_of_obj obj)
217
218 let arity_of_composed_coercion obj =
219   let attrs = attributes_of_obj obj in
220   try
221     let tag=List.find (function `Class (`Coercion _) -> true|_->false) attrs in
222     match tag with
223     |  `Class (`Coercion n) -> n
224     | _-> assert false 
225   with Not_found -> 0
226 ;;
227
228 let projections_of_record obj uri =
229   let attrs = attributes_of_obj obj in
230   try
231     let tag=List.find (function `Class (`Record _) -> true|_->false) attrs in
232     match tag with
233     |  `Class (`Record l) -> 
234          List.map (fun (name,_,_) ->
235            let buri = UriManager.buri_of_uri uri in
236            let puri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ".con") in
237            puri) l
238     | _-> assert false 
239   with Not_found -> []
240 ;;
241       
242 let rec mk_rels howmany from =
243   match howmany with 
244   | 0 -> []
245   | _ -> (C.Rel (howmany + from)) :: (mk_rels (howmany-1) from)
246
247 let id_of_annterm =
248   function
249   | C.ARel (id,_,_,_)
250   | C.AVar (id,_,_)
251   | C.AMeta (id,_,_)
252   | C.ASort (id,_)
253   | C.AImplicit (id,_)
254   | C.ACast (id,_,_)
255   | C.AProd (id,_,_,_)
256   | C.ALambda (id,_,_,_)
257   | C.ALetIn (id,_,_,_,_)
258   | C.AAppl (id,_)
259   | C.AConst (id,_,_)
260   | C.AMutInd (id,_,_,_)
261   | C.AMutConstruct (id,_,_,_,_)
262   | C.AMutCase (id,_,_,_,_,_)
263   | C.AFix (id,_,_)
264   | C.ACoFix (id,_,_) -> id
265
266
267 let rec rehash_term =
268   let module C = Cic in
269   let recons uri = UriManager.uri_of_string (UriManager.string_of_uri uri) in
270   function
271    | (C.Rel _) as t -> t
272    | C.Var (uri,exp_named_subst) ->
273       let uri' = recons uri in
274       let exp_named_subst' =
275        List.map
276         (function (uri,t) ->(recons uri,rehash_term t)) 
277          exp_named_subst
278       in
279        C.Var (uri',exp_named_subst')
280    | C.Meta (i,l) ->
281       let l' =
282        List.map
283         (function
284             None -> None
285           | Some t -> Some (rehash_term t)
286         ) l
287       in
288        C.Meta(i,l')
289    | C.Sort (C.Type u) -> 
290        CicUniv.assert_univ u;
291        C.Sort (C.Type (CicUniv.recons_univ u))
292    | C.Sort _ as t -> t
293    | C.Implicit _ as t -> t
294    | C.Cast (te,ty) -> C.Cast (rehash_term te, rehash_term ty)
295    | C.Prod (n,s,t) -> C.Prod (n, rehash_term s, rehash_term t)
296    | C.Lambda (n,s,t) -> C.Lambda (n, rehash_term s, rehash_term t)
297    | C.LetIn (n,s,ty,t) ->
298       C.LetIn (n, rehash_term s, rehash_term ty, rehash_term t)
299    | C.Appl l -> C.Appl (List.map rehash_term l)
300    | C.Const (uri,exp_named_subst) ->
301       let uri' = recons uri in
302       let exp_named_subst' = 
303        List.map
304         (function (uri,t) -> (recons uri,rehash_term t)) exp_named_subst
305       in
306        C.Const (uri',exp_named_subst')
307    | C.MutInd (uri,tyno,exp_named_subst) ->
308       let uri' = recons uri in
309       let exp_named_subst' = 
310        List.map
311         (function (uri,t) -> (recons uri,rehash_term t)) exp_named_subst
312       in
313        C.MutInd (uri',tyno,exp_named_subst')
314    | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
315       let uri' = recons uri in
316       let exp_named_subst' = 
317        List.map
318         (function (uri,t) -> (recons uri,rehash_term t)) exp_named_subst
319       in
320        C.MutConstruct (uri',tyno,consno,exp_named_subst')
321    | C.MutCase (uri,i,outty,t,pl) ->
322       C.MutCase (recons uri, i, rehash_term outty, rehash_term t,
323        List.map rehash_term pl)
324    | C.Fix (i, fl) ->
325       let liftedfl =
326        List.map
327         (fun (name, i, ty, bo) ->
328           (name, i, rehash_term ty, rehash_term bo))
329          fl
330       in
331        C.Fix (i, liftedfl)
332    | C.CoFix (i, fl) ->
333       let liftedfl =
334        List.map
335         (fun (name, ty, bo) -> (name, rehash_term ty, rehash_term bo))
336          fl
337       in
338        C.CoFix (i, liftedfl)
339
340 let rehash_obj =
341  let module C = Cic in
342  let recons uri = UriManager.uri_of_string (UriManager.string_of_uri uri) in
343  function 
344    C.Constant (name,bo,ty,params,attrs) ->
345      let bo' =
346        match bo with
347          None -> None
348        | Some bo -> Some (rehash_term bo)
349      in
350      let ty' = rehash_term ty in
351      let params' = List.map recons params in
352      C.Constant (name, bo', ty', params',attrs)
353  | C.CurrentProof (name,conjs,bo,ty,params,attrs) ->
354      let conjs' =
355        List.map
356          (function (i,hyps,ty) ->
357            (i,
358            List.map (function
359                None -> None
360              | Some (name,C.Decl t) ->
361                  Some (name,C.Decl (rehash_term t))
362              | Some (name,C.Def (bo,ty)) ->
363                  Some (name,C.Def (rehash_term bo, rehash_term ty))) hyps,
364            rehash_term ty))
365          conjs
366      in
367      let bo' = rehash_term bo in
368      let ty' = rehash_term ty in
369      let params' = List.map recons params in
370      C.CurrentProof (name, conjs', bo', ty', params',attrs)
371  | C.Variable (name,bo,ty,params,attrs) ->
372      let bo' =
373        match bo with
374          None -> None
375        | Some bo -> Some (rehash_term bo)
376      in
377      let ty' = rehash_term ty in
378      let params' = List.map recons params in
379      C.Variable (name, bo', ty', params',attrs)
380  | C.InductiveDefinition (tl,params,paramsno,attrs) ->
381      let params' = List.map recons params in
382      let tl' =
383        List.map (function (name, inductive, ty, constructors) ->
384          name,
385          inductive,
386          rehash_term ty,
387          (List.map
388            (function (name, ty) -> name, rehash_term ty)
389            constructors))
390          tl
391      in
392      C.InductiveDefinition (tl', params', paramsno, attrs)
393
394 let rec metas_of_term = function
395   | C.Meta (i, c) -> [i,c]
396   | C.Var (_, ens) 
397   | C.Const (_, ens) 
398   | C.MutInd (_, _, ens) 
399   | C.MutConstruct (_, _, _, ens) ->
400       List.flatten (List.map (fun (u, t) -> metas_of_term t) ens)
401   | C.Cast (s, t)
402   | C.Prod (_, s, t)
403   | C.Lambda (_, s, t) -> (metas_of_term s) @ (metas_of_term t)
404   | C.LetIn (_, s, ty, t) ->
405      (metas_of_term s) @ (metas_of_term ty) @ (metas_of_term t)
406   | C.Appl l -> List.flatten (List.map metas_of_term l)
407   | C.MutCase (uri, i, s, t, l) ->
408       (metas_of_term s) @ (metas_of_term t) @
409         (List.flatten (List.map metas_of_term l))
410   | C.Fix (i, il) ->
411       List.flatten
412         (List.map (fun (s, i, t1, t2) ->
413                      (metas_of_term t1) @ (metas_of_term t2)) il)
414   | C.CoFix (i, il) ->
415       List.flatten
416         (List.map (fun (s, t1, t2) ->
417                      (metas_of_term t1) @ (metas_of_term t2)) il)
418   | _ -> []
419 ;;      
420
421 module MetaOT = struct
422   type t = int * C.term option list
423   let compare = Pervasives.compare
424 end
425
426 module S = Set.Make(MetaOT)
427
428 let rec metas_of_term_set = function
429   | C.Meta (i, c) -> S.singleton (i,c)
430   | C.Var (_, ens) 
431   | C.Const (_, ens) 
432   | C.MutInd (_, _, ens) 
433   | C.MutConstruct (_, _, _, ens) ->
434       List.fold_left 
435         (fun s (_,t) -> S.union s (metas_of_term_set t)) 
436         S.empty ens
437   | C.Cast (s, t)
438   | C.Prod (_, s, t)
439   | C.Lambda (_, s, t) -> S.union (metas_of_term_set s) (metas_of_term_set t)
440   | C.LetIn (_, s, ty, t) ->
441      S.union (metas_of_term_set s)
442       (S.union (metas_of_term_set ty) (metas_of_term_set t))
443   | C.Appl l -> 
444       List.fold_left 
445         (fun s t -> S.union s (metas_of_term_set t)) 
446         S.empty l
447   | C.MutCase (uri, i, s, t, l) ->
448       S.union 
449         (S.union (metas_of_term_set s)  (metas_of_term_set t))
450         (List.fold_left 
451           (fun s t -> S.union s (metas_of_term_set t)) 
452           S.empty l)
453   | C.Fix (_, il) ->
454       (List.fold_left 
455         (fun s (_,_,t1,t2) -> 
456           S.union s (S.union (metas_of_term_set t1) (metas_of_term_set t2))))
457         S.empty il
458   | C.CoFix (i, il) ->
459       (List.fold_left 
460         (fun s (_,t1,t2) -> 
461           S.union s (S.union (metas_of_term_set t1) (metas_of_term_set t2))))
462         S.empty il
463   | _ -> S.empty
464 ;;      
465
466 let metas_of_term_set t = 
467   let s = metas_of_term_set t in
468   S.elements s
469 ;;
470
471 (* syntactic_equality up to the                 *)
472 (* distinction between fake dependent products  *)
473 (* and non-dependent products, alfa-conversion  *)
474 let alpha_equivalence =
475   let rec aux t t' =
476    if t = t' then true
477    else
478     match t,t' with
479        C.Var (uri1,exp_named_subst1), C.Var (uri2,exp_named_subst2) ->
480         UriManager.eq uri1 uri2 &&
481          aux_exp_named_subst exp_named_subst1 exp_named_subst2
482      | C.Cast (te,ty), C.Cast (te',ty') ->
483         aux te te' && aux ty ty'
484      | C.Prod (_,s,t), C.Prod (_,s',t') ->
485         aux s s' && aux t t'
486      | C.Lambda (_,s,t), C.Lambda (_,s',t') ->
487         aux s s' && aux t t'
488      | C.LetIn (_,s,ty,t), C.LetIn(_,s',ty',t') ->
489         aux s s' && aux ty ty' && aux t t'
490      | C.Appl l, C.Appl l' when List.length l = List.length l' ->
491         (try
492           List.fold_left2
493            (fun b t1 t2 -> b && aux t1 t2) true l l'
494          with
495           Invalid_argument _ -> false)
496      | C.Const (uri,exp_named_subst1), C.Const (uri',exp_named_subst2) ->
497         UriManager.eq uri uri' &&
498          aux_exp_named_subst exp_named_subst1 exp_named_subst2
499      | C.MutInd (uri,i,exp_named_subst1), C.MutInd (uri',i',exp_named_subst2) ->
500         UriManager.eq uri uri' && i = i' &&
501          aux_exp_named_subst exp_named_subst1 exp_named_subst2
502      | C.MutConstruct (uri,i,j,exp_named_subst1),
503        C.MutConstruct (uri',i',j',exp_named_subst2) ->
504         UriManager.eq uri uri' && i = i' && j = j' &&
505          aux_exp_named_subst exp_named_subst1 exp_named_subst2
506      | C.MutCase (sp,i,outt,t,pl), C.MutCase (sp',i',outt',t',pl') ->
507         UriManager.eq sp sp' && i = i' &&
508          aux outt outt' && aux t t' &&
509           (try
510             List.fold_left2
511              (fun b t1 t2 -> b && aux t1 t2) true pl pl'
512            with
513             Invalid_argument _ -> false)
514      | C.Fix (i,fl), C.Fix (i',fl') ->
515         i = i' &&
516         (try
517           List.fold_left2
518            (fun b (_,i,ty,bo) (_,i',ty',bo') ->
519              b && i = i' && aux ty ty' && aux bo bo'
520            ) true fl fl'
521          with
522           Invalid_argument _ -> false)
523      | C.CoFix (i,fl), C.CoFix (i',fl') ->
524         i = i' &&
525         (try
526           List.fold_left2
527            (fun b (_,ty,bo) (_,ty',bo') ->
528              b && aux ty ty' && aux bo bo'
529            ) true fl fl'
530          with
531           Invalid_argument _ -> false)
532      | C.Meta (i, subst), C.Meta (i', subst') ->
533         i = i' &&
534         (try
535           List.fold_left2
536            (fun b xt xt' -> match xt,xt' with
537              | Some t, Some t' -> b && aux t t'
538              | _               -> b
539            ) true subst subst'
540          with
541           Invalid_argument _ -> false)
542      | C.Appl [t], t' | t, C.Appl [t'] -> assert false
543 (* FG: are we _really_ sure of these?      
544      | C.Sort (C.Type u), C.Sort (C.Type u') -> u = u' 
545      | C.Implicit a, C.Implicit a' -> a = a'
546    we insert an unused variable below to genarate a warning at compile time
547 *)     
548      | _,_ -> false (* we already know that t != t' *)
549   and aux_exp_named_subst exp_named_subst1 exp_named_subst2 =
550    try
551      List.fold_left2
552       (fun b (uri1,t1) (uri2,t2) ->
553         b && UriManager.eq uri1 uri2 && aux t1 t2
554       ) true exp_named_subst1 exp_named_subst2
555     with
556      Invalid_argument _ -> false
557   in
558    aux
559
560 let is_sober t =
561    let rec sober_term g = function
562       | C.Rel _ 
563       | C.Sort _  
564       | C.Implicit _                    -> g      
565       | C.Const (_, xnss) 
566       | C.Var (_, xnss) 
567       | C.MutConstruct (_, _, _, xnss)
568       | C.MutInd (_, _, xnss)           -> sober_xnss g xnss
569       | C.Meta (_, xss)                 -> sober_xss g xss
570       | C.Lambda (_, v, t)
571       | C.Prod (_, v, t)
572       | C.Cast (t, v)                   -> sober_term (sober_term g t) v
573       | C.LetIn (_, v, ty, t)           -> sober_term
574                                             (sober_term (sober_term g t) ty) v
575       | C.Appl []                       
576       | C.Appl [_]                      -> fun b -> false
577       | C.Appl ts                       -> sober_terms g ts
578       | C.MutCase (_, _, t, v, ts)      -> 
579          sober_terms (sober_term (sober_term g t) v) ts
580       | C.Fix (_, ifs)                  -> sober_ifs g ifs
581       | C.CoFix (_, cifs)               -> sober_cifs g cifs
582    and sober_terms g = List.fold_left sober_term g
583    and sober_xnss g =
584       let map g (_, t) = sober_term g t in
585       List.fold_left map g
586    and sober_xss g =
587       let map g = function 
588          | None   -> g
589          | Some t -> sober_term g t
590       in
591       List.fold_left map g
592    and sober_ifs g =
593       let map g (_, _, t, v) = sober_term (sober_term g t) v in
594       List.fold_left map g
595    and sober_cifs g =
596       let map g (_, t, v) = sober_term (sober_term g t) v in
597       List.fold_left map g
598    in 
599    sober_term (fun b -> b) t true