]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_proof_checking/cicTypeChecker.ml
Module Logger added.
[helm.git] / helm / ocaml / cic_proof_checking / cicTypeChecker.ml
1 (* Copyright (C) 2000, 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://cs.unibo.it/helm/.
24  *)
25
26 exception Impossible of int;;
27 exception NotWellTyped of string;;
28 exception WrongUriToConstant of string;;
29 exception WrongUriToVariable of string;;
30 exception WrongUriToMutualInductiveDefinitions of string;;
31 exception ListTooShort;;
32 exception NotPositiveOccurrences of string;;
33 exception NotWellFormedTypeOfInductiveConstructor of string;;
34 exception WrongRequiredArgument of string;;
35
36 let fdebug = ref 0;;
37 let debug t env =
38  let rec debug_aux t i =
39   let module C = Cic in
40   let module U = UriManager in
41    CicPp.ppobj (C.Variable ("DEBUG", None, t)) ^ "\n" ^ i
42  in
43   if !fdebug = 0 then
44    raise (NotWellTyped ("\n" ^ List.fold_right debug_aux (t::env) ""))
45    (*print_endline ("\n" ^ List.fold_right debug_aux (t::env) "") ; flush stdout*)
46 ;;
47
48 let rec split l n =
49  match (l,n) with
50     (l,0) -> ([], l)
51   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
52   | (_,_) -> raise ListTooShort
53 ;;
54
55 exception CicEnvironmentError;;
56
57 let rec cooked_type_of_constant uri cookingsno =
58  let module C = Cic in
59  let module R = CicReduction in
60  let module U = UriManager in
61   let cobj =
62    match CicEnvironment.is_type_checked uri cookingsno with
63       CicEnvironment.CheckedObj cobj -> cobj
64     | CicEnvironment.UncheckedObj uobj ->
65        Logger.log (`Start_type_checking uri) ;
66        (* let's typecheck the uncooked obj *)
67        (match uobj with
68            C.Definition (_,te,ty,_) ->
69              let _ = type_of ty in
70               if not (R.are_convertible (type_of te) ty) then
71                raise (NotWellTyped ("Constant " ^ (U.string_of_uri uri)))
72          | C.Axiom (_,ty,_) ->
73            (* only to check that ty is well-typed *)
74            let _ = type_of ty in ()
75          | C.CurrentProof (_,conjs,te,ty) ->
76              let _ = type_of_aux' conjs [] ty in
77               if not (R.are_convertible (type_of_aux' conjs [] te) ty) then
78                raise (NotWellTyped ("CurrentProof" ^ (U.string_of_uri uri)))
79          | _ -> raise (WrongUriToConstant (U.string_of_uri uri))
80        ) ;
81        CicEnvironment.set_type_checking_info uri ;
82        Logger.log (`Type_checking_completed uri) ;
83        match CicEnvironment.is_type_checked uri cookingsno with
84           CicEnvironment.CheckedObj cobj -> cobj
85         | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
86   in
87    match cobj with
88       C.Definition (_,_,ty,_) -> ty
89     | C.Axiom (_,ty,_) -> ty
90     | C.CurrentProof (_,_,_,ty) -> ty
91     | _ -> raise (WrongUriToConstant (U.string_of_uri uri))
92
93 and type_of_variable uri =
94  let module C = Cic in
95  let module R = CicReduction in
96  let module U = UriManager in
97   (* 0 because a variable is never cooked => no partial cooking at one level *)
98   match CicEnvironment.is_type_checked uri 0 with
99      CicEnvironment.CheckedObj (C.Variable (_,_,ty)) -> ty
100    | CicEnvironment.UncheckedObj (C.Variable (_,bo,ty)) ->
101       Logger.log (`Start_type_checking uri) ;
102       (* only to check that ty is well-typed *)
103       let _ = type_of ty in
104        (match bo with
105            None -> ()
106          | Some bo ->
107             if not (R.are_convertible (type_of bo) ty) then
108              raise (NotWellTyped ("Variable " ^ (U.string_of_uri uri)))
109        ) ;
110        CicEnvironment.set_type_checking_info uri ;
111        Logger.log (`Type_checking_completed uri) ;
112        ty
113    |  _ -> raise (WrongUriToVariable (UriManager.string_of_uri uri))
114
115 and does_not_occur n nn te =
116  let module C = Cic in
117    (*CSC: whd sembra essere superflua perche' un caso in cui l'occorrenza *)
118    (*CSC: venga mangiata durante la whd sembra presentare problemi di *)
119    (*CSC: universi                                                    *)
120    match CicReduction.whd te with
121       C.Rel m when m > n && m <= nn -> false
122     | C.Rel _
123     | C.Var _
124     | C.Meta _
125     | C.Sort _
126     | C.Implicit -> true
127     | C.Cast (te,ty) -> does_not_occur n nn te && does_not_occur n nn ty
128     | C.Prod (_,so,dest) ->
129        does_not_occur n nn so && does_not_occur (n + 1) (nn + 1) dest
130     | C.Lambda (_,so,dest) ->
131        does_not_occur n nn so && does_not_occur (n + 1) (nn + 1) dest
132     | C.LetIn (_,so,dest) ->
133        does_not_occur n nn so && does_not_occur (n + 1) (nn + 1) dest
134     | C.Appl l ->
135        List.fold_right (fun x i -> i && does_not_occur n nn x) l true
136     | C.Const _
137     | C.Abst _
138     | C.MutInd _
139     | C.MutConstruct _ -> true
140     | C.MutCase (_,_,_,out,te,pl) ->
141        does_not_occur n nn out && does_not_occur n nn te &&
142         List.fold_right (fun x i -> i && does_not_occur n nn x) pl true
143     | C.Fix (_,fl) ->
144        let len = List.length fl in
145         let n_plus_len = n + len in
146         let nn_plus_len = nn + len in
147          List.fold_right
148           (fun (_,_,ty,bo) i ->
149             i && does_not_occur n_plus_len nn_plus_len ty &&
150             does_not_occur n_plus_len nn_plus_len bo
151           ) fl true
152     | C.CoFix (_,fl) ->
153        let len = List.length fl in
154         let n_plus_len = n + len in
155         let nn_plus_len = nn + len in
156          List.fold_right
157           (fun (_,ty,bo) i ->
158             i && does_not_occur n_plus_len nn_plus_len ty &&
159             does_not_occur n_plus_len nn_plus_len bo
160           ) fl true
161
162 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
163 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
164 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla  *)
165 (*CSC strictly_positive                                                  *)
166 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-)              *)
167 and weakly_positive n nn uri te =
168  let module C = Cic in
169   (*CSC mettere in cicSubstitution *)
170   let rec subst_inductive_type_with_dummy_rel =
171    function
172       C.MutInd (uri',_,0) when UriManager.eq uri' uri ->
173        C.Rel 0 (* dummy rel *)
174     | C.Appl ((C.MutInd (uri',_,0))::tl) when UriManager.eq uri' uri ->
175        C.Rel 0 (* dummy rel *)
176     | C.Cast (te,ty) -> subst_inductive_type_with_dummy_rel te
177     | C.Prod (name,so,ta) ->
178        C.Prod (name, subst_inductive_type_with_dummy_rel so,
179         subst_inductive_type_with_dummy_rel ta)
180     | C.Lambda (name,so,ta) ->
181        C.Lambda (name, subst_inductive_type_with_dummy_rel so,
182         subst_inductive_type_with_dummy_rel ta)
183     | C.Appl tl ->
184        C.Appl (List.map subst_inductive_type_with_dummy_rel tl)
185     | C.MutCase (uri,cookingsno,i,outtype,term,pl) ->
186        C.MutCase (uri,cookingsno,i,
187         subst_inductive_type_with_dummy_rel outtype,
188         subst_inductive_type_with_dummy_rel term,
189         List.map subst_inductive_type_with_dummy_rel pl)
190     | C.Fix (i,fl) ->
191        C.Fix (i,List.map (fun (name,i,ty,bo) -> (name,i,
192         subst_inductive_type_with_dummy_rel ty,
193         subst_inductive_type_with_dummy_rel bo)) fl)
194     | C.CoFix (i,fl) ->
195        C.CoFix (i,List.map (fun (name,ty,bo) -> (name,
196         subst_inductive_type_with_dummy_rel ty,
197         subst_inductive_type_with_dummy_rel bo)) fl)
198     | t -> t
199   in
200   match CicReduction.whd te with
201      C.Appl ((C.MutInd (uri',_,0))::tl) when UriManager.eq uri' uri -> true
202    | C.MutInd (uri',_,0) when UriManager.eq uri' uri -> true
203    | C.Prod (C.Anonimous,source,dest) ->
204       strictly_positive n nn (subst_inductive_type_with_dummy_rel source) &&
205        weakly_positive (n + 1) (nn + 1) uri dest
206    | C.Prod (name,source,dest) when does_not_occur 0 n dest ->
207       (* dummy abstraction, so we behave as in the anonimous case *)
208       strictly_positive n nn (subst_inductive_type_with_dummy_rel source) &&
209        weakly_positive (n + 1) (nn + 1) uri dest
210    | C.Prod (_,source,dest) ->
211       does_not_occur n nn (subst_inductive_type_with_dummy_rel source) &&
212        weakly_positive (n + 1) (nn + 1) uri dest
213    | _ -> raise (NotWellFormedTypeOfInductiveConstructor ("Guess where the error is ;-)"))
214
215 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C                             *)
216 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
217 and instantiate_parameters params c =
218  let module C = Cic in
219   match (c,params) with
220      (c,[]) -> c
221    | (C.Prod (_,_,ta), he::tl) ->
222        instantiate_parameters tl
223         (CicSubstitution.subst he ta)
224    | (C.Cast (te,_), _) -> instantiate_parameters params te
225    | (t,l) -> raise (Impossible 1)
226
227 and strictly_positive n nn te =
228  let module C = Cic in
229  let module U = UriManager in
230   match CicReduction.whd te with
231      C.Rel _ -> true
232    | C.Cast (te,ty) ->
233       (*CSC: bisogna controllare ty????*)
234       strictly_positive n nn te
235    | C.Prod (_,so,ta) ->
236       does_not_occur n nn so &&
237        strictly_positive (n+1) (nn+1) ta
238    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
239       List.fold_right (fun x i -> i && does_not_occur n nn x) tl true
240    | C.Appl ((C.MutInd (uri,_,i))::tl) -> 
241       let (ok,paramsno,cl) =
242        match CicEnvironment.get_obj uri with
243            C.InductiveDefinition (tl,_,paramsno) ->
244             let (_,_,_,cl) = List.nth tl i in
245              (List.length tl = 1, paramsno, cl)
246          | _ -> raise(WrongUriToMutualInductiveDefinitions(U.string_of_uri uri))
247       in
248        let (params,arguments) = split tl paramsno in
249        let lifted_params = List.map (CicSubstitution.lift 1) params in
250        let cl' =
251         List.map (fun (_,te,_) -> instantiate_parameters lifted_params te) cl
252        in
253         ok &&
254          List.fold_right
255           (fun x i -> i && does_not_occur n nn x)
256           arguments true &&
257          (*CSC: MEGAPATCH3 (sara' quella giusta?)*)
258          List.fold_right
259           (fun x i ->
260             i &&
261              weakly_positive (n+1) (nn+1) uri x
262           ) cl' true
263    | t -> does_not_occur n nn t
264
265 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
266 and are_all_occurrences_positive uri indparamsno i n nn te =
267  let module C = Cic in
268   match CicReduction.whd te with
269      C.Appl ((C.Rel m)::tl) when m = i ->
270       (*CSC: riscrivere fermandosi a 0 *)
271       (* let's check if the inductive type is applied at least to *)
272       (* indparamsno parameters                                   *)
273       let last =
274        List.fold_left
275         (fun k x ->
276           if k = 0 then 0
277           else
278            match CicReduction.whd x with
279               C.Rel m when m = n - (indparamsno - k) -> k - 1
280             | _ -> raise (WrongRequiredArgument (UriManager.string_of_uri uri))
281         ) indparamsno tl
282       in
283        if last = 0 then
284         List.fold_right (fun x i -> i && does_not_occur n nn x) tl true
285        else
286         raise (WrongRequiredArgument (UriManager.string_of_uri uri))
287    | C.Rel m when m = i ->
288       if indparamsno = 0 then
289        true
290       else
291        raise (WrongRequiredArgument (UriManager.string_of_uri uri))
292    | C.Prod (C.Anonimous,source,dest) ->
293       strictly_positive n nn source &&
294        are_all_occurrences_positive uri indparamsno (i+1) (n + 1) (nn + 1) dest
295    | C.Prod (name,source,dest) when does_not_occur 0 n dest ->
296       (* dummy abstraction, so we behave as in the anonimous case *)
297       strictly_positive n nn source &&
298        are_all_occurrences_positive uri indparamsno (i+1) (n + 1) (nn + 1) dest
299    | C.Prod (_,source,dest) ->
300       does_not_occur n nn source &&
301        are_all_occurrences_positive uri indparamsno (i+1) (n + 1) (nn + 1) dest
302    | _ -> raise (NotWellFormedTypeOfInductiveConstructor (UriManager.string_of_uri uri))
303
304 (*CSC: cambiare il nome, torna unit! *)
305 and cooked_mutual_inductive_defs uri =
306  let module U = UriManager in
307   function
308      Cic.InductiveDefinition (itl, _, indparamsno) ->
309       (* let's check if the arity of the inductive types are well *)
310       (* formed                                                   *)
311       List.iter (fun (_,_,x,_) -> let _ = type_of x in ()) itl ;
312
313       (* let's check if the types of the inductive constructors  *)
314       (* are well formed.                                        *)
315       (* In order not to use type_of_aux we put the types of the *)
316       (* mutual inductive types at the head of the types of the  *)
317       (* constructors using Prods                                *)
318       (*CSC: piccola??? inefficienza                             *)
319       let len = List.length itl in
320        let _ =
321         List.fold_right
322          (fun (_,_,_,cl) i ->
323            List.iter
324             (fun (name,te,r) -> 
325               let augmented_term =
326                List.fold_right
327                 (fun (name,_,ty,_) i -> Cic.Prod (Cic.Name name, ty, i))
328                 itl te
329               in
330                let _ = type_of augmented_term in
331                 (* let's check also the positivity conditions *)
332                 if not (are_all_occurrences_positive uri indparamsno i 0 len te)
333                 then
334                  raise (NotPositiveOccurrences (U.string_of_uri uri))
335                 else
336                  match !r with
337                     Some _ -> raise (Impossible 2)
338                   | None -> r := Some (recursive_args 0 len te)
339             ) cl ;
340            (i + 1)
341         ) itl 1
342        in
343         ()
344    | _ ->
345      raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
346
347 and cooked_type_of_mutual_inductive_defs uri cookingsno i =
348  let module C = Cic in
349  let module R = CicReduction in
350  let module U = UriManager in
351   let cobj =
352    match CicEnvironment.is_type_checked uri cookingsno with
353       CicEnvironment.CheckedObj cobj -> cobj
354     | CicEnvironment.UncheckedObj uobj ->
355        Logger.log (`Start_type_checking uri) ;
356        cooked_mutual_inductive_defs uri uobj ;
357        CicEnvironment.set_type_checking_info uri ;
358        Logger.log (`Type_checking_completed uri) ;
359        (match CicEnvironment.is_type_checked uri cookingsno with
360           CicEnvironment.CheckedObj cobj -> cobj
361         | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
362        )
363   in
364    match cobj with
365       C.InductiveDefinition (dl,_,_) ->
366        let (_,_,arity,_) = List.nth dl i in
367         arity
368     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
369
370 and cooked_type_of_mutual_inductive_constr uri cookingsno i j =
371  let module C = Cic in
372  let module R = CicReduction in
373  let module U = UriManager in
374   let cobj =
375    match CicEnvironment.is_type_checked uri cookingsno with
376       CicEnvironment.CheckedObj cobj -> cobj
377     | CicEnvironment.UncheckedObj uobj ->
378        Logger.log (`Start_type_checking uri) ;
379        cooked_mutual_inductive_defs uri uobj ;
380        CicEnvironment.set_type_checking_info uri ;
381        Logger.log (`Type_checking_completed uri) ;
382        (match CicEnvironment.is_type_checked uri cookingsno with
383           CicEnvironment.CheckedObj cobj -> cobj
384         | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
385        )
386   in
387    match cobj with
388       C.InductiveDefinition (dl,_,_) ->
389        let (_,_,_,cl) = List.nth dl i in
390         let (_,ty,_) = List.nth cl (j-1) in
391          ty
392     | _ -> raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
393
394 and recursive_args n nn te =
395  let module C = Cic in
396   match CicReduction.whd te with
397      C.Rel _ -> []
398    | C.Var _
399    | C.Meta _
400    | C.Sort _
401    | C.Implicit
402    | C.Cast _ (*CSC ??? *) -> raise (Impossible 3) (* due to type-checking *)
403    | C.Prod (_,so,de) ->
404       (not (does_not_occur n nn so))::(recursive_args (n+1) (nn + 1) de)
405    | C.Lambda _
406    | C.LetIn _ -> raise (Impossible 4) (* due to type-checking *)
407    | C.Appl _ -> []
408    | C.Const _
409    | C.Abst _ -> raise (Impossible 5)
410    | C.MutInd _
411    | C.MutConstruct _
412    | C.MutCase _
413    | C.Fix _
414    | C.CoFix _ -> raise (Impossible 6) (* due to type-checking *)
415
416 and get_new_safes p c rl safes n nn x =
417  let module C = Cic in
418  let module U = UriManager in
419  let module R = CicReduction in
420   match (R.whd c, R.whd p, rl) with
421      (C.Prod (_,_,ta1), C.Lambda (_,_,ta2), b::tl) ->
422        (* we are sure that the two sources are convertible because we *)
423        (* have just checked this. So let's go along ...               *)
424        let safes' =
425         List.map (fun x -> x + 1) safes
426        in
427         let safes'' =
428          if b then 1::safes' else safes'
429         in
430          get_new_safes ta2 ta1 tl safes'' (n+1) (nn+1) (x+1)
431    | (C.Prod _, (C.MutConstruct _ as e), _)
432    | (C.Prod _, (C.Rel _ as e), _)
433    | (C.MutInd _, e, [])
434    | (C.Appl _, e, []) -> (e,safes,n,nn,x)
435    | (_,_,_) ->
436       (* CSC: If the next exception is raised, it just means that   *)
437       (* CSC: the proof-assistant allows to use very strange things *)
438       (* CSC: as a branch of a case whose type is a Prod. In        *)
439       (* CSC: particular, this means that a new (C.Prod, x,_) case  *)
440       (* CSC: must be considered in this match. (e.g. x = MutCase)  *)
441       raise (Impossible 7)
442
443 and split_prods n te =
444  let module C = Cic in
445  let module R = CicReduction in
446   match (n, R.whd te) with
447      (0, _) -> [],te
448    | (n, C.Prod (_,so,ta)) when n > 0 ->
449       let (l1,l2) = split_prods (n - 1) ta in
450        (so::l1,l2)
451    | (_, _) -> raise (Impossible 8)
452
453 and eat_lambdas n te =
454  let module C = Cic in
455  let module R = CicReduction in
456   match (n, R.whd te) with
457      (0, _) -> (te, 0)
458    | (n, C.Lambda (_,_,ta)) when n > 0 ->
459       let (te, k) = eat_lambdas (n - 1) ta in
460        (te, k + 1)
461    | (_, _) -> raise (Impossible 9)
462
463 (*CSC: Tutto quello che segue e' l'intuzione di luca ;-) *)
464 and check_is_really_smaller_arg n nn kl x safes te =
465  (*CSC: forse la whd si puo' fare solo quando serve veramente. *)
466  (*CSC: cfr guarded_by_destructors                             *)
467  let module C = Cic in
468  let module U = UriManager in
469  match CicReduction.whd te with
470      C.Rel m when List.mem m safes -> true
471    | C.Rel _ -> false
472    | C.Var _
473    | C.Meta _
474    | C.Sort _
475    | C.Implicit 
476    | C.Cast _
477 (*   | C.Cast (te,ty) ->
478       check_is_really_smaller_arg n nn kl x safes te &&
479        check_is_really_smaller_arg n nn kl x safes ty*)
480 (*   | C.Prod (_,so,ta) ->
481       check_is_really_smaller_arg n nn kl x safes so &&
482        check_is_really_smaller_arg (n+1) (nn+1) kl (x+1)
483         (List.map (fun x -> x + 1) safes) ta*)
484    | C.Prod _ -> raise (Impossible 10)
485    | C.Lambda (_,so,ta) ->
486       check_is_really_smaller_arg n nn kl x safes so &&
487        check_is_really_smaller_arg (n+1) (nn+1) kl (x+1)
488         (List.map (fun x -> x + 1) safes) ta
489    | C.LetIn (_,so,ta) ->
490       check_is_really_smaller_arg n nn kl x safes so &&
491        check_is_really_smaller_arg (n+1) (nn+1) kl (x+1)
492         (List.map (fun x -> x + 1) safes) ta
493    | C.Appl (he::_) ->
494       (*CSC: sulla coda ci vogliono dei controlli? secondo noi no, ma *)
495       (*CSC: solo perche' non abbiamo trovato controesempi            *)
496       check_is_really_smaller_arg n nn kl x safes he
497    | C.Appl [] -> raise (Impossible 11)
498    | C.Const _
499    | C.Abst _
500    | C.MutInd _ -> raise (Impossible 12)
501    | C.MutConstruct _ -> false
502    | C.MutCase (uri,_,i,outtype,term,pl) ->
503       (match term with
504           C.Rel m when List.mem m safes || m = x ->
505            let (isinductive,paramsno,cl) =
506             match CicEnvironment.get_obj uri with
507                C.InductiveDefinition (tl,_,paramsno) ->
508                 let (_,isinductive,_,cl) = List.nth tl i in
509                  let cl' =
510                   List.map (fun (id,ty,r) -> (id, snd (split_prods paramsno ty), r)) cl
511                  in
512                   (isinductive,paramsno,cl')
513              | _ ->
514                raise (WrongUriToMutualInductiveDefinitions(U.string_of_uri uri))
515            in
516             if not isinductive then
517               List.fold_right
518                (fun p i -> i && check_is_really_smaller_arg n nn kl x safes p)
519                pl true
520             else
521               List.fold_right
522                (fun (p,(_,c,rl)) i ->
523                  let rl' =
524                   match !rl with
525                      Some rl' ->
526                       let (_,rl'') = split rl' paramsno in
527                        rl''
528                    | None -> raise (Impossible 13)
529                  in
530                   let (e,safes',n',nn',x') =
531                    get_new_safes p c rl' safes n nn x
532                   in
533                    i &&
534                    check_is_really_smaller_arg n' nn' kl x' safes' e
535                ) (List.combine pl cl) true
536         | C.Appl ((C.Rel m)::tl) when List.mem m safes || m = x ->
537            let (isinductive,paramsno,cl) =
538             match CicEnvironment.get_obj uri with
539                C.InductiveDefinition (tl,_,paramsno) ->
540                 let (_,isinductive,_,cl) = List.nth tl i in
541                  let cl' =
542                   List.map (fun (id,ty,r) -> (id, snd (split_prods paramsno ty), r)) cl
543                  in
544                   (isinductive,paramsno,cl')
545              | _ ->
546                raise (WrongUriToMutualInductiveDefinitions(U.string_of_uri uri))
547            in
548             if not isinductive then
549               List.fold_right
550                (fun p i -> i && check_is_really_smaller_arg n nn kl x safes p)
551                pl true
552             else
553               (*CSC: supponiamo come prima che nessun controllo sia necessario*)
554               (*CSC: sugli argomenti di una applicazione                      *)
555               List.fold_right
556                (fun (p,(_,c,rl)) i ->
557                  let rl' =
558                   match !rl with
559                      Some rl' ->
560                       let (_,rl'') = split rl' paramsno in
561                        rl''
562                    | None -> raise (Impossible 14)
563                  in
564                   let (e, safes',n',nn',x') =
565                    get_new_safes p c rl' safes n nn x
566                   in
567                    i &&
568                    check_is_really_smaller_arg n' nn' kl x' safes' e
569                ) (List.combine pl cl) true
570         | _ ->
571           List.fold_right
572            (fun p i -> i && check_is_really_smaller_arg n nn kl x safes p)
573            pl true
574       )
575    | C.Fix (_, fl) ->
576       let len = List.length fl in
577        let n_plus_len = n + len
578        and nn_plus_len = nn + len
579        and x_plus_len = x + len
580        and safes' = List.map (fun x -> x + len) safes in
581         List.fold_right
582          (fun (_,_,ty,bo) i ->
583            i &&
584             check_is_really_smaller_arg n_plus_len nn_plus_len kl x_plus_len
585              safes' bo
586          ) fl true
587    | C.CoFix (_, fl) ->
588       let len = List.length fl in
589        let n_plus_len = n + len
590        and nn_plus_len = nn + len
591        and x_plus_len = x + len
592        and safes' = List.map (fun x -> x + len) safes in
593         List.fold_right
594          (fun (_,ty,bo) i ->
595            i &&
596             check_is_really_smaller_arg n_plus_len nn_plus_len kl x_plus_len
597              safes' bo
598          ) fl true
599
600 and guarded_by_destructors n nn kl x safes =
601  let module C = Cic in
602  let module U = UriManager in
603   function
604      C.Rel m when m > n && m <= nn -> false
605    | C.Rel _
606    | C.Var _
607    | C.Meta _
608    | C.Sort _
609    | C.Implicit -> true
610    | C.Cast (te,ty) ->
611       guarded_by_destructors n nn kl x safes te &&
612        guarded_by_destructors n nn kl x safes ty
613    | C.Prod (_,so,ta) ->
614       guarded_by_destructors n nn kl x safes so &&
615        guarded_by_destructors (n+1) (nn+1) kl (x+1)
616         (List.map (fun x -> x + 1) safes) ta
617    | C.Lambda (_,so,ta) ->
618       guarded_by_destructors n nn kl x safes so &&
619        guarded_by_destructors (n+1) (nn+1) kl (x+1)
620         (List.map (fun x -> x + 1) safes) ta
621    | C.LetIn (_,so,ta) ->
622       guarded_by_destructors n nn kl x safes so &&
623        guarded_by_destructors (n+1) (nn+1) kl (x+1)
624         (List.map (fun x -> x + 1) safes) ta
625    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
626       let k = List.nth kl (m - n - 1) in
627        if not (List.length tl > k) then false
628        else
629         List.fold_right
630          (fun param i ->
631            i && guarded_by_destructors n nn kl x safes param
632          ) tl true &&
633          check_is_really_smaller_arg n nn kl x safes (List.nth tl k)
634    | C.Appl tl ->
635       List.fold_right (fun t i -> i && guarded_by_destructors n nn kl x safes t)
636        tl true
637    | C.Const _
638    | C.Abst _
639    | C.MutInd _
640    | C.MutConstruct _ -> true
641    | C.MutCase (uri,_,i,outtype,term,pl) ->
642       (match term with
643           C.Rel m when List.mem m safes || m = x ->
644            let (isinductive,paramsno,cl) =
645             match CicEnvironment.get_obj uri with
646                C.InductiveDefinition (tl,_,paramsno) ->
647                 let (_,isinductive,_,cl) = List.nth tl i in
648                  let cl' =
649                   List.map (fun (id,ty,r) -> (id, snd (split_prods paramsno ty), r)) cl
650                  in
651                   (isinductive,paramsno,cl')
652              | _ ->
653                raise (WrongUriToMutualInductiveDefinitions(U.string_of_uri uri))
654            in
655             if not isinductive then
656              guarded_by_destructors n nn kl x safes outtype &&
657               guarded_by_destructors n nn kl x safes term &&
658               (*CSC: manca ??? il controllo sul tipo di term? *)
659               List.fold_right
660                (fun p i -> i && guarded_by_destructors n nn kl x safes p)
661                pl true
662             else
663              guarded_by_destructors n nn kl x safes outtype &&
664               (*CSC: manca ??? il controllo sul tipo di term? *)
665               List.fold_right
666                (fun (p,(_,c,rl)) i ->
667                  let rl' =
668                   match !rl with
669                      Some rl' ->
670                       let (_,rl'') = split rl' paramsno in
671                        rl''
672                    | None -> raise (Impossible 15)
673                  in
674                   let (e,safes',n',nn',x') =
675                    get_new_safes p c rl' safes n nn x
676                   in
677                    i &&
678                    guarded_by_destructors n' nn' kl x' safes' e
679                ) (List.combine pl cl) true
680         | C.Appl ((C.Rel m)::tl) when List.mem m safes || m = x ->
681            let (isinductive,paramsno,cl) =
682             match CicEnvironment.get_obj uri with
683                C.InductiveDefinition (tl,_,paramsno) ->
684                 let (_,isinductive,_,cl) = List.nth tl i in
685                  let cl' =
686                   List.map (fun (id,ty,r) -> (id, snd (split_prods paramsno ty), r)) cl
687                  in
688                   (isinductive,paramsno,cl')
689              | _ ->
690                raise (WrongUriToMutualInductiveDefinitions(U.string_of_uri uri))
691            in
692             if not isinductive then
693              guarded_by_destructors n nn kl x safes outtype &&
694               guarded_by_destructors n nn kl x safes term &&
695               (*CSC: manca ??? il controllo sul tipo di term? *)
696               List.fold_right
697                (fun p i -> i && guarded_by_destructors n nn kl x safes p)
698                pl true
699             else
700              guarded_by_destructors n nn kl x safes outtype &&
701               (*CSC: manca ??? il controllo sul tipo di term? *)
702               List.fold_right
703                (fun t i -> i && guarded_by_destructors n nn kl x safes t)
704                tl true &&
705               List.fold_right
706                (fun (p,(_,c,rl)) i ->
707                  let rl' =
708                   match !rl with
709                      Some rl' ->
710                       let (_,rl'') = split rl' paramsno in
711                        rl''
712                    | None -> raise (Impossible 16)
713                  in
714                   let (e, safes',n',nn',x') =
715                    get_new_safes p c rl' safes n nn x
716                   in
717                    i &&
718                    guarded_by_destructors n' nn' kl x' safes' e
719                ) (List.combine pl cl) true
720         | _ ->
721           guarded_by_destructors n nn kl x safes outtype &&
722            guarded_by_destructors n nn kl x safes term &&
723            (*CSC: manca ??? il controllo sul tipo di term? *)
724            List.fold_right
725             (fun p i -> i && guarded_by_destructors n nn kl x safes p)
726             pl true
727       )
728    | C.Fix (_, fl) ->
729       let len = List.length fl in
730        let n_plus_len = n + len
731        and nn_plus_len = nn + len
732        and x_plus_len = x + len
733        and safes' = List.map (fun x -> x + len) safes in
734         List.fold_right
735          (fun (_,_,ty,bo) i ->
736            i && guarded_by_destructors n_plus_len nn_plus_len kl x_plus_len
737             safes' ty &&
738             guarded_by_destructors n_plus_len nn_plus_len kl x_plus_len
739              safes' bo
740          ) fl true
741    | C.CoFix (_, fl) ->
742       let len = List.length fl in
743        let n_plus_len = n + len
744        and nn_plus_len = nn + len
745        and x_plus_len = x + len
746        and safes' = List.map (fun x -> x + len) safes in
747         List.fold_right
748          (fun (_,ty,bo) i ->
749            i && guarded_by_destructors n_plus_len nn_plus_len kl x_plus_len
750             safes' ty &&
751             guarded_by_destructors n_plus_len nn_plus_len kl x_plus_len safes'
752              bo
753          ) fl true
754
755 (* the boolean h means already protected *)
756 (* args is the list of arguments the type of the constructor that may be *)
757 (* found in head position must be applied to.                            *)
758 (*CSC: coInductiveTypeURI non cambia mai di ricorsione in ricorsione *)
759 and guarded_by_constructors n nn h te args coInductiveTypeURI =
760  let module C = Cic in
761   (*CSC: There is a lot of code replication between the cases X and    *)
762   (*CSC: (C.Appl X tl). Maybe it will be better to define a function   *)
763   (*CSC: that maps X into (C.Appl X []) when X is not already a C.Appl *)
764   match CicReduction.whd te with
765      C.Rel m when m > n && m <= nn -> h
766    | C.Rel _
767    | C.Var _  -> true
768    | C.Meta _
769    | C.Sort _
770    | C.Implicit
771    | C.Cast _
772    | C.Prod _
773    | C.LetIn _ ->
774       raise (Impossible 17) (* the term has just been type-checked *)
775    | C.Lambda (_,so,de) ->
776       does_not_occur n nn so &&
777        guarded_by_constructors (n + 1) (nn + 1) h de args coInductiveTypeURI
778    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
779       h &&
780        List.fold_right (fun x i -> i && does_not_occur n nn x) tl true
781    | C.Appl ((C.MutConstruct (uri,cookingsno,i,j))::tl) ->
782       let consty =
783        match CicEnvironment.get_cooked_obj uri cookingsno with
784           C.InductiveDefinition (itl,_,_) ->
785            let (_,_,_,cl) = List.nth itl i in
786             let (_,cons,_) = List.nth cl (j - 1) in cons
787         | _ ->
788          raise (WrongUriToMutualInductiveDefinitions
789           (UriManager.string_of_uri uri))
790       in
791        let rec analyse_branch ty te =
792         match CicReduction.whd ty with
793            C.Meta _ -> raise (Impossible 34)
794          | C.Rel _
795          | C.Var _
796          | C.Sort _ ->
797             does_not_occur n nn te
798          | C.Implicit
799          | C.Cast _ -> raise (Impossible 24) (* due to type-checking *)
800          | C.Prod (_,_,de) ->
801             analyse_branch de te
802          | C.Lambda _
803          | C.LetIn _ -> raise (Impossible 25) (* due to type-checking *)
804          | C.Appl ((C.MutInd (uri,_,_))::tl) as ty
805             when uri == coInductiveTypeURI -> 
806              guarded_by_constructors n nn true te [] coInductiveTypeURI
807          | C.Appl ((C.MutInd (uri,_,_))::tl) as ty -> 
808             guarded_by_constructors n nn true te tl coInductiveTypeURI
809          | C.Appl _ ->
810             does_not_occur n nn te
811          | C.Const _
812          | C.Abst _ -> raise (Impossible 26)
813          | C.MutInd (uri,_,_) when uri == coInductiveTypeURI ->
814             guarded_by_constructors n nn true te [] coInductiveTypeURI
815          | C.MutInd _ ->
816             does_not_occur n nn te
817          | C.MutConstruct _ -> raise (Impossible 27)
818          (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
819          (*CSC: in head position.                                       *)
820          | C.MutCase _
821          | C.Fix _
822          | C.CoFix _ -> raise (Impossible 28) (* due to type-checking *)
823        in
824        let rec analyse_instantiated_type ty l =
825         match CicReduction.whd ty with
826            C.Rel _
827          | C.Var _
828          | C.Meta _
829          | C.Sort _
830          | C.Implicit
831          | C.Cast _ -> raise (Impossible 29) (* due to type-checking *)
832          | C.Prod (_,so,de) ->
833             begin
834              match l with
835                 [] -> true
836               | he::tl ->
837                  analyse_branch so he &&
838                   analyse_instantiated_type de tl
839             end
840          | C.Lambda _
841          | C.LetIn _ -> raise (Impossible 30) (* due to type-checking *)
842          | C.Appl _ -> 
843             List.fold_left (fun i x -> i && does_not_occur n nn x) true l
844          | C.Const _
845          | C.Abst _ -> raise (Impossible 31)
846          | C.MutInd _ ->
847             List.fold_left (fun i x -> i && does_not_occur n nn x) true l
848          | C.MutConstruct _ -> raise (Impossible 32)
849          (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
850          (*CSC: in head position.                                       *)
851          | C.MutCase _
852          | C.Fix _
853          | C.CoFix _ -> raise (Impossible 33) (* due to type-checking *)
854        in
855         let rec instantiate_type args consty =
856          function
857             [] -> true
858           | tlhe::tltl as l ->
859              let consty' = CicReduction.whd consty in
860               match args with 
861                  he::tl ->
862                   begin
863                    match consty' with
864                       C.Prod (_,_,de) ->
865                        let instantiated_de = CicSubstitution.subst he de in
866                         (*CSC: siamo sicuri che non sia troppo forte? *)
867                         does_not_occur n nn tlhe &
868                          instantiate_type tl instantiated_de tltl
869                     | _ ->
870                       (*CSC:We do not consider backbones with a MutCase, a    *)
871                       (*CSC:FixPoint, a CoFixPoint and so on in head position.*)
872                       raise (Impossible 23)
873                   end
874                | [] -> analyse_instantiated_type consty' l
875                   (* These are all the other cases *)
876        in
877         instantiate_type args consty tl
878    | C.Appl ((C.CoFix (_,fl))::tl) ->
879       List.fold_left (fun i x -> i && does_not_occur n nn x) true tl &&
880        let len = List.length fl in
881         let n_plus_len = n + len
882         and nn_plus_len = nn + len in
883          List.fold_right
884           (fun (_,ty,bo) i ->
885             i && does_not_occur n_plus_len nn_plus_len ty &&
886              guarded_by_constructors n_plus_len nn_plus_len h bo args
887               coInductiveTypeURI
888           ) fl true
889    | C.Appl ((C.MutCase (_,_,_,out,te,pl))::tl) ->
890        List.fold_left (fun i x -> i && does_not_occur n nn x) true tl &&
891         does_not_occur n nn out &&
892          does_not_occur n nn te &&
893           List.fold_right
894            (fun x i ->
895              i &&
896              guarded_by_constructors n nn h x args coInductiveTypeURI
897            ) pl true
898    | C.Appl l ->
899       List.fold_right (fun x i -> i && does_not_occur n nn x) l true
900    | C.Const _ -> true
901    | C.Abst _
902    | C.MutInd _ -> assert false
903    | C.MutConstruct _ -> true
904    | C.MutCase (_,_,_,out,te,pl) ->
905        does_not_occur n nn out &&
906         does_not_occur n nn te &&
907          List.fold_right
908           (fun x i ->
909             i &&
910              guarded_by_constructors n nn h x args coInductiveTypeURI
911           ) pl true
912    | C.Fix (_,fl) ->
913       let len = List.length fl in
914        let n_plus_len = n + len
915        and nn_plus_len = nn + len in
916         List.fold_right
917          (fun (_,_,ty,bo) i ->
918            i && does_not_occur n_plus_len nn_plus_len ty &&
919             does_not_occur n_plus_len nn_plus_len bo
920          ) fl true
921    | C.CoFix (_,fl) ->
922       let len = List.length fl in
923        let n_plus_len = n + len
924        and nn_plus_len = nn + len in
925         List.fold_right
926          (fun (_,ty,bo) i ->
927            i && does_not_occur n_plus_len nn_plus_len ty &&
928             guarded_by_constructors n_plus_len nn_plus_len h bo args
929              coInductiveTypeURI
930          ) fl true
931
932 and check_allowed_sort_elimination uri i need_dummy ind arity1 arity2 =
933  let module C = Cic in
934  let module U = UriManager in
935   match (CicReduction.whd arity1, CicReduction.whd arity2) with
936      (C.Prod (_,so1,de1), C.Prod (_,so2,de2))
937       when CicReduction.are_convertible so1 so2 ->
938        check_allowed_sort_elimination uri i need_dummy
939         (C.Appl [CicSubstitution.lift 1 ind ; C.Rel 1]) de1 de2
940    | (C.Sort C.Prop, C.Sort C.Prop) when need_dummy -> true
941    | (C.Sort C.Prop, C.Sort C.Set) when need_dummy ->
942        (match CicEnvironment.get_obj uri with
943            C.InductiveDefinition (itl,_,_) ->
944             let (_,_,_,cl) = List.nth itl i in
945              (* is a singleton definition? *)
946              List.length cl = 1
947          | _ ->
948            raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
949        )
950    | (C.Sort C.Set, C.Sort C.Prop) when need_dummy -> true
951    | (C.Sort C.Set, C.Sort C.Set) when need_dummy -> true
952    | (C.Sort C.Set, C.Sort C.Type) when need_dummy ->
953        (match CicEnvironment.get_obj uri with
954            C.InductiveDefinition (itl,_,paramsno) ->
955             let (_,_,_,cl) = List.nth itl i in
956              List.fold_right (fun (_,x,_) i -> i && is_small paramsno x) cl true
957          | _ ->
958            raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
959        )
960    | (C.Sort C.Type, C.Sort _) when need_dummy -> true
961    | (C.Sort C.Prop, C.Prod (_,so,ta)) when not need_dummy ->
962        let res = CicReduction.are_convertible so ind
963        in
964         res &&
965         (match CicReduction.whd ta with
966             C.Sort C.Prop -> true
967           | C.Sort C.Set ->
968              (match CicEnvironment.get_obj uri with
969                  C.InductiveDefinition (itl,_,_) ->
970                   let (_,_,_,cl) = List.nth itl i in
971                    (* is a singleton definition? *)
972                    List.length cl = 1
973                | _ ->
974                  raise (WrongUriToMutualInductiveDefinitions
975                   (U.string_of_uri uri))
976              )
977           | _ -> false
978         )
979    | (C.Sort C.Set, C.Prod (_,so,ta)) when not need_dummy ->
980        let res = CicReduction.are_convertible so ind
981        in
982         res &&
983         (match CicReduction.whd ta with
984             C.Sort C.Prop
985           | C.Sort C.Set  -> true
986           | C.Sort C.Type ->
987              (match CicEnvironment.get_obj uri with
988                  C.InductiveDefinition (itl,_,paramsno) ->
989                   let (_,_,_,cl) = List.nth itl i in
990                    List.fold_right
991                     (fun (_,x,_) i -> i && is_small paramsno x) cl true
992                | _ ->
993                  raise (WrongUriToMutualInductiveDefinitions
994                   (U.string_of_uri uri))
995              )
996           | _ -> raise (Impossible 19)
997         )
998    | (C.Sort C.Type, C.Prod (_,so,_)) when not need_dummy ->
999        CicReduction.are_convertible so ind
1000    | (_,_) -> false
1001   
1002 and type_of_branch argsno need_dummy outtype term constype =
1003  let module C = Cic in
1004  let module R = CicReduction in
1005   match R.whd constype with
1006      C.MutInd (_,_,_) ->
1007       if need_dummy then
1008        outtype
1009       else
1010        C.Appl [outtype ; term]
1011    | C.Appl (C.MutInd (_,_,_)::tl) ->
1012       let (_,arguments) = split tl argsno
1013       in
1014        if need_dummy && arguments = [] then
1015         outtype
1016        else
1017         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
1018    | C.Prod (name,so,de) ->
1019       C.Prod (C.Name "pippo",so,type_of_branch argsno need_dummy 
1020        (CicSubstitution.lift 1 outtype)
1021        (C.Appl [CicSubstitution.lift 1 term ; C.Rel 1]) de)
1022   | _ -> raise (Impossible 20)
1023        
1024  
1025 (* type_of_aux' is just another name (with a different scope) for type_of_aux *)
1026 and type_of_aux' metasenv env t =
1027  let rec type_of_aux env =
1028   let module C = Cic in
1029   let module R = CicReduction in
1030   let module S = CicSubstitution in
1031   let module U = UriManager in
1032    function
1033       C.Rel n ->
1034        let t =
1035         try
1036          List.nth env (n - 1)
1037         with
1038          _ -> raise (NotWellTyped "Not a close term")
1039        in
1040         S.lift n t
1041     | C.Var uri ->
1042       incr fdebug ;
1043       let ty = type_of_variable uri in
1044        decr fdebug ;
1045        ty
1046     | C.Meta n -> List.assoc n metasenv
1047     | C.Sort s -> C.Sort C.Type (*CSC manca la gestione degli universi!!! *)
1048     | C.Implicit -> raise (Impossible 21)
1049     | C.Cast (te,ty) ->
1050        let _ = type_of ty in
1051         if R.are_convertible (type_of_aux env te) ty then ty
1052         else raise (NotWellTyped "Cast")
1053     | C.Prod (_,s,t) ->
1054        let sort1 = type_of_aux env s
1055        and sort2 = type_of_aux (s::env) t in
1056         sort_of_prod (sort1,sort2)
1057    | C.Lambda (n,s,t) ->
1058        let sort1 = type_of_aux env s
1059        and type2 = type_of_aux (s::env) t in
1060         let sort2 = type_of_aux (s::env) type2 in
1061          (* only to check if the product is well-typed *)
1062          let _ = sort_of_prod (sort1,sort2) in
1063           C.Prod (n,s,type2)
1064    | C.LetIn (n,s,t) ->
1065        let t' = CicSubstitution.subst s t in
1066         type_of_aux env t'
1067    | C.Appl (he::tl) when List.length tl > 0 ->
1068       let hetype = type_of_aux env he
1069       and tlbody_and_type = List.map (fun x -> (x, type_of_aux env x)) tl in
1070        eat_prods hetype tlbody_and_type
1071    | C.Appl _ -> raise (NotWellTyped "Appl: no arguments")
1072    | C.Const (uri,cookingsno) ->
1073       incr fdebug ;
1074       let cty = cooked_type_of_constant uri cookingsno in
1075        decr fdebug ;
1076        cty
1077    | C.Abst _ -> raise (Impossible 22)
1078    | C.MutInd (uri,cookingsno,i) ->
1079       incr fdebug ;
1080       let cty = cooked_type_of_mutual_inductive_defs uri cookingsno i in
1081        decr fdebug ;
1082        cty
1083    | C.MutConstruct (uri,cookingsno,i,j) ->
1084       let cty = cooked_type_of_mutual_inductive_constr uri cookingsno i j
1085       in
1086        cty
1087    | C.MutCase (uri,cookingsno,i,outtype,term,pl) ->
1088       let outsort = type_of_aux env outtype in
1089       let (need_dummy, k) =
1090        let rec guess_args t =
1091         match CicReduction.whd t with
1092            C.Sort _ -> (true, 0)
1093          | C.Prod (_, s, t) ->
1094             let (b, n) = guess_args t in
1095              if n = 0 then
1096               (* last prod before sort *)
1097               match CicReduction.whd s with
1098                  (*CSC vedi nota delirante su cookingsno in cicReduction.ml *)
1099                  C.MutInd (uri',_,i') when U.eq uri' uri && i' = i -> (false, 1)
1100                | C.Appl ((C.MutInd (uri',_,i')) :: _)
1101                   when U.eq uri' uri && i' = i -> (false, 1)
1102                | _ -> (true, 1)
1103              else
1104               (b, n + 1)
1105          | _ -> raise (NotWellTyped "MutCase: outtype ill-formed")
1106        in
1107         (*CSC whd non serve dopo type_of_aux ? *)
1108         let (b, k) = guess_args outsort in
1109          if not b then (b, k - 1) else (b, k)
1110       in
1111       let (parameters, arguments) =
1112         match R.whd (type_of_aux env term) with
1113            (*CSC manca il caso dei CAST *)
1114            C.MutInd (uri',_,i') ->
1115             (*CSC vedi nota delirante sui cookingsno in cicReduction.ml*)
1116             if U.eq uri uri' && i = i' then ([],[])
1117             else raise (NotWellTyped ("MutCase: the term is of type " ^
1118              (U.string_of_uri uri') ^ "," ^ string_of_int i' ^
1119              " instead of type " ^ (U.string_of_uri uri') ^ "," ^
1120              string_of_int i))
1121          | C.Appl (C.MutInd (uri',_,i') :: tl) ->
1122             if U.eq uri uri' && i = i' then split tl (List.length tl - k)
1123             else raise (NotWellTyped ("MutCase: the term is of type " ^
1124              (U.string_of_uri uri') ^ "," ^ string_of_int i' ^
1125              " instead of type " ^ (U.string_of_uri uri) ^ "," ^
1126              string_of_int i))
1127          | _ -> raise (NotWellTyped "MutCase: the term is not an inductive one")
1128       in
1129        (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
1130        let sort_of_ind_type =
1131         if parameters = [] then
1132          C.MutInd (uri,cookingsno,i)
1133         else
1134          C.Appl ((C.MutInd (uri,cookingsno,i))::parameters)
1135        in
1136         if not (check_allowed_sort_elimination uri i need_dummy
1137          sort_of_ind_type (type_of_aux env sort_of_ind_type) outsort)
1138         then
1139          raise (NotWellTyped "MutCase: not allowed sort elimination") ;
1140
1141         (* let's check if the type of branches are right *)
1142         let (cl,parsno) =
1143          match CicEnvironment.get_cooked_obj uri cookingsno with
1144             C.InductiveDefinition (tl,_,parsno) ->
1145              let (_,_,_,cl) = List.nth tl i in (cl,parsno)
1146           | _ ->
1147             raise (WrongUriToMutualInductiveDefinitions (U.string_of_uri uri))
1148         in
1149          let (_,branches_ok) =
1150           List.fold_left
1151            (fun (j,b) (p,(_,c,_)) ->
1152              let cons =
1153               if parameters = [] then
1154                (C.MutConstruct (uri,cookingsno,i,j))
1155               else
1156                (C.Appl (C.MutConstruct (uri,cookingsno,i,j)::parameters))
1157              in
1158               (j + 1, b &&
1159                R.are_convertible (type_of_aux env p)
1160                 (type_of_branch parsno need_dummy outtype cons
1161                   (type_of_aux env cons))
1162               )
1163            ) (1,true) (List.combine pl cl)
1164          in
1165           if not branches_ok then
1166            raise (NotWellTyped "MutCase: wrong type of a branch") ;
1167
1168           if not need_dummy then
1169            C.Appl ((outtype::arguments)@[term])
1170           else if arguments = [] then
1171            outtype
1172           else
1173            C.Appl (outtype::arguments)
1174    | C.Fix (i,fl) ->
1175       let types_times_kl =
1176        List.rev
1177         (List.map (fun (_,k,ty,_) -> let _ = type_of_aux env ty in (ty,k)) fl)
1178       in
1179       let (types,kl) = List.split types_times_kl in
1180        let len = List.length types in
1181         List.iter
1182          (fun (name,x,ty,bo) ->
1183            if (R.are_convertible (type_of_aux (types @ env) bo)
1184             (CicSubstitution.lift len ty))
1185            then
1186             begin
1187              let (m, eaten) = eat_lambdas (x + 1) bo in
1188               (*let's control the guarded by destructors conditions D{f,k,x,M}*)
1189               if not (guarded_by_destructors eaten (len + eaten) kl 1 [] m) then
1190                raise (NotWellTyped "Fix: not guarded by destructors")
1191             end
1192            else
1193             raise (NotWellTyped "Fix: ill-typed bodies")
1194          ) fl ;
1195       
1196         (*CSC: controlli mancanti solo su D{f,k,x,M} *)
1197         let (_,_,ty,_) = List.nth fl i in
1198         ty
1199    | C.CoFix (i,fl) ->
1200       let types =
1201        List.rev (List.map (fun (_,ty,_) -> let _ = type_of_aux env ty in ty) fl)
1202       in
1203        let len = List.length types in
1204         List.iter
1205          (fun (_,ty,bo) ->
1206            if (R.are_convertible (type_of_aux (types @ env) bo)
1207             (CicSubstitution.lift len ty))
1208            then
1209             begin
1210              (* let's control that the returned type is coinductive *)
1211              match returns_a_coinductive ty with
1212                 None ->
1213                  raise(NotWellTyped "CoFix: does not return a coinductive type")
1214               | Some uri ->
1215                  (*let's control the guarded by constructors conditions C{f,M}*)
1216                  if not (guarded_by_constructors 0 len false bo [] uri) then
1217                   raise (NotWellTyped "CoFix: not guarded by constructors")
1218             end
1219            else
1220             raise (NotWellTyped "CoFix: ill-typed bodies")
1221          ) fl ;
1222       
1223         let (_,ty,_) = List.nth fl i in
1224          ty
1225
1226  and sort_of_prod (t1, t2) =
1227   let module C = Cic in
1228    let t1' = CicReduction.whd t1 in
1229    let t2' = CicReduction.whd t2 in
1230    match (t1', t2') with
1231       (C.Sort s1, C.Sort s2)
1232         when (s2 = C.Prop or s2 = C.Set) -> (* different from Coq manual!!! *)
1233          C.Sort s2
1234     | (C.Sort s1, C.Sort s2) -> C.Sort C.Type (*CSC manca la gestione degli universi!!! *)
1235     | (_,_) ->
1236       raise
1237        (NotWellTyped
1238         ("Prod: sort1= " ^ CicPp.ppterm t1' ^ " ; sort2= " ^ CicPp.ppterm t2'))
1239
1240  and eat_prods hetype =
1241   (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
1242   (*CSC: cucinati                                                         *)
1243   function
1244      [] -> hetype
1245    | (hete, hety)::tl ->
1246     (match (CicReduction.whd hetype) with
1247         Cic.Prod (n,s,t) ->
1248          if CicReduction.are_convertible s hety then
1249           (CicReduction.fdebug := -1 ;
1250            eat_prods (CicSubstitution.subst hete t) tl
1251           )
1252          else
1253           begin
1254            CicReduction.fdebug := 0 ;
1255            ignore (CicReduction.are_convertible s hety) ;
1256            fdebug := 0 ;
1257            debug s [hety] ;
1258            raise (NotWellTyped "Appl: wrong parameter-type")
1259           end
1260       | _ -> raise (NotWellTyped "Appl: wrong Prod-type")
1261     )
1262
1263  and returns_a_coinductive ty =
1264   let module C = Cic in
1265    match CicReduction.whd ty with
1266       C.MutInd (uri,cookingsno,i) ->
1267        (*CSC: definire una funzioncina per questo codice sempre replicato *)
1268        (match CicEnvironment.get_cooked_obj uri cookingsno with
1269            C.InductiveDefinition (itl,_,_) ->
1270             let (_,is_inductive,_,cl) = List.nth itl i in
1271              if is_inductive then None else (Some uri)
1272          | _ ->
1273            raise (WrongUriToMutualInductiveDefinitions
1274             (UriManager.string_of_uri uri))
1275         )
1276     | C.Appl ((C.MutInd (uri,_,i))::_) ->
1277        (match CicEnvironment.get_obj uri with
1278            C.InductiveDefinition (itl,_,_) ->
1279             let (_,is_inductive,_,_) = List.nth itl i in
1280              if is_inductive then None else (Some uri)
1281          | _ ->
1282            raise (WrongUriToMutualInductiveDefinitions
1283             (UriManager.string_of_uri uri))
1284         )
1285     | C.Prod (_,_,de) -> returns_a_coinductive de
1286     | _ -> None
1287
1288  in
1289   type_of_aux env t
1290
1291 (* is a small constructor? *)
1292 (*CSC: ottimizzare calcolando staticamente *)
1293 and is_small paramsno c =
1294  let rec is_small_aux env c =
1295   let module C = Cic in
1296    match CicReduction.whd c with
1297       C.Prod (_,so,de) ->
1298        (*CSC: [] is an empty metasenv. Is it correct? *)
1299        let s = type_of_aux' [] env so in
1300         (s = C.Sort C.Prop || s = C.Sort C.Set) &&
1301         is_small_aux (so::env) de
1302     | _ -> true (*CSC: we trust the type-checker *)
1303  in
1304   let (sx,dx) = split_prods paramsno c in
1305    is_small_aux (List.rev sx) dx
1306
1307 and type_of t =
1308  type_of_aux' [] [] t
1309 ;;
1310
1311 let typecheck uri =
1312  let module C = Cic in
1313  let module R = CicReduction in
1314  let module U = UriManager in
1315   match CicEnvironment.is_type_checked uri 0 with
1316      CicEnvironment.CheckedObj _ -> ()
1317    | CicEnvironment.UncheckedObj uobj ->
1318       (* let's typecheck the uncooked object *)
1319       Logger.log (`Start_type_checking uri) ;
1320       (match uobj with
1321           C.Definition (_,te,ty,_) ->
1322            let _ = type_of ty in
1323             if not (R.are_convertible (type_of te ) ty) then
1324              raise (NotWellTyped ("Constant " ^ (U.string_of_uri uri)))
1325         | C.Axiom (_,ty,_) ->
1326           (* only to check that ty is well-typed *)
1327           let _ = type_of ty in ()
1328         | C.CurrentProof (_,conjs,te,ty) ->
1329             (*CSC [] wrong *)
1330             let _ = type_of_aux' conjs [] ty in
1331              debug (type_of_aux' conjs [] te) [] ;
1332              if not (R.are_convertible (type_of_aux' conjs [] te) ty) then
1333               raise (NotWellTyped ("CurrentProof" ^ (U.string_of_uri uri)))
1334         | C.Variable (_,bo,ty) ->
1335            (* only to check that ty is well-typed *)
1336            let _ = type_of ty in
1337             (match bo with
1338                 None -> ()
1339               | Some bo ->
1340                  if not (R.are_convertible (type_of bo) ty) then
1341                   raise (NotWellTyped ("Variable" ^ (U.string_of_uri uri)))
1342             )
1343         | C.InductiveDefinition _ ->
1344            cooked_mutual_inductive_defs uri uobj
1345       ) ;
1346       CicEnvironment.set_type_checking_info uri ;
1347       Logger.log (`Type_checking_completed uri)
1348 ;;
1349