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