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