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