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