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