]> matita.cs.unibo.it Git - helm.git/blob - components/cic_proof_checking/cicTypeChecker.ml
experimental branch with no set baseuri command and no developments
[helm.git] / components / 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 (* $Id$ *)
27
28 (* TODO factorize functions to frequent errors (e.g. "Unknwon mutual inductive
29  * ...") *)
30
31 open Printf
32
33 exception AssertFailure of string Lazy.t;;
34 exception TypeCheckerFailure of string Lazy.t;;
35
36 let fdebug = ref 0;;
37 let debug t context =
38  let rec debug_aux t i =
39   let module C = Cic in
40   let module U = UriManager in
41    CicPp.ppobj (C.Variable ("DEBUG", None, t, [], [])) ^ "\n" ^ i
42  in
43   if !fdebug = 0 then
44    raise (TypeCheckerFailure (lazy (List.fold_right debug_aux (t::context) "")))
45 ;;
46
47 let debug_print = fun _ -> ();;
48
49 let rec split l n =
50  match (l,n) with
51     (l,0) -> ([], l)
52   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
53   | (_,_) ->
54       raise (TypeCheckerFailure (lazy "Parameters number < left parameters number"))
55 ;;
56
57 let debrujin_constructor ?(cb=fun _ _ -> ()) uri number_of_types =
58  let rec aux k t =
59   let module C = Cic in
60   let res =
61    match t with
62       C.Rel n as t when n <= k -> t
63     | C.Rel _ ->
64         raise (TypeCheckerFailure (lazy "unbound variable found in constructor type"))
65     | C.Var (uri,exp_named_subst) ->
66        let exp_named_subst' = 
67         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
68        in
69         C.Var (uri,exp_named_subst')
70     | C.Meta (i,l) ->
71        let l' = List.map (function None -> None | Some t -> Some (aux k t)) l in
72         C.Meta (i,l')
73     | C.Sort _
74     | C.Implicit _ as t -> t
75     | C.Cast (te,ty) -> C.Cast (aux k te, aux k ty)
76     | C.Prod (n,s,t) -> C.Prod (n, aux k s, aux (k+1) t)
77     | C.Lambda (n,s,t) -> C.Lambda (n, aux k s, aux (k+1) t)
78     | C.LetIn (n,s,t) -> C.LetIn (n, aux k s, aux (k+1) t)
79     | C.Appl l -> C.Appl (List.map (aux k) l)
80     | C.Const (uri,exp_named_subst) ->
81        let exp_named_subst' = 
82         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
83        in
84         C.Const (uri,exp_named_subst')
85     | C.MutInd (uri',tyno,exp_named_subst) when UriManager.eq uri uri' ->
86        if exp_named_subst != [] then
87         raise (TypeCheckerFailure
88           (lazy ("non-empty explicit named substitution is applied to "^
89            "a mutual inductive type which is being defined"))) ;
90        C.Rel (k + number_of_types - tyno) ;
91     | C.MutInd (uri',tyno,exp_named_subst) ->
92        let exp_named_subst' = 
93         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
94        in
95         C.MutInd (uri',tyno,exp_named_subst')
96     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
97        let exp_named_subst' = 
98         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
99        in
100         C.MutConstruct (uri,tyno,consno,exp_named_subst')
101     | C.MutCase (sp,i,outty,t,pl) ->
102        C.MutCase (sp, i, aux k outty, aux k t,
103         List.map (aux k) pl)
104     | C.Fix (i, fl) ->
105        let len = List.length fl in
106        let liftedfl =
107         List.map
108          (fun (name, i, ty, bo) -> (name, i, aux k ty, aux (k+len) bo))
109           fl
110        in
111         C.Fix (i, liftedfl)
112     | C.CoFix (i, fl) ->
113        let len = List.length fl in
114        let liftedfl =
115         List.map
116          (fun (name, ty, bo) -> (name, aux k ty, aux (k+len) bo))
117           fl
118        in
119         C.CoFix (i, liftedfl)
120   in
121    cb t res;
122    res
123  in
124   aux 0
125 ;;
126
127 exception CicEnvironmentError;;
128
129 let rec type_of_constant ~logger uri ugraph =
130  let module C = Cic in
131  let module R = CicReduction in
132  let module U = UriManager in
133  let cobj,ugraph =
134    match CicEnvironment.is_type_checked ~trust:true ugraph uri with
135       CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
136     | CicEnvironment.UncheckedObj uobj ->
137        logger#log (`Start_type_checking uri) ;
138        (* let's typecheck the uncooked obj *)
139
140 (****************************************************************
141   TASSI: FIXME qui e' inutile ricordarselo, 
142   tanto poi lo richiediamo alla cache che da quello su disco
143 *****************************************************************) 
144
145        let ugraph_dust = 
146          (match uobj with
147            C.Constant (_,Some te,ty,_,_) ->
148            let _,ugraph = type_of ~logger ty ugraph in
149            let type_of_te,ugraph' = type_of ~logger te ugraph in
150               let b',ugraph'' = (R.are_convertible [] type_of_te ty ugraph') in
151               if not b' then
152                raise (TypeCheckerFailure (lazy (sprintf
153                 "the constant %s is not well typed because the type %s of the body is not convertible to the declared type %s"
154                 (U.string_of_uri uri) (CicPp.ppterm type_of_te)
155                 (CicPp.ppterm ty))))
156               else
157                 ugraph'
158          | C.Constant (_,None,ty,_,_) ->
159            (* only to check that ty is well-typed *)
160            let _,ugraph' = type_of ~logger ty ugraph in 
161            ugraph'
162          | C.CurrentProof (_,conjs,te,ty,_,_) ->
163              let _,ugraph1 =
164               List.fold_left
165                (fun (metasenv,ugraph) ((_,context,ty) as conj) ->
166                  let _,ugraph' = 
167                    type_of_aux' ~logger metasenv context ty ugraph 
168                  in
169                  (metasenv @ [conj],ugraph')
170                ) ([],ugraph) conjs
171              in
172               let _,ugraph2 = type_of_aux' ~logger conjs [] ty ugraph1 in
173                let type_of_te,ugraph3 = 
174                  type_of_aux' ~logger conjs [] te ugraph2 
175                in
176                let b,ugraph4 = (R.are_convertible [] type_of_te ty ugraph3) in
177                if not b then
178                  raise (TypeCheckerFailure (lazy (sprintf
179                   "the current proof %s is not well typed because the type %s of the body is not convertible to the declared type %s"
180                   (U.string_of_uri uri) (CicPp.ppterm type_of_te)
181                   (CicPp.ppterm ty))))
182                else 
183                  ugraph4
184          | _ ->
185              raise
186               (TypeCheckerFailure (lazy ("Unknown constant:" ^ U.string_of_uri uri))))
187        in 
188          try
189            CicEnvironment.set_type_checking_info uri;
190            logger#log (`Type_checking_completed uri) ;
191            match CicEnvironment.is_type_checked ~trust:false ugraph uri with
192                CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
193              | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
194          with Invalid_argument s ->
195            (*debug_print (lazy s);*)
196            uobj,ugraph_dust       
197   in
198    match cobj,ugraph with
199       (C.Constant (_,_,ty,_,_)),g -> ty,g
200     | (C.CurrentProof (_,_,_,ty,_,_)),g -> ty,g
201     | _ ->
202         raise (TypeCheckerFailure (lazy ("Unknown constant:" ^ U.string_of_uri uri)))
203
204 and type_of_variable ~logger uri ugraph =
205  let module C = Cic in
206  let module R = CicReduction in
207  let module U = UriManager in
208   (* 0 because a variable is never cooked => no partial cooking at one level *)
209   match CicEnvironment.is_type_checked ~trust:true ugraph uri with
210      CicEnvironment.CheckedObj ((C.Variable (_,_,ty,_,_)),ugraph') -> ty,ugraph'
211    | CicEnvironment.UncheckedObj (C.Variable (_,bo,ty,_,_)) ->
212       logger#log (`Start_type_checking uri) ;
213       (* only to check that ty is well-typed *)
214       let _,ugraph1 = type_of ~logger ty ugraph in
215       let ugraph2 = 
216        (match bo with
217            None -> ugraph
218          | Some bo ->
219              let ty_bo,ugraph' = type_of ~logger bo ugraph1 in
220              let b,ugraph'' = (R.are_convertible [] ty_bo ty ugraph') in
221              if not b then
222               raise (TypeCheckerFailure
223                 (lazy ("Unknown variable:" ^ U.string_of_uri uri)))
224              else
225                ugraph'') 
226       in
227         (try
228            CicEnvironment.set_type_checking_info uri ;
229            logger#log (`Type_checking_completed uri) ;
230            match CicEnvironment.is_type_checked ~trust:false ugraph uri with
231                CicEnvironment.CheckedObj ((C.Variable (_,_,ty,_,_)),ugraph') -> 
232                  ty,ugraph'
233              | CicEnvironment.CheckedObj _ 
234              | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
235          with Invalid_argument s ->
236            (*debug_print (lazy s);*)
237            ty,ugraph2)
238    |  _ ->
239         raise (TypeCheckerFailure (lazy ("Unknown variable:" ^ U.string_of_uri uri)))
240
241 and does_not_occur ?(subst=[]) context n nn te =
242  let module C = Cic in
243    match te with
244       C.Rel m when m > n && m <= nn -> false
245     | C.Rel m ->
246        (try
247          (match List.nth context (m-1) with
248              Some (_,C.Def (bo,_)) ->
249               does_not_occur ~subst context n nn (CicSubstitution.lift m bo)
250            | _ -> true)
251         with
252          Failure _ -> assert false)
253     | C.Sort _
254     | C.Implicit _ -> true
255     | C.Meta (_,l) ->
256        List.fold_right
257         (fun x i ->
258           match x with
259              None -> i
260            | Some x -> i && does_not_occur ~subst context n nn x) l true &&
261        (try
262          let (canonical_context,term,ty) = CicUtil.lookup_subst n subst in
263           does_not_occur ~subst context n nn (CicSubstitution.subst_meta l term)
264         with
265          CicUtil.Subst_not_found _ -> true)
266     | C.Cast (te,ty) ->
267        does_not_occur ~subst context n nn te && does_not_occur ~subst context n nn ty
268     | C.Prod (name,so,dest) ->
269        does_not_occur ~subst context n nn so &&
270         does_not_occur ~subst ((Some (name,(C.Decl so)))::context) (n + 1)
271          (nn + 1) dest
272     | C.Lambda (name,so,dest) ->
273        does_not_occur ~subst context n nn so &&
274         does_not_occur ~subst ((Some (name,(C.Decl so)))::context) (n + 1) (nn + 1)
275          dest
276     | C.LetIn (name,so,dest) ->
277        does_not_occur ~subst context n nn so &&
278         does_not_occur ~subst ((Some (name,(C.Def (so,None))))::context)
279          (n + 1) (nn + 1) dest
280     | C.Appl l ->
281        List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) l true
282     | C.Var (_,exp_named_subst)
283     | C.Const (_,exp_named_subst)
284     | C.MutInd (_,_,exp_named_subst)
285     | C.MutConstruct (_,_,_,exp_named_subst) ->
286        List.fold_right (fun (_,x) i -> i && does_not_occur ~subst context n nn x)
287         exp_named_subst true
288     | C.MutCase (_,_,out,te,pl) ->
289        does_not_occur ~subst context n nn out && does_not_occur ~subst context n nn te &&
290         List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) pl true
291     | C.Fix (_,fl) ->
292        let len = List.length fl in
293         let n_plus_len = n + len in
294         let nn_plus_len = nn + len in
295         let tys,_ =
296          List.fold_left
297           (fun (types,len) (n,_,ty,_) ->
298              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
299               len+1)
300           ) ([],0) fl
301         in
302          List.fold_right
303           (fun (_,_,ty,bo) i ->
304             i && does_not_occur ~subst context n nn ty &&
305             does_not_occur ~subst (tys @ context) n_plus_len nn_plus_len bo
306           ) fl true
307     | C.CoFix (_,fl) ->
308        let len = List.length fl in
309         let n_plus_len = n + len in
310         let nn_plus_len = nn + len in
311         let tys,_ =
312          List.fold_left
313           (fun (types,len) (n,ty,_) ->
314              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
315               len+1)
316           ) ([],0) fl
317         in
318          List.fold_right
319           (fun (_,ty,bo) i ->
320             i && does_not_occur ~subst context n nn ty &&
321             does_not_occur ~subst (tys @ context) n_plus_len nn_plus_len bo
322           ) fl true
323
324 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
325 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
326 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla  *)
327 (*CSC strictly_positive                                                  *)
328 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-)              *)
329 and weakly_positive context n nn uri te =
330  let module C = Cic in
331 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
332   let dummy_mutind =
333    C.MutInd (HelmLibraryObjects.Datatypes.nat_URI,0,[])
334   in
335   (*CSC: mettere in cicSubstitution *)
336   let rec subst_inductive_type_with_dummy_mutind =
337    function
338       C.MutInd (uri',0,_) when UriManager.eq uri' uri ->
339        dummy_mutind
340     | C.Appl ((C.MutInd (uri',0,_))::tl) when UriManager.eq uri' uri ->
341        dummy_mutind
342     | C.Cast (te,ty) -> subst_inductive_type_with_dummy_mutind te
343     | C.Prod (name,so,ta) ->
344        C.Prod (name, subst_inductive_type_with_dummy_mutind so,
345         subst_inductive_type_with_dummy_mutind ta)
346     | C.Lambda (name,so,ta) ->
347        C.Lambda (name, subst_inductive_type_with_dummy_mutind so,
348         subst_inductive_type_with_dummy_mutind ta)
349     | C.Appl tl ->
350        C.Appl (List.map subst_inductive_type_with_dummy_mutind tl)
351     | C.MutCase (uri,i,outtype,term,pl) ->
352        C.MutCase (uri,i,
353         subst_inductive_type_with_dummy_mutind outtype,
354         subst_inductive_type_with_dummy_mutind term,
355         List.map subst_inductive_type_with_dummy_mutind pl)
356     | C.Fix (i,fl) ->
357        C.Fix (i,List.map (fun (name,i,ty,bo) -> (name,i,
358         subst_inductive_type_with_dummy_mutind ty,
359         subst_inductive_type_with_dummy_mutind bo)) fl)
360     | C.CoFix (i,fl) ->
361        C.CoFix (i,List.map (fun (name,ty,bo) -> (name,
362         subst_inductive_type_with_dummy_mutind ty,
363         subst_inductive_type_with_dummy_mutind bo)) fl)
364     | C.Const (uri,exp_named_subst) ->
365        let exp_named_subst' =
366         List.map
367          (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
368          exp_named_subst
369        in
370         C.Const (uri,exp_named_subst')
371     | C.MutInd (uri,typeno,exp_named_subst) ->
372        let exp_named_subst' =
373         List.map
374          (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
375          exp_named_subst
376        in
377         C.MutInd (uri,typeno,exp_named_subst')
378     | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
379        let exp_named_subst' =
380         List.map
381          (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
382          exp_named_subst
383        in
384         C.MutConstruct (uri,typeno,consno,exp_named_subst')
385     | t -> t
386   in
387   match CicReduction.whd context te with
388 (*
389      C.Appl ((C.MutInd (uri',0,_))::tl) when UriManager.eq uri' uri -> true
390 *)
391      C.Appl ((C.MutInd (uri',_,_))::tl) when UriManager.eq uri' uri -> true
392    | C.MutInd (uri',0,_) when UriManager.eq uri' uri -> true
393    | C.Prod (C.Anonymous,source,dest) ->
394       strictly_positive context n nn
395        (subst_inductive_type_with_dummy_mutind source) &&
396        weakly_positive ((Some (C.Anonymous,(C.Decl source)))::context)
397         (n + 1) (nn + 1) uri dest
398    | C.Prod (name,source,dest) when
399       does_not_occur ((Some (name,(C.Decl source)))::context) 0 n dest ->
400        (* dummy abstraction, so we behave as in the anonimous case *)
401        strictly_positive context n nn
402         (subst_inductive_type_with_dummy_mutind source) &&
403          weakly_positive ((Some (name,(C.Decl source)))::context)
404          (n + 1) (nn + 1) uri dest
405    | C.Prod (name,source,dest) ->
406        does_not_occur context n nn
407          (subst_inductive_type_with_dummy_mutind source)&&
408          weakly_positive ((Some (name,(C.Decl source)))::context)
409          (n + 1) (nn + 1) uri dest
410    | _ ->
411      raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
412
413 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C                             *)
414 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
415 and instantiate_parameters params c =
416  let module C = Cic in
417   match (c,params) with
418      (c,[]) -> c
419    | (C.Prod (_,_,ta), he::tl) ->
420        instantiate_parameters tl
421         (CicSubstitution.subst he ta)
422    | (C.Cast (te,_), _) -> instantiate_parameters params te
423    | (t,l) -> raise (AssertFailure (lazy "1"))
424
425 and strictly_positive context n nn te =
426  let module C = Cic in
427  let module U = UriManager in
428   match CicReduction.whd context te with
429    | t when does_not_occur context n nn t -> true
430    | C.Rel _ -> true
431    | C.Cast (te,ty) ->
432       (*CSC: bisogna controllare ty????*)
433       strictly_positive context n nn te
434    | C.Prod (name,so,ta) ->
435       does_not_occur context n nn so &&
436        strictly_positive ((Some (name,(C.Decl so)))::context) (n+1) (nn+1) ta
437    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
438       List.fold_right (fun x i -> i && does_not_occur context n nn x) tl true
439    | C.Appl ((C.MutInd (uri,i,exp_named_subst))::tl) -> 
440       let (ok,paramsno,ity,cl,name) =
441         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
442           match o with
443               C.InductiveDefinition (tl,_,paramsno,_) ->
444                 let (name,_,ity,cl) = List.nth tl i in
445                 (List.length tl = 1, paramsno, ity, cl, name) 
446                 (* (true, paramsno, ity, cl, name) *)
447             | _ ->
448                 raise 
449                   (TypeCheckerFailure
450                      (lazy ("Unknown inductive type:" ^ U.string_of_uri uri)))
451       in 
452       let (params,arguments) = split tl paramsno in
453       let lifted_params = List.map (CicSubstitution.lift 1) params in
454       let cl' =
455         List.map
456           (fun (_,te) ->
457              instantiate_parameters lifted_params
458                (CicSubstitution.subst_vars exp_named_subst te)
459           ) cl
460       in
461         ok &&
462           List.fold_right
463           (fun x i -> i && does_not_occur context n nn x)
464           arguments true &&
465          (*CSC: MEGAPATCH3 (sara' quella giusta?)*)
466           List.fold_right
467           (fun x i ->
468              i &&
469                weakly_positive
470                ((Some (C.Name name,(Cic.Decl ity)))::context) (n+1) (nn+1) uri
471                x
472           ) cl' true
473    | t -> false
474        
475 (* the inductive type indexes are s.t. n < x <= nn *)
476 and are_all_occurrences_positive context uri indparamsno i n nn te =
477  let module C = Cic in
478   match CicReduction.whd context te with
479      C.Appl ((C.Rel m)::tl) when m = i ->
480       (*CSC: riscrivere fermandosi a 0 *)
481       (* let's check if the inductive type is applied at least to *)
482       (* indparamsno parameters                                   *)
483       let last =
484        List.fold_left
485         (fun k x ->
486           if k = 0 then 0
487           else
488            match CicReduction.whd context x with
489               C.Rel m when m = n - (indparamsno - k) -> k - 1
490             | _ ->
491               raise (TypeCheckerFailure
492                (lazy 
493                ("Non-positive occurence in mutual inductive definition(s) [1]" ^
494                 UriManager.string_of_uri uri)))
495         ) indparamsno tl
496       in
497        if last = 0 then
498         List.fold_right (fun x i -> i && does_not_occur context n nn x) tl true
499        else
500         raise (TypeCheckerFailure
501          (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
502           UriManager.string_of_uri uri)))
503    | C.Rel m when m = i ->
504       if indparamsno = 0 then
505        true
506       else
507         raise (TypeCheckerFailure
508          (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
509           UriManager.string_of_uri uri)))
510    | C.Prod (C.Anonymous,source,dest) ->
511        let b = strictly_positive context n nn source in
512        b &&
513        are_all_occurrences_positive
514         ((Some (C.Anonymous,(C.Decl source)))::context) uri indparamsno
515         (i+1) (n + 1) (nn + 1) dest
516    | C.Prod (name,source,dest) when
517       does_not_occur ((Some (name,(C.Decl source)))::context) 0 n dest ->
518       (* dummy abstraction, so we behave as in the anonimous case *)
519       strictly_positive context n nn source &&
520        are_all_occurrences_positive
521         ((Some (name,(C.Decl source)))::context) uri indparamsno
522         (i+1) (n + 1) (nn + 1) dest
523    | C.Prod (name,source,dest) ->
524       does_not_occur context n nn source &&
525        are_all_occurrences_positive ((Some (name,(C.Decl source)))::context)
526         uri indparamsno (i+1) (n + 1) (nn + 1) dest
527    | _ ->
528      raise
529       (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
530         (UriManager.string_of_uri uri))))
531
532 (* Main function to checks the correctness of a mutual *)
533 (* inductive block definition. This is the function    *)
534 (* exported to the proof-engine.                       *)
535 and typecheck_mutual_inductive_defs ~logger uri (itl,_,indparamsno) ugraph =
536  let module U = UriManager in
537   (* let's check if the arity of the inductive types are well *)
538   (* formed                                                   *)
539   let ugrap1 = List.fold_left 
540    (fun ugraph (_,_,x,_) -> let _,ugraph' = 
541       type_of ~logger x ugraph in ugraph') 
542    ugraph itl in
543
544   (* let's check if the types of the inductive constructors  *)
545   (* are well formed.                                        *)
546   (* In order not to use type_of_aux we put the types of the *)
547   (* mutual inductive types at the head of the types of the  *)
548   (* constructors using Prods                                *)
549   let len = List.length itl in
550   let tys =
551     List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) itl in
552   let _,ugraph2 =
553     List.fold_right
554       (fun (_,_,_,cl) (i,ugraph) ->
555         let ugraph'' = 
556           List.fold_left
557             (fun ugraph (name,te) -> 
558               let debrujinedte = debrujin_constructor uri len te in
559               let augmented_term =
560                 List.fold_right
561                   (fun (name,_,ty,_) i -> Cic.Prod (Cic.Name name, ty, i))
562                   itl debrujinedte
563               in
564               let _,ugraph' = type_of ~logger augmented_term ugraph in
565               (* let's check also the positivity conditions *)
566               if
567                 not
568                   (are_all_occurrences_positive tys uri indparamsno i 0 len
569                      debrujinedte)
570               then
571                 begin
572                 prerr_endline (UriManager.string_of_uri uri);
573                 prerr_endline (string_of_int (List.length tys));
574                 raise
575                   (TypeCheckerFailure
576                     (lazy ("Non positive occurence in " ^ U.string_of_uri uri)))                end 
577               else
578                 ugraph'
579             ) ugraph cl in
580         (i + 1),ugraph''
581       ) itl (1,ugrap1)
582   in
583   ugraph2
584
585 (* Main function to checks the correctness of a mutual *)
586 (* inductive block definition.                         *)
587 and check_mutual_inductive_defs uri obj ugraph =
588   match obj with
589       Cic.InductiveDefinition (itl, params, indparamsno, _) ->
590         typecheck_mutual_inductive_defs uri (itl,params,indparamsno) ugraph 
591     | _ ->
592         raise (TypeCheckerFailure (
593                 lazy ("Unknown mutual inductive definition:" ^
594                  UriManager.string_of_uri uri)))
595
596 and type_of_mutual_inductive_defs ~logger uri i ugraph =
597  let module C = Cic in
598  let module R = CicReduction in
599  let module U = UriManager in
600   let cobj,ugraph1 =
601    match CicEnvironment.is_type_checked ~trust:true ugraph uri with
602        CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
603      | CicEnvironment.UncheckedObj uobj ->
604          logger#log (`Start_type_checking uri) ;
605          let ugraph1_dust = 
606            check_mutual_inductive_defs ~logger uri uobj ugraph 
607          in
608            (* TASSI: FIXME: check ugraph1 == ugraph ritornato da env *)
609            try 
610              CicEnvironment.set_type_checking_info uri ;
611              logger#log (`Type_checking_completed uri) ;
612              (match CicEnvironment.is_type_checked ~trust:false ugraph uri with
613                   CicEnvironment.CheckedObj (cobj,ugraph') -> (cobj,ugraph')
614                 | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
615              )
616            with
617                Invalid_argument s ->
618                  (*debug_print (lazy s);*)
619                  uobj,ugraph1_dust
620   in
621     match cobj with
622         C.InductiveDefinition (dl,_,_,_) ->
623           let (_,_,arity,_) = List.nth dl i in
624             arity,ugraph1
625       | _ ->
626           raise (TypeCheckerFailure
627            (lazy ("Unknown mutual inductive definition:" ^ U.string_of_uri uri)))
628             
629 and type_of_mutual_inductive_constr ~logger uri i j ugraph =
630  let module C = Cic in
631  let module R = CicReduction in
632  let module U = UriManager in
633   let cobj,ugraph1 =
634     match CicEnvironment.is_type_checked ~trust:true ugraph uri with
635         CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
636       | CicEnvironment.UncheckedObj uobj ->
637           logger#log (`Start_type_checking uri) ;
638           let ugraph1_dust = 
639             check_mutual_inductive_defs ~logger uri uobj ugraph 
640           in
641             (* check ugraph1 validity ??? == ugraph' *)
642             try
643               CicEnvironment.set_type_checking_info uri ;
644               logger#log (`Type_checking_completed uri) ;
645               (match 
646                  CicEnvironment.is_type_checked ~trust:false ugraph uri 
647                with
648                  CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph' 
649                | CicEnvironment.UncheckedObj _ -> 
650                        raise CicEnvironmentError)
651             with
652                 Invalid_argument s ->
653                   (*debug_print (lazy s);*)
654                   uobj,ugraph1_dust
655   in
656     match cobj with
657         C.InductiveDefinition (dl,_,_,_) ->
658           let (_,_,_,cl) = List.nth dl i in
659           let (_,ty) = List.nth cl (j-1) in
660             ty,ugraph1
661       | _ ->
662           raise (TypeCheckerFailure
663            (lazy ("Unknown mutual inductive definition:" ^ UriManager.string_of_uri uri)))
664
665 and recursive_args context n nn te =
666  let module C = Cic in
667   match CicReduction.whd context te with
668      C.Rel _ -> []
669    | C.Var _
670    | C.Meta _
671    | C.Sort _
672    | C.Implicit _
673    | C.Cast _ (*CSC ??? *) ->
674       raise (AssertFailure (lazy "3")) (* due to type-checking *)
675    | C.Prod (name,so,de) ->
676       (not (does_not_occur context n nn so)) ::
677        (recursive_args ((Some (name,(C.Decl so)))::context) (n+1) (nn + 1) de)
678    | C.Lambda _
679    | C.LetIn _ ->
680       raise (AssertFailure (lazy "4")) (* due to type-checking *)
681    | C.Appl _ -> []
682    | C.Const _ -> raise (AssertFailure (lazy "5"))
683    | C.MutInd _
684    | C.MutConstruct _
685    | C.MutCase _
686    | C.Fix _
687    | C.CoFix _ -> raise (AssertFailure (lazy "6")) (* due to type-checking *)
688
689 and get_new_safes ~subst context p c rl safes n nn x =
690  let module C = Cic in
691  let module U = UriManager in
692  let module R = CicReduction in
693   match (R.whd ~subst context c, R.whd ~subst context p, rl) with
694      (C.Prod (_,so,ta1), C.Lambda (name,_,ta2), b::tl) ->
695        (* we are sure that the two sources are convertible because we *)
696        (* have just checked this. So let's go along ...               *)
697        let safes' =
698         List.map (fun x -> x + 1) safes
699        in
700         let safes'' =
701          if b then 1::safes' else safes'
702         in
703          get_new_safes ~subst ((Some (name,(C.Decl so)))::context)
704           ta2 ta1 tl safes'' (n+1) (nn+1) (x+1)
705    | (C.Prod _, (C.MutConstruct _ as e), _)
706    | (C.Prod _, (C.Rel _ as e), _)
707    | (C.MutInd _, e, [])
708    | (C.Appl _, e, []) -> (e,safes,n,nn,x,context)
709    | (c,p,l) ->
710       (* CSC: If the next exception is raised, it just means that   *)
711       (* CSC: the proof-assistant allows to use very strange things *)
712       (* CSC: as a branch of a case whose type is a Prod. In        *)
713       (* CSC: particular, this means that a new (C.Prod, x,_) case  *)
714       (* CSC: must be considered in this match. (e.g. x = MutCase)  *)
715       raise
716        (AssertFailure (lazy
717          (Printf.sprintf "Get New Safes: c=%s ; p=%s"
718            (CicPp.ppterm c) (CicPp.ppterm p))))
719
720 and split_prods ~subst context n te =
721  let module C = Cic in
722  let module R = CicReduction in
723   match (n, R.whd ~subst context te) with
724      (0, _) -> context,te
725    | (n, C.Prod (name,so,ta)) when n > 0 ->
726        split_prods ~subst ((Some (name,(C.Decl so)))::context) (n - 1) ta
727    | (_, _) -> raise (AssertFailure (lazy "8"))
728
729 and eat_lambdas ~subst context n te =
730  let module C = Cic in
731  let module R = CicReduction in
732   match (n, R.whd ~subst context te) with
733      (0, _) -> (te, 0, context)
734    | (n, C.Lambda (name,so,ta)) when n > 0 ->
735       let (te, k, context') =
736        eat_lambdas ~subst ((Some (name,(C.Decl so)))::context) (n - 1) ta
737       in
738        (te, k + 1, context')
739    | (n, te) ->
740        raise (AssertFailure (lazy (sprintf "9 (%d, %s)" n (CicPp.ppterm te))))
741
742 (*CSC: Tutto quello che segue e' l'intuzione di luca ;-) *) 
743 and check_is_really_smaller_arg ~subst context n nn kl x safes te =
744  (*CSC: forse la whd si puo' fare solo quando serve veramente. *)
745  (*CSC: cfr guarded_by_destructors                             *)
746  let module C = Cic in
747  let module U = UriManager in
748  match CicReduction.whd ~subst context te with
749      C.Rel m when List.mem m safes -> true
750    | C.Rel _ -> false
751    | C.Var _
752    | C.Meta _
753    | C.Sort _
754    | C.Implicit _
755    | C.Cast _
756 (*   | C.Cast (te,ty) ->
757       check_is_really_smaller_arg ~subst n nn kl x safes te &&
758        check_is_really_smaller_arg ~subst n nn kl x safes ty*)
759 (*   | C.Prod (_,so,ta) ->
760       check_is_really_smaller_arg ~subst n nn kl x safes so &&
761        check_is_really_smaller_arg ~subst (n+1) (nn+1) kl (x+1)
762         (List.map (fun x -> x + 1) safes) ta*)
763    | C.Prod _ -> raise (AssertFailure (lazy "10"))
764    | C.Lambda (name,so,ta) ->
765       check_is_really_smaller_arg ~subst context n nn kl x safes so &&
766        check_is_really_smaller_arg ~subst ((Some (name,(C.Decl so)))::context)
767         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
768    | C.LetIn (name,so,ta) ->
769       check_is_really_smaller_arg ~subst context n nn kl x safes so &&
770        check_is_really_smaller_arg ~subst ((Some (name,(C.Def (so,None))))::context)
771         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
772    | C.Appl (he::_) ->
773       (*CSC: sulla coda ci vogliono dei controlli? secondo noi no, ma *)
774       (*CSC: solo perche' non abbiamo trovato controesempi            *)
775       check_is_really_smaller_arg ~subst context n nn kl x safes he
776    | C.Appl [] -> raise (AssertFailure (lazy "11"))
777    | C.Const _
778    | C.MutInd _ -> raise (AssertFailure (lazy "12"))
779    | C.MutConstruct _ -> false
780    | C.MutCase (uri,i,outtype,term,pl) ->
781       (match term with
782           C.Rel m when List.mem m safes || m = x ->
783            let (lefts_and_tys,len,isinductive,paramsno,cl) =
784             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
785             match o with
786                C.InductiveDefinition (tl,_,paramsno,_) ->
787                 let tys =
788                  List.map
789                   (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) tl
790                 in
791                  let (_,isinductive,_,cl) = List.nth tl i in
792                   let cl' =
793                    List.map
794                     (fun (id,ty) ->
795                       (id, snd (split_prods ~subst tys paramsno ty))) cl in
796                   let lefts =
797                    match tl with
798                       [] -> assert false
799                     | (_,_,ty,_)::_ ->
800                        fst (split_prods ~subst [] paramsno ty)
801                   in
802                    (tys@lefts,List.length tl,isinductive,paramsno,cl')
803              | _ ->
804                 raise (TypeCheckerFailure
805                   (lazy ("Unknown mutual inductive definition:" ^
806                   UriManager.string_of_uri uri)))
807            in
808             if not isinductive then
809               List.fold_right
810                (fun p i ->
811                  i && check_is_really_smaller_arg ~subst context n nn kl x safes p)
812                pl true
813             else
814              let pl_and_cl =
815               try
816                List.combine pl cl
817               with
818                Invalid_argument _ ->
819                 raise (TypeCheckerFailure (lazy "not enough patterns"))
820              in
821               List.fold_right
822                (fun (p,(_,c)) i ->
823                  let rl' =
824                   let debrujinedte = debrujin_constructor uri len c in
825                    recursive_args lefts_and_tys 0 len debrujinedte
826                  in
827                   let (e,safes',n',nn',x',context') =
828                    get_new_safes ~subst context p c rl' safes n nn x
829                   in
830                    i &&
831                    check_is_really_smaller_arg ~subst context' n' nn' kl x' safes' e
832                ) pl_and_cl true
833         | C.Appl ((C.Rel m)::tl) when List.mem m safes || m = x ->
834            let (lefts_and_tys,len,isinductive,paramsno,cl) =
835             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
836             match o with
837                C.InductiveDefinition (tl,_,paramsno,_) ->
838                 let (_,isinductive,_,cl) = List.nth tl i in
839                  let tys =
840                   List.map (fun (n,_,ty,_) ->
841                    Some(Cic.Name n,(Cic.Decl ty))) tl
842                  in
843                   let cl' =
844                    List.map
845                     (fun (id,ty) ->
846                       (id, snd (split_prods ~subst tys paramsno ty))) cl in
847                   let lefts =
848                    match tl with
849                       [] -> assert false
850                     | (_,_,ty,_)::_ ->
851                        fst (split_prods ~subst [] paramsno ty)
852                   in
853                    (tys@lefts,List.length tl,isinductive,paramsno,cl')
854              | _ ->
855                 raise (TypeCheckerFailure
856                   (lazy ("Unknown mutual inductive definition:" ^
857                   UriManager.string_of_uri uri)))
858            in
859             if not isinductive then
860               List.fold_right
861                (fun p i ->
862                  i && check_is_really_smaller_arg ~subst context n nn kl x safes p)
863                pl true
864             else
865              let pl_and_cl =
866               try
867                List.combine pl cl
868               with
869                Invalid_argument _ ->
870                 raise (TypeCheckerFailure (lazy "not enough patterns"))
871              in
872               (*CSC: supponiamo come prima che nessun controllo sia necessario*)
873               (*CSC: sugli argomenti di una applicazione                      *)
874               List.fold_right
875                (fun (p,(_,c)) i ->
876                  let rl' =
877                   let debrujinedte = debrujin_constructor uri len c in
878                    recursive_args lefts_and_tys 0 len debrujinedte
879                  in
880                   let (e, safes',n',nn',x',context') =
881                    get_new_safes ~subst context p c rl' safes n nn x
882                   in
883                    i &&
884                    check_is_really_smaller_arg ~subst context' n' nn' kl x' safes' e
885                ) pl_and_cl true
886         | _ ->
887           List.fold_right
888            (fun p i ->
889              i && check_is_really_smaller_arg ~subst context n nn kl x safes p
890            ) pl true
891       )
892    | C.Fix (_, fl) ->
893       let len = List.length fl in
894        let n_plus_len = n + len
895        and nn_plus_len = nn + len
896        and x_plus_len = x + len
897        and tys,_ =
898         List.fold_left
899           (fun (types,len) (n,_,ty,_) ->
900              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
901               len+1)
902           ) ([],0) fl
903        and safes' = List.map (fun x -> x + len) safes in
904         List.fold_right
905          (fun (_,_,ty,bo) i ->
906            i &&
907             check_is_really_smaller_arg ~subst (tys@context) n_plus_len nn_plus_len kl
908              x_plus_len safes' bo
909          ) fl true
910    | C.CoFix (_, fl) ->
911       let len = List.length fl in
912        let n_plus_len = n + len
913        and nn_plus_len = nn + len
914        and x_plus_len = x + len
915        and tys,_ =
916         List.fold_left
917           (fun (types,len) (n,ty,_) ->
918              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
919               len+1)
920           ) ([],0) fl
921        and safes' = List.map (fun x -> x + len) safes in
922         List.fold_right
923          (fun (_,ty,bo) i ->
924            i &&
925             check_is_really_smaller_arg ~subst (tys@context) n_plus_len nn_plus_len kl
926              x_plus_len safes' bo
927          ) fl true
928
929 and guarded_by_destructors ~subst context n nn kl x safes =
930  let module C = Cic in
931  let module U = UriManager in
932   function
933      C.Rel m when m > n && m <= nn -> false
934    | C.Rel m ->
935       (match List.nth context (n-1) with
936           Some (_,C.Decl _) -> true
937         | Some (_,C.Def (bo,_)) ->
938            guarded_by_destructors ~subst context m nn kl x safes
939             (CicSubstitution.lift m bo)
940         | None -> raise (TypeCheckerFailure (lazy "Reference to deleted hypothesis"))
941       )
942    | C.Meta _
943    | C.Sort _
944    | C.Implicit _ -> true
945    | C.Cast (te,ty) ->
946       guarded_by_destructors ~subst context n nn kl x safes te &&
947        guarded_by_destructors ~subst context n nn kl x safes ty
948    | C.Prod (name,so,ta) ->
949       guarded_by_destructors ~subst context n nn kl x safes so &&
950        guarded_by_destructors ~subst ((Some (name,(C.Decl so)))::context)
951         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
952    | C.Lambda (name,so,ta) ->
953       guarded_by_destructors ~subst context n nn kl x safes so &&
954        guarded_by_destructors ~subst ((Some (name,(C.Decl so)))::context)
955         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
956    | C.LetIn (name,so,ta) ->
957       guarded_by_destructors ~subst context n nn kl x safes so &&
958        guarded_by_destructors ~subst ((Some (name,(C.Def (so,None))))::context)
959         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
960    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
961       let k = List.nth kl (m - n - 1) in
962        if not (List.length tl > k) then false
963        else
964         List.fold_right
965          (fun param i ->
966            i && guarded_by_destructors ~subst context n nn kl x safes param
967          ) tl true &&
968          check_is_really_smaller_arg ~subst context n nn kl x safes (List.nth tl k)
969    | C.Appl tl ->
970       List.fold_right
971        (fun t i -> i && guarded_by_destructors ~subst context n nn kl x safes t)
972        tl true
973    | C.Var (_,exp_named_subst)
974    | C.Const (_,exp_named_subst)
975    | C.MutInd (_,_,exp_named_subst)
976    | C.MutConstruct (_,_,_,exp_named_subst) ->
977       List.fold_right
978        (fun (_,t) i -> i && guarded_by_destructors ~subst context n nn kl x safes t)
979        exp_named_subst true
980    | C.MutCase (uri,i,outtype,term,pl) ->
981       (match CicReduction.whd ~subst context term with
982           C.Rel m when List.mem m safes || m = x ->
983            let (lefts_and_tys,len,isinductive,paramsno,cl) =
984             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
985             match o with
986                C.InductiveDefinition (tl,_,paramsno,_) ->
987                 let len = List.length tl in
988                  let (_,isinductive,_,cl) = List.nth tl i in
989                   let tys =
990                    List.map (fun (n,_,ty,_) ->
991                     Some(Cic.Name n,(Cic.Decl ty))) tl
992                   in
993                    let cl' =
994                     List.map
995                      (fun (id,ty) ->
996                       let debrujinedty = debrujin_constructor uri len ty in
997                        (id, snd (split_prods ~subst tys paramsno ty),
998                         snd (split_prods ~subst tys paramsno debrujinedty)
999                        )) cl in
1000                    let lefts =
1001                     match tl with
1002                        [] -> assert false
1003                      | (_,_,ty,_)::_ ->
1004                         fst (split_prods ~subst [] paramsno ty)
1005                    in
1006                     (tys@lefts,len,isinductive,paramsno,cl')
1007              | _ ->
1008                 raise (TypeCheckerFailure
1009                   (lazy ("Unknown mutual inductive definition:" ^
1010                   UriManager.string_of_uri uri)))
1011            in
1012             if not isinductive then
1013              guarded_by_destructors ~subst context n nn kl x safes outtype &&
1014               guarded_by_destructors ~subst context n nn kl x safes term &&
1015               (*CSC: manca ??? il controllo sul tipo di term? *)
1016               List.fold_right
1017                (fun p i ->
1018                  i && guarded_by_destructors ~subst context n nn kl x safes p)
1019                pl true
1020             else
1021              let pl_and_cl =
1022               try
1023                List.combine pl cl
1024               with
1025                Invalid_argument _ ->
1026                 raise (TypeCheckerFailure (lazy "not enough patterns"))
1027              in
1028              guarded_by_destructors ~subst context n nn kl x safes outtype &&
1029               (*CSC: manca ??? il controllo sul tipo di term? *)
1030               List.fold_right
1031                (fun (p,(_,c,brujinedc)) i ->
1032                  let rl' = recursive_args lefts_and_tys 0 len brujinedc in
1033                   let (e,safes',n',nn',x',context') =
1034                    get_new_safes ~subst context p c rl' safes n nn x
1035                   in
1036                    i &&
1037                    guarded_by_destructors ~subst context' n' nn' kl x' safes' e
1038                ) pl_and_cl true
1039         | C.Appl ((C.Rel m)::tl) when List.mem m safes || m = x ->
1040            let (lefts_and_tys,len,isinductive,paramsno,cl) =
1041             let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1042             match o with
1043                C.InductiveDefinition (tl,_,paramsno,_) ->
1044                 let (_,isinductive,_,cl) = List.nth tl i in
1045                  let tys =
1046                   List.map
1047                    (fun (n,_,ty,_) -> Some(Cic.Name n,(Cic.Decl ty))) tl
1048                  in
1049                   let cl' =
1050                    List.map
1051                     (fun (id,ty) ->
1052                       (id, snd (split_prods ~subst tys paramsno ty))) cl in
1053                   let lefts =
1054                    match tl with
1055                       [] -> assert false
1056                     | (_,_,ty,_)::_ ->
1057                        fst (split_prods ~subst [] paramsno ty)
1058                   in
1059                    (tys@lefts,List.length tl,isinductive,paramsno,cl')
1060              | _ ->
1061                 raise (TypeCheckerFailure
1062                   (lazy ("Unknown mutual inductive definition:" ^
1063                   UriManager.string_of_uri uri)))
1064            in
1065             if not isinductive then
1066              guarded_by_destructors ~subst context n nn kl x safes outtype &&
1067               guarded_by_destructors ~subst context n nn kl x safes term &&
1068               (*CSC: manca ??? il controllo sul tipo di term? *)
1069               List.fold_right
1070                (fun p i ->
1071                  i && guarded_by_destructors ~subst context n nn kl x safes p)
1072                pl true
1073             else
1074              let pl_and_cl =
1075               try
1076                List.combine pl cl
1077               with
1078                Invalid_argument _ ->
1079                 raise (TypeCheckerFailure (lazy "not enough patterns"))
1080              in
1081              guarded_by_destructors ~subst context n nn kl x safes outtype &&
1082               (*CSC: manca ??? il controllo sul tipo di term? *)
1083               List.fold_right
1084                (fun t i ->
1085                  i && guarded_by_destructors ~subst context n nn kl x safes t)
1086                tl true &&
1087               List.fold_right
1088                (fun (p,(_,c)) i ->
1089                  let rl' =
1090                   let debrujinedte = debrujin_constructor uri len c in
1091                    recursive_args lefts_and_tys 0 len debrujinedte
1092                  in
1093                   let (e, safes',n',nn',x',context') =
1094                    get_new_safes ~subst context p c rl' safes n nn x
1095                   in
1096                    i &&
1097                    guarded_by_destructors ~subst context' n' nn' kl x' safes' e
1098                ) pl_and_cl true
1099         | _ ->
1100           guarded_by_destructors ~subst context n nn kl x safes outtype &&
1101            guarded_by_destructors ~subst context n nn kl x safes term &&
1102            (*CSC: manca ??? il controllo sul tipo di term? *)
1103            List.fold_right
1104             (fun p i -> i && guarded_by_destructors ~subst context n nn kl x safes p)
1105             pl true
1106       )
1107    | C.Fix (_, fl) ->
1108       let len = List.length fl in
1109        let n_plus_len = n + len
1110        and nn_plus_len = nn + len
1111        and x_plus_len = x + len
1112        and tys,_ =
1113         List.fold_left
1114           (fun (types,len) (n,_,ty,_) ->
1115              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1116               len+1)
1117           ) ([],0) fl
1118        and safes' = List.map (fun x -> x + len) safes in
1119         List.fold_right
1120          (fun (_,_,ty,bo) i ->
1121            i && guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
1122             guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
1123              x_plus_len safes' bo
1124          ) fl true
1125    | C.CoFix (_, fl) ->
1126       let len = List.length fl in
1127        let n_plus_len = n + len
1128        and nn_plus_len = nn + len
1129        and x_plus_len = x + len
1130        and tys,_ =
1131         List.fold_left
1132           (fun (types,len) (n,ty,_) ->
1133              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1134               len+1)
1135           ) ([],0) fl
1136        and safes' = List.map (fun x -> x + len) safes in
1137         List.fold_right
1138          (fun (_,ty,bo) i ->
1139            i &&
1140             guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
1141             guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
1142              x_plus_len safes' bo
1143          ) fl true
1144
1145 (* the boolean h means already protected *)
1146 (* args is the list of arguments the type of the constructor that may be *)
1147 (* found in head position must be applied to.                            *)
1148 and guarded_by_constructors ~subst context n nn h te args coInductiveTypeURI =
1149  let module C = Cic in
1150   (*CSC: There is a lot of code replication between the cases X and    *)
1151   (*CSC: (C.Appl X tl). Maybe it will be better to define a function   *)
1152   (*CSC: that maps X into (C.Appl X []) when X is not already a C.Appl *)
1153   match CicReduction.whd ~subst context te with
1154      C.Rel m when m > n && m <= nn -> h
1155    | C.Rel _ -> true
1156    | C.Meta _
1157    | C.Sort _
1158    | C.Implicit _
1159    | C.Cast _
1160    | C.Prod _
1161    | C.LetIn _ ->
1162       (* the term has just been type-checked *)
1163       raise (AssertFailure (lazy "17"))
1164    | C.Lambda (name,so,de) ->
1165       does_not_occur ~subst context n nn so &&
1166        guarded_by_constructors ~subst ((Some (name,(C.Decl so)))::context)
1167         (n + 1) (nn + 1) h de args coInductiveTypeURI
1168    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
1169       h &&
1170        List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) tl true
1171    | C.Appl ((C.MutConstruct (uri,i,j,exp_named_subst))::tl) ->
1172       let consty =
1173         let obj,_ = 
1174           try 
1175             CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
1176           with Not_found -> assert false
1177         in
1178        match obj with
1179           C.InductiveDefinition (itl,_,_,_) ->
1180            let (_,_,_,cl) = List.nth itl i in
1181             let (_,cons) = List.nth cl (j - 1) in
1182              CicSubstitution.subst_vars exp_named_subst cons
1183         | _ ->
1184             raise (TypeCheckerFailure
1185              (lazy ("Unknown mutual inductive definition:" ^ UriManager.string_of_uri uri)))
1186       in
1187        let rec analyse_branch context ty te =
1188         match CicReduction.whd ~subst context ty with
1189            C.Meta _ -> raise (AssertFailure (lazy "34"))
1190          | C.Rel _
1191          | C.Var _
1192          | C.Sort _ ->
1193             does_not_occur ~subst context n nn te
1194          | C.Implicit _
1195          | C.Cast _ ->
1196             raise (AssertFailure (lazy "24"))(* due to type-checking *)
1197          | C.Prod (name,so,de) ->
1198             analyse_branch ((Some (name,(C.Decl so)))::context) de te
1199          | C.Lambda _
1200          | C.LetIn _ ->
1201             raise (AssertFailure (lazy "25"))(* due to type-checking *)
1202          | C.Appl ((C.MutInd (uri,_,_))::_) when uri == coInductiveTypeURI -> 
1203              guarded_by_constructors ~subst context n nn true te []
1204               coInductiveTypeURI
1205          | C.Appl ((C.MutInd (uri,_,_))::_) -> 
1206             guarded_by_constructors ~subst context n nn true te tl
1207              coInductiveTypeURI
1208          | C.Appl _ ->
1209             does_not_occur ~subst context n nn te
1210          | C.Const _ -> raise (AssertFailure (lazy "26"))
1211          | C.MutInd (uri,_,_) when uri == coInductiveTypeURI ->
1212             guarded_by_constructors ~subst context n nn true te []
1213              coInductiveTypeURI
1214          | C.MutInd _ ->
1215             does_not_occur ~subst context n nn te
1216          | C.MutConstruct _ -> raise (AssertFailure (lazy "27"))
1217          (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
1218          (*CSC: in head position.                                       *)
1219          | C.MutCase _
1220          | C.Fix _
1221          | C.CoFix _ ->
1222             raise (AssertFailure (lazy "28"))(* due to type-checking *)
1223        in
1224        let rec analyse_instantiated_type context ty l =
1225         match CicReduction.whd ~subst context ty with
1226            C.Rel _
1227          | C.Var _
1228          | C.Meta _
1229          | C.Sort _
1230          | C.Implicit _
1231          | C.Cast _ -> raise (AssertFailure (lazy "29"))(* due to type-checking *)
1232          | C.Prod (name,so,de) ->
1233             begin
1234              match l with
1235                 [] -> true
1236               | he::tl ->
1237                  analyse_branch context so he &&
1238                   analyse_instantiated_type
1239                    ((Some (name,(C.Decl so)))::context) de tl
1240             end
1241          | C.Lambda _
1242          | C.LetIn _ ->
1243             raise (AssertFailure (lazy "30"))(* due to type-checking *)
1244          | C.Appl _ -> 
1245             List.fold_left
1246              (fun i x -> i && does_not_occur ~subst context n nn x) true l
1247          | C.Const _ -> raise (AssertFailure (lazy "31"))
1248          | C.MutInd _ ->
1249             List.fold_left
1250              (fun i x -> i && does_not_occur ~subst context n nn x) true l
1251          | C.MutConstruct _ -> raise (AssertFailure (lazy "32"))
1252          (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
1253          (*CSC: in head position.                                       *)
1254          | C.MutCase _
1255          | C.Fix _
1256          | C.CoFix _ ->
1257             raise (AssertFailure (lazy "33"))(* due to type-checking *)
1258        in
1259         let rec instantiate_type args consty =
1260          function
1261             [] -> true
1262           | tlhe::tltl as l ->
1263              let consty' = CicReduction.whd ~subst context consty in
1264               match args with 
1265                  he::tl ->
1266                   begin
1267                    match consty' with
1268                       C.Prod (_,_,de) ->
1269                        let instantiated_de = CicSubstitution.subst he de in
1270                         (*CSC: siamo sicuri che non sia troppo forte? *)
1271                         does_not_occur ~subst context n nn tlhe &
1272                          instantiate_type tl instantiated_de tltl
1273                     | _ ->
1274                       (*CSC:We do not consider backbones with a MutCase, a    *)
1275                       (*CSC:FixPoint, a CoFixPoint and so on in head position.*)
1276                       raise (AssertFailure (lazy "23"))
1277                   end
1278                | [] -> analyse_instantiated_type context consty' l
1279                   (* These are all the other cases *)
1280        in
1281         instantiate_type args consty tl
1282    | C.Appl ((C.CoFix (_,fl))::tl) ->
1283       List.fold_left (fun i x -> i && does_not_occur ~subst context n nn x) true tl &&
1284        let len = List.length fl in
1285         let n_plus_len = n + len
1286         and nn_plus_len = nn + len
1287         (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
1288         and tys,_ =
1289           List.fold_left
1290             (fun (types,len) (n,ty,_) ->
1291                (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1292                 len+1)
1293             ) ([],0) fl
1294         in
1295          List.fold_right
1296           (fun (_,ty,bo) i ->
1297             i && does_not_occur ~subst context n nn ty &&
1298              guarded_by_constructors ~subst (tys@context) n_plus_len nn_plus_len
1299               h bo args coInductiveTypeURI
1300           ) fl true
1301    | C.Appl ((C.MutCase (_,_,out,te,pl))::tl) ->
1302        List.fold_left (fun i x -> i && does_not_occur ~subst context n nn x) true tl &&
1303         does_not_occur ~subst context n nn out &&
1304          does_not_occur ~subst context n nn te &&
1305           List.fold_right
1306            (fun x i ->
1307              i &&
1308              guarded_by_constructors ~subst context n nn h x args
1309               coInductiveTypeURI
1310            ) pl true
1311    | C.Appl l ->
1312       List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) l true
1313    | C.Var (_,exp_named_subst)
1314    | C.Const (_,exp_named_subst) ->
1315       List.fold_right
1316        (fun (_,x) i -> i && does_not_occur ~subst context n nn x) exp_named_subst true
1317    | C.MutInd _ -> assert false
1318    | C.MutConstruct (_,_,_,exp_named_subst) ->
1319       List.fold_right
1320        (fun (_,x) i -> i && does_not_occur ~subst context n nn x) exp_named_subst true
1321    | C.MutCase (_,_,out,te,pl) ->
1322        does_not_occur ~subst context n nn out &&
1323         does_not_occur ~subst context n nn te &&
1324          List.fold_right
1325           (fun x i ->
1326             i &&
1327              guarded_by_constructors ~subst context n nn h x args
1328               coInductiveTypeURI
1329           ) pl true
1330    | C.Fix (_,fl) ->
1331       let len = List.length fl in
1332        let n_plus_len = n + len
1333        and nn_plus_len = nn + len
1334        (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
1335        and tys,_ =
1336         List.fold_left
1337           (fun (types,len) (n,_,ty,_) ->
1338              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1339               len+1)
1340           ) ([],0) fl
1341        in
1342         List.fold_right
1343          (fun (_,_,ty,bo) i ->
1344            i && does_not_occur ~subst context n nn ty &&
1345             does_not_occur ~subst (tys@context) n_plus_len nn_plus_len bo
1346          ) fl true
1347    | C.CoFix (_,fl) ->
1348       let len = List.length fl in
1349        let n_plus_len = n + len
1350        and nn_plus_len = nn + len
1351        (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
1352        and tys,_ =
1353         List.fold_left
1354           (fun (types,len) (n,ty,_) ->
1355              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1356               len+1)
1357           ) ([],0) fl
1358        in
1359         List.fold_right
1360          (fun (_,ty,bo) i ->
1361            i && does_not_occur ~subst context n nn ty &&
1362             guarded_by_constructors ~subst (tys@context) n_plus_len nn_plus_len
1363              h bo
1364              args coInductiveTypeURI
1365          ) fl true
1366
1367 and check_allowed_sort_elimination ~subst ~metasenv ~logger context uri i
1368   need_dummy ind arity1 arity2 ugraph =
1369  let module C = Cic in
1370  let module U = UriManager in
1371   let arity1 = CicReduction.whd ~subst context arity1 in
1372   let rec check_allowed_sort_elimination_aux ugraph context arity2 need_dummy =
1373    match arity1, CicReduction.whd ~subst context arity2 with
1374      (C.Prod (_,so1,de1), C.Prod (_,so2,de2)) ->
1375        let b,ugraph1 =
1376         CicReduction.are_convertible ~subst ~metasenv context so1 so2 ugraph in
1377        if b then
1378          check_allowed_sort_elimination ~subst ~metasenv ~logger context uri i
1379           need_dummy (C.Appl [CicSubstitution.lift 1 ind ; C.Rel 1]) de1 de2
1380           ugraph1
1381        else
1382          false,ugraph1
1383    | (C.Sort _, C.Prod (name,so,ta)) when not need_dummy ->
1384        let b,ugraph1 =
1385         CicReduction.are_convertible ~subst ~metasenv context so ind ugraph in
1386        if not b then
1387          false,ugraph1
1388        else
1389         check_allowed_sort_elimination_aux ugraph1
1390          ((Some (name,C.Decl so))::context) ta true
1391    | (C.Sort C.Prop, C.Sort C.Prop) when need_dummy -> true,ugraph
1392    | (C.Sort C.Prop, C.Sort C.Set)
1393    | (C.Sort C.Prop, C.Sort C.CProp)
1394    | (C.Sort C.Prop, C.Sort (C.Type _) ) when need_dummy ->
1395        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1396          match o with
1397          C.InductiveDefinition (itl,_,paramsno,_) ->
1398            let itl_len = List.length itl in
1399            let (name,_,ty,cl) = List.nth itl i in
1400            let cl_len = List.length cl in
1401             if (cl_len = 0 || (itl_len = 1 && cl_len = 1)) then
1402              let non_informative,ugraph =
1403               if cl_len = 0 then true,ugraph
1404               else
1405                is_non_informative ~logger [Some (C.Name name,C.Decl ty)]
1406                 paramsno (snd (List.nth cl 0)) ugraph
1407              in
1408               (* is it a singleton or empty non recursive and non informative
1409                  definition? *)
1410               non_informative, ugraph
1411             else
1412               false,ugraph
1413          | _ ->
1414              raise (TypeCheckerFailure 
1415                      (lazy ("Unknown mutual inductive definition:" ^
1416                        UriManager.string_of_uri uri)))
1417        )
1418    | (C.Sort C.Set, C.Sort C.Prop) when need_dummy -> true , ugraph
1419    | (C.Sort C.CProp, C.Sort C.Prop) when need_dummy -> true , ugraph
1420    | (C.Sort C.Set, C.Sort C.Set) when need_dummy -> true , ugraph
1421    | (C.Sort C.Set, C.Sort C.CProp) when need_dummy -> true , ugraph
1422    | (C.Sort C.CProp, C.Sort C.Set) when need_dummy -> true , ugraph
1423    | (C.Sort C.CProp, C.Sort C.CProp) when need_dummy -> true , ugraph
1424    | ((C.Sort C.Set, C.Sort (C.Type _)) | (C.Sort C.CProp, C.Sort (C.Type _)))
1425       when need_dummy ->
1426        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1427          match o with
1428            C.InductiveDefinition (itl,_,paramsno,_) ->
1429             let tys =
1430              List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) itl
1431             in
1432              let (_,_,_,cl) = List.nth itl i in
1433               (List.fold_right
1434                (fun (_,x) (i,ugraph) -> 
1435                  if i then
1436                    is_small ~logger tys paramsno x ugraph
1437                  else
1438                    false,ugraph
1439                     ) cl (true,ugraph))
1440            | _ ->
1441             raise (TypeCheckerFailure
1442              (lazy ("Unknown mutual inductive definition:" ^
1443               UriManager.string_of_uri uri)))
1444        )
1445    | (C.Sort (C.Type _), C.Sort _) when need_dummy -> true , ugraph
1446    | (_,_) -> false,ugraph
1447  in
1448   check_allowed_sort_elimination_aux ugraph context arity2 need_dummy
1449          
1450 and type_of_branch ~subst context argsno need_dummy outtype term constype =
1451  let module C = Cic in
1452  let module R = CicReduction in
1453   match R.whd ~subst context constype with
1454      C.MutInd (_,_,_) ->
1455       if need_dummy then
1456        outtype
1457       else
1458        C.Appl [outtype ; term]
1459    | C.Appl (C.MutInd (_,_,_)::tl) ->
1460       let (_,arguments) = split tl argsno
1461       in
1462        if need_dummy && arguments = [] then
1463         outtype
1464        else
1465         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
1466    | C.Prod (name,so,de) ->
1467       let term' =
1468        match CicSubstitution.lift 1 term with
1469           C.Appl l -> C.Appl (l@[C.Rel 1])
1470         | t -> C.Appl [t ; C.Rel 1]
1471       in
1472        C.Prod (name,so,type_of_branch ~subst
1473         ((Some (name,(C.Decl so)))::context) argsno need_dummy
1474         (CicSubstitution.lift 1 outtype) term' de)
1475    | _ -> raise (AssertFailure (lazy "20"))
1476
1477 (* check_metasenv_consistency checks that the "canonical" context of a
1478 metavariable is consitent - up to relocation via the relocation list l -
1479 with the actual context *)
1480
1481
1482 and check_metasenv_consistency ~logger ~subst metasenv context 
1483   canonical_context l ugraph 
1484 =
1485   let module C = Cic in
1486   let module R = CicReduction in
1487   let module S = CicSubstitution in
1488   let lifted_canonical_context = 
1489     let rec aux i =
1490      function
1491          [] -> []
1492        | (Some (n,C.Decl t))::tl ->
1493            (Some (n,C.Decl (S.subst_meta l (S.lift i t))))::(aux (i+1) tl)
1494        | (Some (n,C.Def (t,None)))::tl ->
1495            (Some (n,C.Def ((S.subst_meta l (S.lift i t)),None)))::(aux (i+1) tl)
1496        | None::tl -> None::(aux (i+1) tl)
1497        | (Some (n,C.Def (t,Some ty)))::tl ->
1498            (Some (n,C.Def ((S.subst_meta l (S.lift i t)),Some (S.subst_meta l (S.lift i ty)))))::(aux (i+1) tl)
1499     in
1500      aux 1 canonical_context
1501    in
1502    List.fold_left2 
1503      (fun ugraph t ct -> 
1504        match (t,ct) with
1505        | _,None -> ugraph
1506        | Some t,Some (_,C.Def (ct,_)) ->
1507            let b,ugraph1 = 
1508              R.are_convertible ~subst ~metasenv context t ct ugraph 
1509            in
1510            if not b then
1511              raise 
1512                (TypeCheckerFailure 
1513                   (lazy (sprintf "Not well typed metavariable local context: expected a term convertible with %s, found %s" (CicPp.ppterm ct) (CicPp.ppterm t))))
1514            else
1515              ugraph1
1516        | Some t,Some (_,C.Decl ct) ->
1517            let type_t,ugraph1 = 
1518              type_of_aux' ~logger ~subst metasenv context t ugraph 
1519            in
1520            let b,ugraph2 = 
1521              R.are_convertible ~subst ~metasenv context type_t ct ugraph1 
1522            in
1523            if not b then
1524              raise (TypeCheckerFailure 
1525                      (lazy (sprintf "Not well typed metavariable local context: expected a term of type %s, found %s of type %s" 
1526                          (CicPp.ppterm ct) (CicPp.ppterm t)
1527                          (CicPp.ppterm type_t))))
1528            else
1529              ugraph2
1530        | None, _  ->
1531            raise (TypeCheckerFailure
1532                    (lazy ("Not well typed metavariable local context: "^
1533                      "an hypothesis, that is not hidden, is not instantiated")))
1534      ) ugraph l lifted_canonical_context 
1535      
1536
1537 (* 
1538    type_of_aux' is just another name (with a different scope) 
1539    for type_of_aux 
1540 *)
1541
1542 and type_of_aux' ~logger ?(subst = []) metasenv context t ugraph =
1543  let rec type_of_aux ~logger context t ugraph =
1544   let module C = Cic in
1545   let module R = CicReduction in
1546   let module S = CicSubstitution in
1547   let module U = UriManager in
1548    match t with
1549       C.Rel n ->
1550        (try
1551          match List.nth context (n - 1) with
1552             Some (_,C.Decl t) -> S.lift n t,ugraph
1553           | Some (_,C.Def (_,Some ty)) -> S.lift n ty,ugraph
1554           | Some (_,C.Def (bo,None)) ->
1555              debug_print (lazy "##### CASO DA INVESTIGARE E CAPIRE") ;
1556               type_of_aux ~logger context (S.lift n bo) ugraph
1557           | None -> raise 
1558               (TypeCheckerFailure (lazy "Reference to deleted hypothesis"))
1559         with
1560         Failure _ ->
1561           raise (TypeCheckerFailure (lazy "unbound variable"))
1562        )
1563     | C.Var (uri,exp_named_subst) ->
1564       incr fdebug ;
1565         let ugraph1 = 
1566           check_exp_named_subst ~logger ~subst context exp_named_subst ugraph 
1567         in 
1568         let ty,ugraph2 = type_of_variable ~logger uri ugraph1 in
1569         let ty1 = CicSubstitution.subst_vars exp_named_subst ty in
1570           decr fdebug ;
1571           ty1,ugraph2
1572     | C.Meta (n,l) -> 
1573        (try
1574           let (canonical_context,term,ty) = CicUtil.lookup_subst n subst in
1575           let ugraph1 =
1576             check_metasenv_consistency ~logger
1577               ~subst metasenv context canonical_context l ugraph
1578           in
1579             (* assuming subst is well typed !!!!! *)
1580             ((CicSubstitution.subst_meta l ty), ugraph1)
1581               (* type_of_aux context (CicSubstitution.subst_meta l term) *)
1582         with CicUtil.Subst_not_found _ ->
1583           let (_,canonical_context,ty) = CicUtil.lookup_meta n metasenv in
1584           let ugraph1 = 
1585             check_metasenv_consistency ~logger
1586               ~subst metasenv context canonical_context l ugraph
1587           in
1588             ((CicSubstitution.subst_meta l ty),ugraph1))
1589       (* TASSI: CONSTRAINTS *)
1590     | C.Sort (C.Type t) -> 
1591        let t' = CicUniv.fresh() in
1592        (try
1593          let ugraph1 = CicUniv.add_gt t' t ugraph in
1594            (C.Sort (C.Type t')),ugraph1
1595         with
1596          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1597     | C.Sort s -> (C.Sort (C.Type (CicUniv.fresh ()))),ugraph
1598     | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
1599     | C.Cast (te,ty) as t ->
1600        let _,ugraph1 = type_of_aux ~logger context ty ugraph in
1601        let ty_te,ugraph2 = type_of_aux ~logger context te ugraph1 in
1602        let b,ugraph3 = 
1603          R.are_convertible ~subst ~metasenv context ty_te ty ugraph2 
1604        in
1605          if b then
1606            ty,ugraph3
1607          else
1608            raise (TypeCheckerFailure
1609                     (lazy (sprintf "Invalid cast %s" (CicPp.ppterm t))))
1610     | C.Prod (name,s,t) ->
1611        let sort1,ugraph1 = type_of_aux ~logger context s ugraph in
1612        let sort2,ugraph2 = 
1613          type_of_aux ~logger  ((Some (name,(C.Decl s)))::context) t ugraph1 
1614        in
1615        sort_of_prod ~subst context (name,s) (sort1,sort2) ugraph2
1616    | C.Lambda (n,s,t) ->
1617        let sort1,ugraph1 = type_of_aux ~logger context s ugraph in
1618        (match R.whd ~subst context sort1 with
1619            C.Meta _
1620          | C.Sort _ -> ()
1621          | _ ->
1622            raise
1623             (TypeCheckerFailure (lazy (sprintf
1624               "Not well-typed lambda-abstraction: the source %s should be a type; instead it is a term of type %s" (CicPp.ppterm s)
1625                 (CicPp.ppterm sort1))))
1626        ) ;
1627        let type2,ugraph2 = 
1628          type_of_aux ~logger ((Some (n,(C.Decl s)))::context) t ugraph1 
1629        in
1630          (C.Prod (n,s,type2)),ugraph2
1631    | C.LetIn (n,s,t) ->
1632       (* only to check if s is well-typed *)
1633       let ty,ugraph1 = type_of_aux ~logger context s ugraph in
1634        (* The type of a LetIn is a LetIn. Extremely slow since the computed
1635           LetIn is later reduced and maybe also re-checked.
1636        (C.LetIn (n,s, type_of_aux ((Some (n,(C.Def s)))::context) t))
1637        *)
1638        (* The type of the LetIn is reduced. Much faster than the previous
1639           solution. Moreover the inferred type is probably very different
1640           from the expected one.
1641        (CicReduction.whd ~subst context
1642         (C.LetIn (n,s, type_of_aux ((Some (n,(C.Def s)))::context) t)))
1643        *)
1644        (* One-step LetIn reduction. Even faster than the previous solution.
1645           Moreover the inferred type is closer to the expected one. *)
1646        let ty1,ugraph2 = 
1647          type_of_aux ~logger 
1648            ((Some (n,(C.Def (s,Some ty))))::context) t ugraph1 
1649        in
1650        (CicSubstitution.subst ~avoid_beta_redexes:true s ty1),ugraph2
1651    | C.Appl (he::tl) when List.length tl > 0 ->
1652        let hetype,ugraph1 = type_of_aux ~logger context he ugraph in
1653        let tlbody_and_type,ugraph2 = 
1654          List.fold_right (
1655            fun x (l,ugraph) -> 
1656              let ty,ugraph1 = type_of_aux ~logger context x ugraph in
1657              let _,ugraph1 = type_of_aux ~logger  context ty ugraph1 in
1658                ((x,ty)::l,ugraph1)) 
1659            tl ([],ugraph1) 
1660        in
1661          (* TASSI: questa c'era nel mio... ma non nel CVS... *)
1662          (* let _,ugraph2 = type_of_aux context hetype ugraph2 in *)
1663          eat_prods ~subst context hetype tlbody_and_type ugraph2
1664    | C.Appl _ -> raise (AssertFailure (lazy "Appl: no arguments"))
1665    | C.Const (uri,exp_named_subst) ->
1666        incr fdebug ;
1667        let ugraph1 = 
1668          check_exp_named_subst ~logger ~subst  context exp_named_subst ugraph 
1669        in
1670        let cty,ugraph2 = type_of_constant ~logger uri ugraph1 in
1671        let cty1 =
1672          CicSubstitution.subst_vars exp_named_subst cty
1673        in
1674          decr fdebug ;
1675          cty1,ugraph2
1676    | C.MutInd (uri,i,exp_named_subst) ->
1677       incr fdebug ;
1678        let ugraph1 = 
1679          check_exp_named_subst ~logger  ~subst context exp_named_subst ugraph 
1680        in
1681          (* TASSI: da me c'era anche questa, ma in CVS no *)
1682        let mty,ugraph2 = type_of_mutual_inductive_defs ~logger uri i ugraph1 in
1683          (* fine parte dubbia *)
1684        let cty =
1685          CicSubstitution.subst_vars exp_named_subst mty
1686        in
1687          decr fdebug ;
1688          cty,ugraph2
1689    | C.MutConstruct (uri,i,j,exp_named_subst) ->
1690        let ugraph1 = 
1691          check_exp_named_subst ~logger ~subst context exp_named_subst ugraph 
1692        in
1693          (* TASSI: idem come sopra *)
1694        let mty,ugraph2 = 
1695          type_of_mutual_inductive_constr ~logger uri i j ugraph1 
1696        in
1697        let cty =
1698          CicSubstitution.subst_vars exp_named_subst mty
1699        in
1700          cty,ugraph2
1701    | C.MutCase (uri,i,outtype,term,pl) ->
1702       let outsort,ugraph1 = type_of_aux ~logger context outtype ugraph in
1703       let (need_dummy, k) =
1704       let rec guess_args context t =
1705         let outtype = CicReduction.whd ~subst context t in
1706           match outtype with
1707               C.Sort _ -> (true, 0)
1708             | C.Prod (name, s, t) ->
1709                 let (b, n) = 
1710                   guess_args ((Some (name,(C.Decl s)))::context) t in
1711                   if n = 0 then
1712                   (* last prod before sort *)
1713                     match CicReduction.whd ~subst context s with
1714 (*CSC: for _ see comment below about the missing named_exp_subst ?????????? *)
1715                         C.MutInd (uri',i',_) when U.eq uri' uri && i' = i ->
1716                           (false, 1)
1717 (*CSC: for _ see comment below about the missing named_exp_subst ?????????? *)
1718                       | C.Appl ((C.MutInd (uri',i',_)) :: _)
1719                           when U.eq uri' uri && i' = i -> (false, 1)
1720                       | _ -> (true, 1)
1721                   else
1722                     (b, n + 1)
1723             | _ ->
1724                 raise 
1725                   (TypeCheckerFailure 
1726                      (lazy (sprintf
1727                         "Malformed case analasys' output type %s" 
1728                         (CicPp.ppterm outtype))))
1729       in
1730 (*
1731       let (parameters, arguments, exp_named_subst),ugraph2 =
1732         let ty,ugraph2 = type_of_aux context term ugraph1 in
1733           match R.whd ~subst context ty with
1734            (*CSC manca il caso dei CAST *)
1735 (*CSC: ma servono i parametri (uri,i)? Se si', perche' non serve anche il *)
1736 (*CSC: parametro exp_named_subst? Se no, perche' non li togliamo?         *)
1737 (*CSC: Hint: nella DTD servono per gli stylesheet.                        *)
1738               C.MutInd (uri',i',exp_named_subst) as typ ->
1739                 if U.eq uri uri' && i = i' then 
1740                   ([],[],exp_named_subst),ugraph2
1741                 else 
1742                   raise 
1743                     (TypeCheckerFailure 
1744                       (lazy (sprintf
1745                           ("Case analysys: analysed term type is %s, but is expected to be (an application of) %s#1/%d{_}")
1746                           (CicPp.ppterm typ) (U.string_of_uri uri) i)))
1747             | C.Appl 
1748                 ((C.MutInd (uri',i',exp_named_subst) as typ):: tl) as typ' ->
1749                 if U.eq uri uri' && i = i' then
1750                   let params,args =
1751                     split tl (List.length tl - k)
1752                   in (params,args,exp_named_subst),ugraph2
1753                 else 
1754                   raise 
1755                     (TypeCheckerFailure 
1756                       (lazy (sprintf 
1757                           ("Case analysys: analysed term type is %s, "^
1758                            "but is expected to be (an application of) "^
1759                            "%s#1/%d{_}")
1760                           (CicPp.ppterm typ') (U.string_of_uri uri) i)))
1761             | _ ->
1762                 raise 
1763                   (TypeCheckerFailure 
1764                     (lazy (sprintf
1765                         ("Case analysis: "^
1766                          "analysed term %s is not an inductive one")
1767                         (CicPp.ppterm term))))
1768 *)
1769       let (b, k) = guess_args context outsort in
1770           if not b then (b, k - 1) else (b, k) in
1771       let (parameters, arguments, exp_named_subst),ugraph2 =
1772         let ty,ugraph2 = type_of_aux ~logger context term ugraph1 in
1773         match R.whd ~subst context ty with
1774             C.MutInd (uri',i',exp_named_subst) as typ ->
1775               if U.eq uri uri' && i = i' then 
1776                 ([],[],exp_named_subst),ugraph2
1777               else raise 
1778                 (TypeCheckerFailure 
1779                   (lazy (sprintf
1780                       ("Case analysys: analysed term type is %s (%s#1/%d{_}), but is expected to be (an application of) %s#1/%d{_}")
1781                       (CicPp.ppterm typ) (U.string_of_uri uri') i' (U.string_of_uri uri) i)))
1782           | C.Appl ((C.MutInd (uri',i',exp_named_subst) as typ):: tl) ->
1783               if U.eq uri uri' && i = i' then
1784                 let params,args =
1785                   split tl (List.length tl - k)
1786                 in (params,args,exp_named_subst),ugraph2
1787               else raise 
1788                 (TypeCheckerFailure 
1789                   (lazy (sprintf
1790                       ("Case analysys: analysed term type is %s (%s#1/%d{_}), but is expected to be (an application of) %s#1/%d{_}")
1791                       (CicPp.ppterm typ) (U.string_of_uri uri') i' (U.string_of_uri uri) i)))
1792           | _ ->
1793               raise 
1794                 (TypeCheckerFailure 
1795                   (lazy (sprintf
1796                       "Case analysis: analysed term %s is not an inductive one"
1797                       (CicPp.ppterm term))))
1798       in
1799         (* 
1800            let's control if the sort elimination is allowed: 
1801            [(I q1 ... qr)|B] 
1802         *)
1803       let sort_of_ind_type =
1804         if parameters = [] then
1805           C.MutInd (uri,i,exp_named_subst)
1806         else
1807           C.Appl ((C.MutInd (uri,i,exp_named_subst))::parameters)
1808       in
1809       let type_of_sort_of_ind_ty,ugraph3 = 
1810         type_of_aux ~logger context sort_of_ind_type ugraph2 in
1811       let b,ugraph4 = 
1812         check_allowed_sort_elimination ~subst ~metasenv ~logger  context uri i
1813           need_dummy sort_of_ind_type type_of_sort_of_ind_ty outsort ugraph3 
1814       in
1815         if not b then
1816         raise
1817           (TypeCheckerFailure (lazy ("Case analysis: sort elimination not allowed")));
1818         (* let's check if the type of branches are right *)
1819       let parsno,constructorsno =
1820         let obj,_ =
1821           try
1822             CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
1823           with Not_found -> assert false
1824         in
1825         match obj with
1826             C.InductiveDefinition (il,_,parsno,_) ->
1827              let _,_,_,cl =
1828               try List.nth il i with Failure _ -> assert false
1829              in
1830               parsno, List.length cl
1831           | _ ->
1832               raise (TypeCheckerFailure
1833                 (lazy ("Unknown mutual inductive definition:" ^
1834                   UriManager.string_of_uri uri)))
1835       in
1836       if List.length pl <> constructorsno then
1837        raise (TypeCheckerFailure
1838         (lazy ("Wrong number of cases in case analysis"))) ;
1839       let (_,branches_ok,ugraph5) =
1840         List.fold_left
1841           (fun (j,b,ugraph) p ->
1842             if b then
1843               let cons =
1844                 if parameters = [] then
1845                   (C.MutConstruct (uri,i,j,exp_named_subst))
1846                 else
1847                   (C.Appl 
1848                      (C.MutConstruct (uri,i,j,exp_named_subst)::parameters))
1849               in
1850               let ty_p,ugraph1 = type_of_aux ~logger context p ugraph in
1851               let ty_cons,ugraph3 = type_of_aux ~logger context cons ugraph1 in
1852               (* 2 is skipped *)
1853               let ty_branch = 
1854                 type_of_branch ~subst context parsno need_dummy outtype cons 
1855                   ty_cons in
1856               let b1,ugraph4 =
1857                 R.are_convertible 
1858                   ~subst ~metasenv context ty_p ty_branch ugraph3 
1859               in 
1860 (* Debugging code
1861 if not b1 then
1862 begin
1863 prerr_endline ("\n!OUTTYPE= " ^ CicPp.ppterm outtype);
1864 prerr_endline ("!CONS= " ^ CicPp.ppterm cons);
1865 prerr_endline ("!TY_CONS= " ^ CicPp.ppterm ty_cons);
1866 prerr_endline ("#### " ^ CicPp.ppterm ty_p ^ "\n<==>\n" ^ CicPp.ppterm ty_branch);
1867 end;
1868 *)
1869               if not b1 then
1870                 debug_print (lazy
1871                   ("#### " ^ CicPp.ppterm ty_p ^ 
1872                   " <==> " ^ CicPp.ppterm ty_branch));
1873               (j + 1,b1,ugraph4)
1874             else
1875               (j,false,ugraph)
1876           ) (1,true,ugraph4) pl
1877          in
1878           if not branches_ok then
1879            raise
1880             (TypeCheckerFailure (lazy "Case analysys: wrong branch type"));
1881           let arguments' =
1882            if not need_dummy then outtype::arguments@[term]
1883            else outtype::arguments in
1884           let outtype =
1885            if need_dummy && arguments = [] then outtype
1886            else CicReduction.head_beta_reduce (C.Appl arguments')
1887           in
1888            outtype,ugraph5
1889    | C.Fix (i,fl) ->
1890       let types,kl,ugraph1,len =
1891         List.fold_left
1892           (fun (types,kl,ugraph,len) (n,k,ty,_) ->
1893             let _,ugraph1 = type_of_aux ~logger context ty ugraph in
1894              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1895               k::kl,ugraph1,len+1)
1896           ) ([],[],ugraph,0) fl
1897       in
1898       let ugraph2 = 
1899         List.fold_left
1900           (fun ugraph (name,x,ty,bo) ->
1901              let ty_bo,ugraph1 = 
1902                type_of_aux ~logger (types@context) bo ugraph 
1903              in
1904              let b,ugraph2 = 
1905                R.are_convertible ~subst ~metasenv (types@context) 
1906                  ty_bo (CicSubstitution.lift len ty) ugraph1 in
1907                if b then
1908                  begin
1909                    let (m, eaten, context') =
1910                      eat_lambdas ~subst (types @ context) (x + 1) bo
1911                    in
1912                      (*
1913                        let's control the guarded by 
1914                        destructors conditions D{f,k,x,M}
1915                      *)
1916                      if not (guarded_by_destructors ~subst context' eaten 
1917                                (len + eaten) kl 1 [] m) then
1918                        raise
1919                          (TypeCheckerFailure 
1920                            (lazy ("Fix: not guarded by destructors")))
1921                      else
1922                        ugraph2
1923                  end
1924                else
1925                  raise (TypeCheckerFailure (lazy ("Fix: ill-typed bodies")))
1926           ) ugraph1 fl in
1927         (*CSC: controlli mancanti solo su D{f,k,x,M} *)
1928       let (_,_,ty,_) = List.nth fl i in
1929         ty,ugraph2
1930    | C.CoFix (i,fl) ->
1931        let types,ugraph1,len =
1932          List.fold_left
1933            (fun (l,ugraph,len) (n,ty,_) -> 
1934               let _,ugraph1 = 
1935                 type_of_aux ~logger context ty ugraph in 
1936                 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::l,
1937                  ugraph1,len+1)
1938            ) ([],ugraph,0) fl
1939        in
1940        let ugraph2 = 
1941          List.fold_left
1942            (fun ugraph (_,ty,bo) ->
1943               let ty_bo,ugraph1 = 
1944                 type_of_aux ~logger (types @ context) bo ugraph 
1945               in
1946               let b,ugraph2 = 
1947                 R.are_convertible ~subst ~metasenv (types @ context) ty_bo
1948                   (CicSubstitution.lift len ty) ugraph1 
1949               in
1950                 if b then
1951                   begin
1952                     (* let's control that the returned type is coinductive *)
1953                     match returns_a_coinductive ~subst context ty with
1954                         None ->
1955                           raise
1956                           (TypeCheckerFailure
1957                             (lazy "CoFix: does not return a coinductive type"))
1958                       | Some uri ->
1959                           (*
1960                             let's control the guarded by constructors 
1961                             conditions C{f,M}
1962                           *)
1963                           if not (guarded_by_constructors ~subst
1964                               (types @ context) 0 len false bo [] uri) then
1965                             raise
1966                               (TypeCheckerFailure 
1967                                 (lazy "CoFix: not guarded by constructors"))
1968                           else
1969                           ugraph2
1970                   end
1971                 else
1972                   raise
1973                     (TypeCheckerFailure (lazy "CoFix: ill-typed bodies"))
1974            ) ugraph1 fl 
1975        in
1976        let (_,ty,_) = List.nth fl i in
1977          ty,ugraph2
1978
1979  and check_exp_named_subst ~logger ~subst context ugraph =
1980    let rec check_exp_named_subst_aux ~logger esubsts l ugraph =
1981      match l with
1982          [] -> ugraph
1983        | ((uri,t) as item)::tl ->
1984            let ty_uri,ugraph1 = type_of_variable ~logger uri ugraph in 
1985            let typeofvar =
1986              CicSubstitution.subst_vars esubsts ty_uri in
1987            let typeoft,ugraph2 = type_of_aux ~logger context t ugraph1 in
1988            let b,ugraph3 =
1989              CicReduction.are_convertible ~subst ~metasenv
1990                context typeoft typeofvar ugraph2 
1991            in
1992              if b then
1993                check_exp_named_subst_aux ~logger (esubsts@[item]) tl ugraph3
1994              else
1995                begin
1996                  CicReduction.fdebug := 0 ;
1997                  ignore 
1998                    (CicReduction.are_convertible 
1999                       ~subst ~metasenv context typeoft typeofvar ugraph2) ;
2000                  fdebug := 0 ;
2001                  debug typeoft [typeofvar] ;
2002                  raise (TypeCheckerFailure (lazy "Wrong Explicit Named Substitution"))
2003                end
2004    in
2005      check_exp_named_subst_aux ~logger [] ugraph 
2006        
2007  and sort_of_prod ~subst context (name,s) (t1, t2) ugraph =
2008   let module C = Cic in
2009    let t1' = CicReduction.whd ~subst context t1 in
2010    let t2' = CicReduction.whd ~subst ((Some (name,C.Decl s))::context) t2 in
2011    match (t1', t2') with
2012       (C.Sort s1, C.Sort s2)
2013         when (s2 = C.Prop or s2 = C.Set or s2 = C.CProp) -> 
2014          (* different from Coq manual!!! *)
2015          C.Sort s2,ugraph
2016     | (C.Sort (C.Type t1), C.Sort (C.Type t2)) -> 
2017       (* TASSI: CONSRTAINTS: the same in doubletypeinference, cicrefine *)
2018        let t' = CicUniv.fresh() in
2019         (try
2020          let ugraph1 = CicUniv.add_ge t' t1 ugraph in
2021          let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
2022           C.Sort (C.Type t'),ugraph2
2023         with
2024          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
2025     | (C.Sort _,C.Sort (C.Type t1)) -> 
2026         (* TASSI: CONSRTAINTS: the same in doubletypeinference, cicrefine *)
2027         C.Sort (C.Type t1),ugraph (* c'e' bisogno di un fresh? *)
2028     | (C.Meta _, C.Sort _) -> t2',ugraph
2029     | (C.Meta _, (C.Meta (_,_) as t))
2030     | (C.Sort _, (C.Meta (_,_) as t)) when CicUtil.is_closed t ->
2031         t2',ugraph
2032     | (_,_) -> raise (TypeCheckerFailure (lazy (sprintf
2033         "Prod: expected two sorts, found = %s, %s" (CicPp.ppterm t1')
2034           (CicPp.ppterm t2'))))
2035
2036  and eat_prods ~subst context hetype l ugraph =
2037    (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
2038    (*CSC: cucinati                                                         *)
2039    match l with
2040        [] -> hetype,ugraph
2041      | (hete, hety)::tl ->
2042          (match (CicReduction.whd ~subst context hetype) with 
2043               Cic.Prod (n,s,t) ->
2044                 let b,ugraph1 = 
2045                   CicReduction.are_convertible 
2046                     ~subst ~metasenv context hety s ugraph 
2047                 in      
2048                   if b then
2049                     begin
2050                       CicReduction.fdebug := -1 ;
2051                       eat_prods ~subst context 
2052                         (CicSubstitution.subst ~avoid_beta_redexes:true hete t)
2053                          tl ugraph1
2054                         (*TASSI: not sure *)
2055                     end
2056                   else
2057                     begin
2058                       CicReduction.fdebug := 0 ;
2059                       ignore (CicReduction.are_convertible 
2060                                 ~subst ~metasenv context s hety ugraph) ;
2061                       fdebug := 0 ;
2062                       debug s [hety] ;
2063                       raise 
2064                         (TypeCheckerFailure 
2065                           (lazy (sprintf
2066                               ("Appl: wrong parameter-type, expected %s, found %s")
2067                               (CicPp.ppterm hetype) (CicPp.ppterm s))))
2068                     end
2069             | _ ->
2070                 raise (TypeCheckerFailure
2071                         (lazy "Appl: this is not a function, it cannot be applied"))
2072          )
2073
2074  and returns_a_coinductive ~subst context ty =
2075   let module C = Cic in
2076    match CicReduction.whd ~subst context ty with
2077       C.MutInd (uri,i,_) ->
2078        (*CSC: definire una funzioncina per questo codice sempre replicato *)
2079         let obj,_ =
2080           try
2081             CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
2082           with Not_found -> assert false
2083         in
2084         (match obj with
2085            C.InductiveDefinition (itl,_,_,_) ->
2086             let (_,is_inductive,_,_) = List.nth itl i in
2087              if is_inductive then None else (Some uri)
2088          | _ ->
2089             raise (TypeCheckerFailure
2090               (lazy ("Unknown mutual inductive definition:" ^
2091               UriManager.string_of_uri uri)))
2092         )
2093     | C.Appl ((C.MutInd (uri,i,_))::_) ->
2094        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
2095          match o with
2096            C.InductiveDefinition (itl,_,_,_) ->
2097             let (_,is_inductive,_,_) = List.nth itl i in
2098              if is_inductive then None else (Some uri)
2099          | _ ->
2100             raise (TypeCheckerFailure
2101               (lazy ("Unknown mutual inductive definition:" ^
2102               UriManager.string_of_uri uri)))
2103         )
2104     | C.Prod (n,so,de) ->
2105        returns_a_coinductive ~subst ((Some (n,C.Decl so))::context) de
2106     | _ -> None
2107
2108  in
2109 (*CSC
2110 debug_print (lazy ("INIZIO TYPE_OF_AUX " ^ CicPp.ppterm t)) ; flush stderr ;
2111 let res =
2112 *)
2113   type_of_aux ~logger context t ugraph
2114 (*
2115 in debug_print (lazy "FINE TYPE_OF_AUX") ; flush stderr ; res
2116 *)
2117
2118 (* is a small constructor? *)
2119 (*CSC: ottimizzare calcolando staticamente *)
2120 and is_small_or_non_informative ~condition ~logger context paramsno c ugraph =
2121  let rec is_small_or_non_informative_aux ~logger context c ugraph =
2122   let module C = Cic in
2123    match CicReduction.whd context c with
2124       C.Prod (n,so,de) ->
2125        let s,ugraph1 = type_of_aux' ~logger [] context so ugraph in
2126        let b = condition s in
2127        if b then
2128          is_small_or_non_informative_aux
2129           ~logger ((Some (n,(C.Decl so)))::context) de ugraph1
2130        else 
2131          false,ugraph1
2132     | _ -> true,ugraph (*CSC: we trust the type-checker *)
2133  in
2134   let (context',dx) = split_prods ~subst:[] context paramsno c in
2135    is_small_or_non_informative_aux ~logger context' dx ugraph
2136
2137 and is_small ~logger =
2138  is_small_or_non_informative
2139   ~condition:(fun s -> s=Cic.Sort Cic.Prop || s=Cic.Sort Cic.Set)
2140   ~logger
2141
2142 and is_non_informative ~logger =
2143  is_small_or_non_informative
2144   ~condition:(fun s -> s=Cic.Sort Cic.Prop)
2145   ~logger
2146
2147 and type_of ~logger t ugraph =
2148 (*CSC
2149 debug_print (lazy ("INIZIO TYPE_OF_AUX' " ^ CicPp.ppterm t)) ; flush stderr ;
2150 let res =
2151 *)
2152  type_of_aux' ~logger [] [] t ugraph 
2153 (*CSC
2154 in debug_print (lazy "FINE TYPE_OF_AUX'") ; flush stderr ; res
2155 *)
2156 ;;
2157
2158 let typecheck_obj0 ~logger uri ugraph =
2159  let module C = Cic in
2160   function
2161      C.Constant (_,Some te,ty,_,_) ->
2162       let _,ugraph = type_of ~logger ty ugraph in
2163       let ty_te,ugraph = type_of ~logger te ugraph in
2164       let b,ugraph = (CicReduction.are_convertible [] ty_te ty ugraph) in
2165        if not b then
2166          raise (TypeCheckerFailure
2167           (lazy
2168             ("the type of the body is not the one expected:\n" ^
2169              CicPp.ppterm ty_te ^ "\nvs\n" ^
2170              CicPp.ppterm ty)))
2171        else
2172         ugraph
2173    | C.Constant (_,None,ty,_,_) ->
2174       (* only to check that ty is well-typed *)
2175       let _,ugraph = type_of ~logger ty ugraph in
2176        ugraph
2177    | C.CurrentProof (_,conjs,te,ty,_,_) ->
2178       let _,ugraph =
2179        List.fold_left
2180         (fun (metasenv,ugraph) ((_,context,ty) as conj) ->
2181           let _,ugraph = 
2182            type_of_aux' ~logger metasenv context ty ugraph 
2183           in
2184            metasenv @ [conj],ugraph
2185         ) ([],ugraph) conjs
2186       in
2187        let _,ugraph = type_of_aux' ~logger conjs [] ty ugraph in
2188        let type_of_te,ugraph = 
2189         type_of_aux' ~logger conjs [] te ugraph
2190        in
2191        let b,ugraph = CicReduction.are_convertible [] type_of_te ty ugraph in
2192         if not b then
2193           raise (TypeCheckerFailure (lazy (sprintf
2194            "the current proof is not well typed because the type %s of the body is not convertible to the declared type %s"
2195            (CicPp.ppterm type_of_te) (CicPp.ppterm ty))))
2196         else
2197          ugraph
2198    | C.Variable (_,bo,ty,_,_) ->
2199       (* only to check that ty is well-typed *)
2200       let _,ugraph = type_of ~logger ty ugraph in
2201        (match bo with
2202            None -> ugraph
2203          | Some bo ->
2204             let ty_bo,ugraph = type_of ~logger bo ugraph in
2205             let b,ugraph = CicReduction.are_convertible [] ty_bo ty ugraph in
2206              if not b then
2207               raise (TypeCheckerFailure
2208                (lazy "the body is not the one expected"))
2209              else
2210               ugraph
2211             )
2212    | (C.InductiveDefinition _ as obj) ->
2213       check_mutual_inductive_defs ~logger uri obj ugraph
2214
2215 let typecheck uri =
2216  let module C = Cic in
2217  let module R = CicReduction in
2218  let module U = UriManager in
2219  let logger = new CicLogger.logger in
2220    (* ??? match CicEnvironment.is_type_checked ~trust:true uri with ???? *)
2221    match CicEnvironment.is_type_checked ~trust:false CicUniv.empty_ugraph uri with
2222      CicEnvironment.CheckedObj (cobj,ugraph') -> 
2223        (* debug_print (lazy ("NON-INIZIO A TYPECHECKARE " ^ U.string_of_uri uri));*)
2224        cobj,ugraph'
2225    | CicEnvironment.UncheckedObj uobj ->
2226       (* let's typecheck the uncooked object *)
2227       logger#log (`Start_type_checking uri) ;
2228       (* debug_print (lazy ("INIZIO A TYPECHECKARE " ^ U.string_of_uri uri)); *)
2229       let ugraph = typecheck_obj0 ~logger uri CicUniv.empty_ugraph uobj in
2230         try
2231           CicEnvironment.set_type_checking_info uri;
2232           logger#log (`Type_checking_completed uri);
2233           match CicEnvironment.is_type_checked ~trust:false ugraph uri with
2234               CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
2235             | _ -> raise CicEnvironmentError
2236         with
2237             (*
2238               this is raised if set_type_checking_info is called on an object
2239               that has no associated universe file. If we are in univ_maker 
2240               phase this is OK since univ_maker will properly commit the 
2241               object.
2242             *)
2243             Invalid_argument s -> 
2244               (*debug_print (lazy s);*)
2245               uobj,ugraph
2246 ;;
2247
2248 let typecheck_obj ~logger uri obj =
2249  let ugraph = typecheck_obj0 ~logger uri CicUniv.empty_ugraph obj in
2250  let ugraph, univlist, obj = CicUnivUtils.clean_and_fill uri obj ugraph in
2251   CicEnvironment.add_type_checked_obj uri (obj,ugraph,univlist)
2252
2253 (** wrappers which instantiate fresh loggers *)
2254
2255 let profiler = HExtlib.profile "K/CicTypeChecker.type_of_aux'"
2256
2257 let type_of_aux' ?(subst = []) metasenv context t ugraph =
2258   let logger = new CicLogger.logger in
2259   profiler.HExtlib.profile 
2260     (type_of_aux' ~logger ~subst metasenv context t) ugraph
2261
2262 let typecheck_obj uri obj =
2263  let logger = new CicLogger.logger in
2264  typecheck_obj ~logger uri obj
2265
2266 (* check_allowed_sort_elimination uri i s1 s2
2267    This function is used outside the kernel to determine in advance whether
2268    a MutCase will be allowed or not.
2269    [uri,i] is the type of the term to match
2270    [s1] is the sort of the term to eliminate (i.e. the head of the arity
2271         of the inductive type [uri,i])
2272    [s2] is the sort of the goal (i.e. the head of the type of the outtype
2273         of the MutCase) *)
2274 let check_allowed_sort_elimination uri i s1 s2 =
2275  fst (check_allowed_sort_elimination ~subst:[] ~metasenv:[]
2276   ~logger:(new CicLogger.logger) [] uri i true
2277   (Cic.Implicit None) (* never used *) (Cic.Sort s1) (Cic.Sort s2)
2278   CicUniv.empty_ugraph)