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