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