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