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