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