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