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