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