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