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