]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_proof_checking/cicTypeChecker.ml
cf3a3c49caec3c2d427ac35dfd3d6c845257f6ba
[helm.git] / helm / software / components / cic_proof_checking / cicTypeChecker.ml
1 (* Copyright (C) 2000, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 (* TODO factorize functions to frequent errors (e.g. "Unknwon mutual inductive
29  * ...") *)
30
31 open Printf
32
33 exception AssertFailure of string Lazy.t;;
34 exception TypeCheckerFailure of string Lazy.t;;
35
36 let fdebug = ref 0;;
37 let debug t context =
38  let rec debug_aux t i =
39   let module C = Cic in
40   let module U = UriManager in
41    CicPp.ppobj (C.Variable ("DEBUG", None, t, [], [])) ^ "\n" ^ i
42  in
43   if !fdebug = 0 then
44    raise (TypeCheckerFailure (lazy (List.fold_right debug_aux (t::context) "")))
45 ;;
46
47 let debug_print = fun _ -> ();;
48
49 let rec split l n =
50  match (l,n) with
51     (l,0) -> ([], l)
52   | (he::tl, n) -> let (l1,l2) = split tl (n-1) in (he::l1,l2)
53   | (_,_) ->
54       raise (TypeCheckerFailure (lazy "Parameters number < left parameters number"))
55 ;;
56
57 (* XXX: bug *)
58 let ugraph_convertibility ug1 ug2 ul2 = true;;
59
60 let check_and_clean_ugraph inferred_ugraph unchecked_ugraph uri obj =
61  match unchecked_ugraph with
62  | Some (ug,ul) ->
63      if not (ugraph_convertibility inferred_ugraph ug ul) then
64        raise (TypeCheckerFailure (lazy 
65          ("inferred univ graph not equal with declared ugraph")))
66      else 
67       ug,ul,obj
68  | None -> 
69      CicUnivUtils.clean_and_fill uri obj inferred_ugraph 
70 ;;
71
72 let debrujin_constructor ?(cb=fun _ _ -> ()) ?(check_exp_named_subst=true) uri number_of_types context =
73  let rec aux k t =
74   let module C = Cic in
75   let res =
76    match t with
77       C.Rel n as t when n <= k -> t
78     | C.Rel _ ->
79         raise (TypeCheckerFailure (lazy "unbound variable found in constructor type"))
80     | C.Var (uri,exp_named_subst) ->
81        let exp_named_subst' = 
82         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
83        in
84         C.Var (uri,exp_named_subst')
85     | C.Meta (i,l) ->
86        let l' = List.map (function None -> None | Some t -> Some (aux k t)) l in
87         C.Meta (i,l')
88     | C.Sort _
89     | C.Implicit _ as t -> t
90     | C.Cast (te,ty) -> C.Cast (aux k te, aux k ty)
91     | C.Prod (n,s,t) -> C.Prod (n, aux k s, aux (k+1) t)
92     | C.Lambda (n,s,t) -> C.Lambda (n, aux k s, aux (k+1) t)
93     | C.LetIn (n,s,ty,t) -> C.LetIn (n, aux k s, aux k ty, aux (k+1) t)
94     | C.Appl l -> C.Appl (List.map (aux k) l)
95     | C.Const (uri,exp_named_subst) ->
96        let exp_named_subst' = 
97         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
98        in
99         C.Const (uri,exp_named_subst')
100     | C.MutInd (uri',tyno,exp_named_subst) when UriManager.eq uri uri' ->
101        if check_exp_named_subst && exp_named_subst != [] then
102         raise (TypeCheckerFailure
103           (lazy ("non-empty explicit named substitution is applied to "^
104            "a mutual inductive type which is being defined"))) ;
105        C.Rel (k + number_of_types - tyno) ;
106     | C.MutInd (uri',tyno,exp_named_subst) ->
107        let exp_named_subst' = 
108         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
109        in
110         C.MutInd (uri',tyno,exp_named_subst')
111     | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
112        let exp_named_subst' = 
113         List.map (function (uri,t) -> (uri,aux k t)) exp_named_subst
114        in
115         C.MutConstruct (uri,tyno,consno,exp_named_subst')
116     | C.MutCase (sp,i,outty,t,pl) ->
117        C.MutCase (sp, i, aux k outty, aux k t,
118         List.map (aux k) pl)
119     | C.Fix (i, fl) ->
120        let len = List.length fl in
121        let liftedfl =
122         List.map
123          (fun (name, i, ty, bo) -> (name, i, aux k ty, aux (k+len) bo))
124           fl
125        in
126         C.Fix (i, liftedfl)
127     | C.CoFix (i, fl) ->
128        let len = List.length fl in
129        let liftedfl =
130         List.map
131          (fun (name, ty, bo) -> (name, aux k ty, aux (k+len) bo))
132           fl
133        in
134         C.CoFix (i, liftedfl)
135   in
136    cb t res;
137    res
138  in
139   aux (List.length context)
140 ;;
141
142 exception CicEnvironmentError;;
143
144 let 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                 | Cic.Sort (Cic.CProp u1), Cic.Sort (Cic.CProp u2) 
577                 | Cic.Sort (Cic.Type u1), Cic.Sort (Cic.CProp u2) ->
578                    CicUniv.add_ge u2 u1 ugraph
579                 | Cic.Sort (Cic.CProp u1), Cic.Sort (Cic.Type u2) ->
580                    CicUniv.add_gt u2 u1 ugraph
581                 | Cic.Sort _, Cic.Sort Cic.Prop
582                 | Cic.Sort _, Cic.Sort Cic.CProp _
583                 | Cic.Sort _, Cic.Sort Cic.Set
584                 | Cic.Sort _, Cic.Sort Cic.Type _ -> ugraph
585                 | a,b ->
586                    raise
587                     (TypeCheckerFailure
588                       (lazy ("Wrong constructor or inductive arity shape: "^
589                         CicPp.ppterm a ^ " --- " ^ CicPp.ppterm b))) in
590               (* let's check also the positivity conditions *)
591               if
592                 not
593                   (are_all_occurrences_positive context uri indparamsno
594                     (i+indparamsno) indparamsno (len+indparamsno) te)
595               then
596                 begin
597                 prerr_endline (UriManager.string_of_uri uri);
598                 prerr_endline (string_of_int (List.length tys));
599                 raise
600                   (TypeCheckerFailure
601                     (lazy ("Non positive occurence in " ^ U.string_of_uri uri)))                end 
602               else
603                 ugraph
604             ) ugraph cl in
605         (i + 1),ugraph''
606       ) itl (1,ugrap1)
607   in
608   ugraph2
609
610 (* Main function to checks the correctness of a mutual *)
611 (* inductive block definition.                         *)
612 and check_mutual_inductive_defs uri obj ugraph =
613   match obj with
614       Cic.InductiveDefinition (itl, params, indparamsno, _) ->
615         typecheck_mutual_inductive_defs uri (itl,params,indparamsno) ugraph 
616     | _ ->
617         raise (TypeCheckerFailure (
618                 lazy ("Unknown mutual inductive definition:" ^
619                  UriManager.string_of_uri uri)))
620
621 and type_of_mutual_inductive_defs ~logger uri i orig_ugraph =
622  let module C = Cic in
623  let module R = CicReduction in
624  let module U = UriManager in
625   let cobj,ugraph1 =
626    match CicEnvironment.is_type_checked ~trust:true orig_ugraph uri with
627        CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
628      | CicEnvironment.UncheckedObj (uobj,unchecked_ugraph) ->
629          logger#log (`Start_type_checking uri) ;
630          let inferred_ugraph = 
631            check_mutual_inductive_defs ~logger uri uobj CicUniv.empty_ugraph 
632          in
633          let ugraph, ul, obj = check_and_clean_ugraph inferred_ugraph unchecked_ugraph uri uobj in
634          CicEnvironment.set_type_checking_info uri (obj,ugraph,ul);
635          logger#log (`Type_checking_completed uri) ;
636          (match CicEnvironment.is_type_checked ~trust:false orig_ugraph uri with
637               CicEnvironment.CheckedObj (cobj,ugraph') -> (cobj,ugraph')
638             | CicEnvironment.UncheckedObj _ -> raise CicEnvironmentError
639          )
640   in
641   match cobj with
642   | C.InductiveDefinition (dl,_,_,_) ->
643       let (_,_,arity,_) = List.nth dl i in
644         arity,ugraph1
645   | _ ->
646      raise (TypeCheckerFailure
647       (lazy ("Unknown mutual inductive definition:" ^ U.string_of_uri uri)))
648             
649 and type_of_mutual_inductive_constr ~logger uri i j orig_ugraph =
650  let module C = Cic in
651  let module R = CicReduction in
652  let module U = UriManager in
653   let cobj,ugraph1 =
654     match CicEnvironment.is_type_checked ~trust:true orig_ugraph uri with
655         CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
656       | CicEnvironment.UncheckedObj (uobj,unchecked_ugraph) ->
657           logger#log (`Start_type_checking uri) ;
658           let inferred_ugraph = 
659             check_mutual_inductive_defs ~logger uri uobj CicUniv.empty_ugraph 
660           in
661           let ugraph, ul, obj = check_and_clean_ugraph inferred_ugraph unchecked_ugraph uri uobj in
662           CicEnvironment.set_type_checking_info uri (obj, ugraph, ul);
663           logger#log (`Type_checking_completed uri) ;
664           (match 
665              CicEnvironment.is_type_checked ~trust:false orig_ugraph uri 
666            with
667                  CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph' 
668                | CicEnvironment.UncheckedObj _ -> 
669                        raise CicEnvironmentError)
670   in
671     match cobj with
672         C.InductiveDefinition (dl,_,_,_) ->
673           let (_,_,_,cl) = List.nth dl i in
674           let (_,ty) = List.nth cl (j-1) in
675             ty,ugraph1
676       | _ ->
677           raise (TypeCheckerFailure
678            (lazy ("Unknown mutual inductive definition:" ^ UriManager.string_of_uri uri)))
679
680 and recursive_args context n nn te =
681  let module C = Cic in
682  match CicReduction.whd context te with
683     C.Rel _ 
684   | C.MutInd _ -> []
685   | C.Var _
686   | C.Meta _
687   | C.Sort _
688   | C.Implicit _
689   | C.Cast _ (*CSC ??? *) ->
690      raise (AssertFailure (lazy "3")) (* due to type-checking *)
691   | C.Prod (name,so,de) ->
692      (not (does_not_occur context n nn so)) ::
693       (recursive_args ((Some (name,(C.Decl so)))::context) (n+1) (nn + 1) de)
694   | C.Lambda _
695   | C.LetIn _ ->
696      raise (AssertFailure (lazy "4")) (* due to type-checking *)
697   | C.Appl _ -> []
698   | C.Const _ -> raise (AssertFailure (lazy "5"))
699   | C.MutConstruct _
700   | C.MutCase _
701   | C.Fix _
702   | C.CoFix _ -> raise (AssertFailure (lazy "6")) (* due to type-checking *)
703
704 and get_new_safes ~subst context p rl safes n nn x =
705  let module C = Cic in
706  let module U = UriManager in
707  let module R = CicReduction in
708   match R.whd ~subst context p, rl with
709    | C.Lambda (name,so,ta), b::tl ->
710        let safes = List.map (fun x -> x + 1) safes in
711        let safes = if b then 1::safes else safes in
712        get_new_safes ~subst ((Some (name,(C.Decl so)))::context)
713           ta tl safes (n+1) (nn+1) (x+1)
714    | C.MutConstruct _ as e, _
715    | (C.Rel _ as e), _
716    | e, [] -> (e,safes,n,nn,x,context)
717    | p,_::_ ->
718       raise
719        (AssertFailure (lazy
720          (Printf.sprintf "Get New Safes: p=%s" (CicPp.ppterm p))))
721
722 and split_prods ~subst context n te =
723  let module C = Cic in
724  let module R = CicReduction in
725   match (n, R.whd ~subst context te) with
726      (0, _) -> context,te
727    | (n, C.Sort _) when n <= 0 -> context,te
728    | (n, C.Prod (name,so,ta)) ->
729        split_prods ~subst ((Some (name,(C.Decl so)))::context) (n - 1) ta
730    | (_, _) -> raise (AssertFailure (lazy "8"))
731
732 and eat_lambdas ~subst context n te =
733  let module C = Cic in
734  let module R = CicReduction in
735   match (n, R.whd ~subst context te) with
736      (0, _) -> (te, 0, context)
737    | (n, C.Lambda (name,so,ta)) when n > 0 ->
738       let (te, k, context') =
739        eat_lambdas ~subst ((Some (name,(C.Decl so)))::context) (n - 1) ta
740       in
741        (te, k + 1, context')
742    | (n, te) ->
743        raise (AssertFailure (lazy (sprintf "9 (%d, %s)" n (CicPp.ppterm te))))
744
745 and specialize_inductive_type ~logger ~subst ~metasenv context t = 
746   let ty,_= type_of_aux' ~logger ~subst metasenv context t CicUniv.oblivion_ugraph in
747   match CicReduction.whd ~subst context ty with
748   | Cic.MutInd (uri,_,exp) 
749   | Cic.Appl (Cic.MutInd (uri,_,exp) :: _) as ty ->
750       let args = match ty with Cic.Appl (_::tl) -> tl | _ -> [] in
751       let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
752       (match o with
753       | Cic.InductiveDefinition (tl,_,paramsno,_) ->
754           let left_args,_ = HExtlib.split_nth paramsno args in
755           List.map (fun (name, isind, arity, cl) ->
756             let arity = CicSubstitution.subst_vars exp arity in
757             let arity = instantiate_parameters left_args arity in
758             let cl =
759               List.map
760                (fun (id,ty) -> 
761                  let ty = CicSubstitution.subst_vars exp ty in
762                  id, instantiate_parameters left_args ty) 
763                cl 
764             in
765             name, isind, arity, cl)
766           tl, paramsno
767       | _ -> assert false)
768   | _ -> assert false
769
770 and check_is_really_smaller_arg 
771   ~logger ~metasenv ~subst rec_uri rec_uri_len context n nn kl x safes te 
772 =
773  let module C = Cic in
774  let module U = UriManager in
775  (*CSC: we could perform beta-iota(-zeta?) immediately, and
776    delta only on-demand when it fails without *)
777  match CicReduction.whd ~subst context te with
778      C.Rel m when List.mem m safes -> true
779    | C.Rel _ 
780    | C.MutConstruct _
781    | C.Const _
782    | C.Var _ -> false
783    | C.Appl (he::_) ->
784         check_is_really_smaller_arg rec_uri rec_uri_len 
785           ~logger ~metasenv ~subst context n nn kl x safes he
786    | C.Lambda (name,ty,ta) ->
787       check_is_really_smaller_arg rec_uri rec_uri_len 
788         ~logger ~metasenv ~subst (Some (name,Cic.Decl ty)::context)
789         (n+1) (nn+1) kl (x+1) (List.map (fun n -> n+1) safes) ta
790    | C.MutCase (uri,i,outtype,term,pl) ->
791       (match term with
792       | C.Rel m | C.Appl ((C.Rel m)::_) when List.mem m safes || m = x ->
793          let tys,_ = 
794            specialize_inductive_type ~logger ~subst ~metasenv context term 
795          in
796          let tys_ctx,_ = 
797            List.fold_left
798              (fun (types,len) (n,_,ty,_) ->
799                Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
800                len+1) 
801              ([],0) tys
802          in
803          let _,isinductive,_,cl = List.nth tys i in
804          if not isinductive then
805            List.for_all
806             (check_is_really_smaller_arg rec_uri rec_uri_len 
807               ~logger ~metasenv ~subst context n nn kl x safes)
808             pl
809          else
810            List.for_all2
811             (fun p (_,c) ->
812               let rec_params =
813                let c = 
814                  debrujin_constructor ~check_exp_named_subst:false
815                   rec_uri rec_uri_len context c in
816                let len_ctx = List.length context in
817                recursive_args (context@tys_ctx) len_ctx (len_ctx+rec_uri_len) c
818               in
819               let (e, safes',n',nn',x',context') =
820                 get_new_safes ~subst context p rec_params safes n nn x
821               in
822                check_is_really_smaller_arg rec_uri rec_uri_len 
823                 ~logger ~metasenv ~subst context' n' nn' kl x' safes' e
824             ) pl cl
825         | _ ->
826           List.for_all
827            (check_is_really_smaller_arg 
828              rec_uri rec_uri_len ~logger ~metasenv ~subst 
829              context n nn kl x safes) pl
830       )
831    | C.Fix (_, fl) ->
832       let len = List.length fl in
833        let n_plus_len = n + len
834        and nn_plus_len = nn + len
835        and x_plus_len = x + len
836        and tys,_ =
837         List.fold_left
838           (fun (types,len) (n,_,ty,_) ->
839              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
840               len+1)
841           ) ([],0) fl
842        and safes' = List.map (fun x -> x + len) safes in
843         List.for_all
844          (fun (_,_,_,bo) ->
845             check_is_really_smaller_arg 
846               rec_uri rec_uri_len ~logger ~metasenv ~subst 
847                 (tys@context) n_plus_len nn_plus_len kl
848              x_plus_len safes' bo
849          ) fl
850    | t ->
851       raise (AssertFailure (lazy ("An inhabitant of an inductive type in normal form cannot have this shape: " ^ CicPp.ppterm t)))
852
853 and guarded_by_destructors 
854   ~logger ~metasenv ~subst rec_uri rec_uri_len context n nn kl x safes t 
855 =
856  let module C = Cic in
857  let module U = UriManager in
858   let t = CicReduction.whd ~delta:false ~subst context t in
859   let res =
860    match t with
861      C.Rel m when m > n && m <= nn -> false
862    | C.Rel m ->
863       (match List.nth context (m-1) with
864           Some (_,C.Decl _) -> true
865         | Some (_,C.Def (bo,_)) ->
866            guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes
867             (CicSubstitution.lift m bo)
868         | None -> raise (TypeCheckerFailure (lazy "Reference to deleted hypothesis"))
869       )
870    | C.Meta _
871    | C.Sort _
872    | C.Implicit _ -> true
873    | C.Cast (te,ty) ->
874       guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes te &&
875        guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes ty
876    | C.Prod (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.Lambda (name,so,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 ((Some (name,(C.Decl so)))::context)
883         (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
884    | C.LetIn (name,so,ty,ta) ->
885       guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes so &&
886        guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes ty &&
887         guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst ((Some (name,(C.Def (so,ty))))::context)
888          (n+1) (nn+1) kl (x+1) (List.map (fun x -> x + 1) safes) ta
889    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
890       let k = List.nth kl (m - n - 1) in
891        if not (List.length tl > k) then false
892        else
893         List.for_all
894          (guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes) tl &&
895         check_is_really_smaller_arg 
896           rec_uri rec_uri_len 
897           ~logger ~metasenv ~subst context n nn kl x safes (List.nth tl k)
898    | C.Var (_,exp_named_subst)
899    | C.Const (_,exp_named_subst)
900    | C.MutInd (_,_,exp_named_subst)
901    | C.MutConstruct (_,_,_,exp_named_subst) ->
902       List.for_all
903        (fun (_,t) -> guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes t)
904        exp_named_subst 
905    | C.MutCase (uri,i,outtype,term,pl) ->
906       (match CicReduction.whd ~subst context term with
907         | C.Rel m 
908         | C.Appl ((C.Rel m)::_) as t when List.mem m safes || m = x ->
909            let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
910            List.for_all
911              (guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes)
912              tl &&
913            let tys,_ = 
914              specialize_inductive_type ~logger ~subst ~metasenv context t
915            in
916            let tys_ctx,_ = 
917              List.fold_left
918                (fun (types,len) (n,_,ty,_) ->
919                  Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
920                  len+1) 
921                ([],0) tys
922            in
923            let _,isinductive,_,cl = List.nth tys i in
924             if not isinductive then
925              guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes outtype &&
926               guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes term &&
927               List.for_all
928                (guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes)
929                pl
930             else
931              guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes outtype &&
932              List.for_all2
933               (fun p (_,c) ->
934                let rec_params =
935                 let c = 
936                  debrujin_constructor ~check_exp_named_subst:false 
937                   rec_uri rec_uri_len context c in
938                 let len_ctx = List.length context in
939                 recursive_args (context@tys_ctx) len_ctx (len_ctx+rec_uri_len) c
940                in
941                let (e, safes',n',nn',x',context') =
942                 get_new_safes ~subst context p rec_params safes n nn x
943                in
944                 guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context' n' nn' kl x' safes' e
945                ) pl cl
946         | _ ->
947           guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes outtype &&
948            guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes term &&
949            (*CSC: manca ??? il controllo sul tipo di term? *)
950            List.fold_right
951             (fun p i -> i && guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes p)
952             pl true
953       )
954    | C.Appl (C.Fix (fixno, fl)::_) | C.Fix (fixno,fl) as t->
955       let l = match t with C.Appl (_::tl) -> tl | _ -> [] in
956       let len = List.length fl in
957       let n_plus_len = n + len in
958       let nn_plus_len = nn + len in
959       let x_plus_len = x + len in
960       let tys,_ =
961         List.fold_left
962           (fun (types,len) (n,_,ty,_) ->
963              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
964               len+1)
965           ) ([],0) fl in
966        let safes' = List.map (fun x -> x + len) safes in
967         List.for_all
968          (guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes) l &&
969         snd (List.fold_left
970          (fun (fixno',i) (_,recno,ty,bo) ->
971            fixno'+1,
972            i &&
973            guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x_plus_len safes' ty &&
974            if
975             fixno' = fixno &&
976             List.length l > recno &&
977             (*case where the recursive argument is already really_smaller *)
978             check_is_really_smaller_arg 
979               rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes
980               (List.nth l recno)
981            then
982             let bo_without_lambdas,_,context =
983              eat_lambdas ~subst (tys@context) (recno+1) bo
984             in
985              (* we assume the formal argument to be safe *)
986              guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context (n_plus_len+recno+1)
987               (nn_plus_len+recno+1) kl (x_plus_len+recno+1)
988               (1::List.map (fun x -> x+recno+1) safes')
989               bo_without_lambdas
990            else
991             guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst (tys@context) n_plus_len nn_plus_len
992              kl x_plus_len safes' bo
993          ) (0,true) fl)
994    | C.CoFix (_, fl) ->
995       let len = List.length fl in
996        let n_plus_len = n + len
997        and nn_plus_len = nn + len
998        and x_plus_len = x + len
999        and tys,_ =
1000         List.fold_left
1001           (fun (types,len) (n,ty,_) ->
1002              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1003               len+1)
1004           ) ([],0) fl
1005        and safes' = List.map (fun x -> x + len) safes in
1006         List.fold_right
1007          (fun (_,ty,bo) i ->
1008            i &&
1009             guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x_plus_len safes' ty &&
1010             guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst (tys@context) n_plus_len nn_plus_len kl
1011              x_plus_len safes' bo
1012          ) fl true
1013    | C.Appl tl ->
1014       List.fold_right
1015        (fun t i -> i && guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes t)
1016        tl true
1017   in
1018    if res then res
1019    else
1020     let t' = CicReduction.whd ~subst context t in
1021      if t = t' then
1022       false
1023      else
1024       guarded_by_destructors rec_uri rec_uri_len ~logger ~metasenv ~subst context n nn kl x safes t'
1025
1026 (* the boolean h means already protected *)
1027 (* args is the list of arguments the type of the constructor that may be *)
1028 (* found in head position must be applied to.                            *)
1029 and guarded_by_constructors ~logger ~subst ~metasenv indURI =
1030  let module C = Cic in
1031  let rec aux context n nn h te =
1032   match CicReduction.whd ~subst context te with
1033    | C.Rel m when m > n && m <= nn -> h
1034    | C.Rel _ 
1035    | C.Meta _ -> true
1036    | C.Sort _
1037    | C.Implicit _
1038    | C.Cast _
1039    | C.Prod _
1040    | C.MutInd _ 
1041    | C.LetIn _ -> raise (AssertFailure (lazy "17"))
1042    | C.Lambda (name,so,de) ->
1043       does_not_occur ~subst context n nn so &&
1044       aux ((Some (name,(C.Decl so)))::context) (n + 1) (nn + 1) h de
1045    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
1046       h && List.for_all (does_not_occur ~subst context n nn) tl
1047    | C.MutConstruct (_,_,_,exp_named_subst) ->
1048       List.for_all 
1049         (fun (_,x) -> does_not_occur ~subst context n nn x) exp_named_subst
1050    | C.Appl ((C.MutConstruct (uri,i,j,exp_named_subst))::tl) as t ->
1051       List.for_all 
1052         (fun (_,x) -> does_not_occur ~subst context n nn x) exp_named_subst &&
1053       let consty, len_tys, tys_ctx, paramsno =
1054        let tys, paramsno = 
1055          specialize_inductive_type ~logger ~subst ~metasenv context t in
1056        let _,_,_,cl = List.nth tys i in  
1057        let _,ty = List.nth cl (j-1) in  
1058          ty, List.length tys,
1059          fst(List.fold_left
1060           (fun (types,len) (n,_,ty,_) ->
1061            Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types, len+1)
1062           ([],0) tys), paramsno
1063       in
1064       let rec_params =
1065        let c = 
1066          debrujin_constructor ~check_exp_named_subst:false
1067            indURI len_tys context consty 
1068        in
1069        let len_ctx = List.length context in
1070        recursive_args (context@tys_ctx) len_ctx (len_ctx+len_tys) c
1071       in
1072       let rec analyse_instantiated_type rec_spec args =
1073        match rec_spec, args with
1074        | h::rec_spec, he::args -> 
1075            aux context n nn h he &&
1076            analyse_instantiated_type rec_spec args 
1077        | _,[] -> true
1078        | _ -> raise (AssertFailure (lazy 
1079          ("Too many args for constructor: " ^ String.concat " "
1080          (List.map (fun x-> CicPp.ppterm x) args))))
1081       in
1082       let left, args = HExtlib.split_nth paramsno tl in
1083       List.for_all (does_not_occur ~subst context n nn) left &&
1084       analyse_instantiated_type rec_params args
1085    | C.Appl ((C.MutCase (_,_,out,te,pl))::_) 
1086    | C.MutCase (_,_,out,te,pl) as t ->
1087        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
1088        List.for_all (does_not_occur ~subst context n nn) tl &&
1089        does_not_occur ~subst context n nn out &&
1090        does_not_occur ~subst context n nn te &&
1091        List.for_all (aux context n nn h ) pl
1092    | C.Fix (_,fl)
1093    | C.Appl (C.Fix (_,fl)::_) as t ->
1094        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
1095       let len = List.length fl in
1096        let n_plus_len = n + len
1097        and nn_plus_len = nn + len
1098        and tys,_ =
1099         List.fold_left
1100           (fun (types,len) (n,_,ty,_) ->
1101              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1102               len+1)
1103           ) ([],0) fl
1104        in
1105         List.for_all (does_not_occur ~subst context n nn) tl &&
1106         List.for_all
1107          (fun (_,_,ty,bo) ->
1108            does_not_occur ~subst context n nn ty &&
1109            aux (tys@context) n_plus_len nn_plus_len h bo)
1110          fl
1111    | C.Appl ((C.CoFix (_,fl))::_) 
1112    | C.CoFix (_,fl) as t ->
1113        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
1114        let len = List.length fl in
1115        let n_plus_len = n + len
1116        and nn_plus_len = nn + len
1117        and tys,_ =
1118           List.fold_left
1119             (fun (types,len) (n,ty,_) ->
1120                (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1121                 len+1)
1122             ) ([],0) fl
1123        in
1124        List.for_all (does_not_occur ~subst context n nn) tl &&
1125        List.for_all 
1126          (fun (_,ty,bo) ->
1127             does_not_occur ~subst context n nn ty &&
1128             aux (tys@context) n_plus_len nn_plus_len h bo) 
1129          fl
1130    | C.Var _
1131    | C.Const _
1132    | C.Appl _ as t -> does_not_occur ~subst context n nn t
1133  in
1134    aux 
1135
1136 and check_allowed_sort_elimination ~subst ~metasenv ~logger context uri i
1137   need_dummy ind arity1 arity2 ugraph =
1138  let module C = Cic in
1139  let module U = UriManager in
1140   let arity1 = CicReduction.whd ~subst context arity1 in
1141   let rec check_allowed_sort_elimination_aux ugraph context arity2 need_dummy =
1142    match arity1, CicReduction.whd ~subst context arity2 with
1143      (C.Prod (name,so1,de1), C.Prod (_,so2,de2)) ->
1144        let b,ugraph1 =
1145         CicReduction.are_convertible ~subst ~metasenv context so1 so2 ugraph in
1146        if b then
1147          check_allowed_sort_elimination ~subst ~metasenv ~logger 
1148            ((Some (name,C.Decl so1))::context) uri i
1149           need_dummy (C.Appl [CicSubstitution.lift 1 ind ; C.Rel 1]) de1 de2
1150           ugraph1
1151        else
1152          false,ugraph1
1153    | (C.Sort _, C.Prod (name,so,ta)) when not need_dummy ->
1154        let b,ugraph1 =
1155         CicReduction.are_convertible ~subst ~metasenv context so ind ugraph in
1156        if not b then
1157          false,ugraph1
1158        else
1159         check_allowed_sort_elimination_aux ugraph1
1160          ((Some (name,C.Decl so))::context) ta true
1161    | (C.Sort C.Prop, C.Sort C.Prop) when need_dummy -> true,ugraph
1162    | (C.Sort C.Prop, C.Sort C.Set)
1163    | (C.Sort C.Prop, C.Sort (C.CProp _))
1164    | (C.Sort C.Prop, C.Sort (C.Type _) ) when need_dummy ->
1165        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1166          match o with
1167          C.InductiveDefinition (itl,_,paramsno,_) ->
1168            let itl_len = List.length itl in
1169            let (name,_,ty,cl) = List.nth itl i in
1170            let cl_len = List.length cl in
1171             if (cl_len = 0 || (itl_len = 1 && cl_len = 1)) then
1172              let non_informative,ugraph =
1173               if cl_len = 0 then true,ugraph
1174               else
1175                is_non_informative ~logger [Some (C.Name name,C.Decl ty)]
1176                 paramsno (snd (List.nth cl 0)) ugraph
1177              in
1178               (* is it a singleton or empty non recursive and non informative
1179                  definition? *)
1180               non_informative, ugraph
1181             else
1182               false,ugraph
1183          | _ ->
1184              raise (TypeCheckerFailure 
1185                      (lazy ("Unknown mutual inductive definition:" ^
1186                        UriManager.string_of_uri uri)))
1187        )
1188    | (C.Sort C.Set, C.Sort C.Prop) when need_dummy -> true , ugraph
1189    | (C.Sort C.Set, C.Sort C.Set) when need_dummy -> true , ugraph
1190    | (C.Sort C.Set, C.Sort (C.Type _)) 
1191    | (C.Sort C.Set, C.Sort (C.CProp _))
1192       when need_dummy ->
1193        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1194          match o with
1195            C.InductiveDefinition (itl,_,paramsno,_) ->
1196             let tys =
1197              List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) itl
1198             in
1199              let (_,_,_,cl) = List.nth itl i in
1200               (List.fold_right
1201                (fun (_,x) (i,ugraph) -> 
1202                  if i then
1203                           is_small ~logger tys paramsno x ugraph
1204                  else
1205                    false,ugraph
1206                     ) cl (true,ugraph))
1207            | _ ->
1208             raise (TypeCheckerFailure
1209              (lazy ("Unknown mutual inductive definition:" ^
1210               UriManager.string_of_uri uri)))
1211        )
1212    | (C.Sort (C.Type _), C.Sort _) when need_dummy -> true , ugraph
1213    | (C.Sort (C.CProp _), C.Sort _) when need_dummy -> true , ugraph
1214    | (_,_) -> false,ugraph
1215  in
1216   check_allowed_sort_elimination_aux ugraph context arity2 need_dummy
1217          
1218 and type_of_branch ~subst context argsno need_dummy outtype term constype =
1219  let module C = Cic in
1220  let module R = CicReduction in
1221   match R.whd ~subst context constype with
1222      C.MutInd (_,_,_) ->
1223       if need_dummy then
1224        outtype
1225       else
1226        C.Appl [outtype ; term]
1227    | C.Appl (C.MutInd (_,_,_)::tl) ->
1228       let (_,arguments) = split tl argsno
1229       in
1230        if need_dummy && arguments = [] then
1231         outtype
1232        else
1233         C.Appl (outtype::arguments@(if need_dummy then [] else [term]))
1234    | C.Prod (name,so,de) ->
1235       let term' =
1236        match CicSubstitution.lift 1 term with
1237           C.Appl l -> C.Appl (l@[C.Rel 1])
1238         | t -> C.Appl [t ; C.Rel 1]
1239       in
1240        C.Prod (name,so,type_of_branch ~subst
1241         ((Some (name,(C.Decl so)))::context) argsno need_dummy
1242         (CicSubstitution.lift 1 outtype) term' de)
1243    | _ -> raise (AssertFailure (lazy "20"))
1244
1245 (* check_metasenv_consistency checks that the "canonical" context of a
1246 metavariable is consitent - up to relocation via the relocation list l -
1247 with the actual context *)
1248
1249
1250 and check_metasenv_consistency ~logger ~subst metasenv context 
1251   canonical_context l ugraph 
1252 =
1253   let module C = Cic in
1254   let module R = CicReduction in
1255   let module S = CicSubstitution in
1256   let lifted_canonical_context = 
1257     let rec aux i =
1258      function
1259          [] -> []
1260        | (Some (n,C.Decl t))::tl ->
1261            (Some (n,C.Decl (S.subst_meta l (S.lift i t))))::(aux (i+1) tl)
1262        | None::tl -> None::(aux (i+1) tl)
1263        | (Some (n,C.Def (t,ty)))::tl ->
1264            (Some (n,C.Def ((S.subst_meta l (S.lift i t)),S.subst_meta l (S.lift i ty))))::(aux (i+1) tl)
1265     in
1266      aux 1 canonical_context
1267    in
1268    List.fold_left2 
1269      (fun ugraph t ct -> 
1270        match (t,ct) with
1271        | _,None -> ugraph
1272        | Some t,Some (_,C.Def (ct,_)) ->
1273           (*CSC: the following optimization is to avoid a possibly expensive
1274                  reduction that can be easily avoided and that is quite
1275                  frequent. However, this is better handled using levels to
1276                  control reduction *)
1277           let optimized_t =
1278            match t with
1279               Cic.Rel n ->
1280                (try
1281                  match List.nth context (n - 1) with
1282                     Some (_,C.Def (te,_)) -> S.lift n te
1283                   | _ -> t
1284                 with
1285                  Failure _ -> t)
1286             | _ -> t
1287           in
1288 (*if t <> optimized_t && optimized_t = ct then prerr_endline "!!!!!!!!!!!!!!!"
1289 else if t <> optimized_t then prerr_endline ("@@ " ^ CicPp.ppterm t ^ " ==> " ^ CicPp.ppterm optimized_t ^ " <==> " ^ CicPp.ppterm ct);*)
1290            let b,ugraph1 = 
1291              R.are_convertible ~subst ~metasenv context optimized_t ct ugraph 
1292            in
1293            if not b then
1294              raise 
1295                (TypeCheckerFailure 
1296                   (lazy (sprintf "Not well typed metavariable local context: expected a term convertible with %s, found %s" (CicPp.ppterm ct) (CicPp.ppterm t))))
1297            else
1298              ugraph1
1299        | Some t,Some (_,C.Decl ct) ->
1300            let type_t,ugraph1 = 
1301              type_of_aux' ~logger ~subst metasenv context t ugraph 
1302            in
1303            let b,ugraph2 = 
1304              R.are_convertible ~subst ~metasenv context type_t ct ugraph1 
1305            in
1306            if not b then
1307              raise (TypeCheckerFailure 
1308                      (lazy (sprintf "Not well typed metavariable local context: expected a term of type %s, found %s of type %s" 
1309                          (CicPp.ppterm ct) (CicPp.ppterm t)
1310                          (CicPp.ppterm type_t))))
1311            else
1312              ugraph2
1313        | None, _  ->
1314            raise (TypeCheckerFailure
1315                    (lazy ("Not well typed metavariable local context: "^
1316                      "an hypothesis, that is not hidden, is not instantiated")))
1317      ) ugraph l lifted_canonical_context 
1318      
1319
1320 (* 
1321    type_of_aux' is just another name (with a different scope) 
1322    for type_of_aux 
1323 *)
1324
1325 and type_of_aux' ~logger ?(subst = []) metasenv context t ugraph =
1326  let rec type_of_aux ~logger context t ugraph =
1327   let module C = Cic in
1328   let module R = CicReduction in
1329   let module S = CicSubstitution in
1330   let module U = UriManager in
1331    match t with
1332       C.Rel n ->
1333        (try
1334          match List.nth context (n - 1) with
1335             Some (_,C.Decl t) -> S.lift n t,ugraph
1336           | Some (_,C.Def (_,ty)) -> S.lift n ty,ugraph
1337           | None -> raise 
1338               (TypeCheckerFailure (lazy "Reference to deleted hypothesis"))
1339         with
1340         Failure _ ->
1341           raise (TypeCheckerFailure (lazy "unbound variable"))
1342        )
1343     | C.Var (uri,exp_named_subst) ->
1344       incr fdebug ;
1345         let ugraph1 = 
1346           check_exp_named_subst uri ~logger ~subst context exp_named_subst ugraph 
1347         in 
1348         let ty,ugraph2 = type_of_variable ~logger uri ugraph1 in
1349         let ty1 = CicSubstitution.subst_vars exp_named_subst ty in
1350           decr fdebug ;
1351           ty1,ugraph2
1352     | C.Meta (n,l) -> 
1353        (try
1354           let (canonical_context,term,ty) = CicUtil.lookup_subst n subst in
1355           let ugraph1 =
1356             check_metasenv_consistency ~logger
1357               ~subst metasenv context canonical_context l ugraph
1358           in
1359             (* assuming subst is well typed !!!!! *)
1360             ((CicSubstitution.subst_meta l ty), ugraph1)
1361               (* type_of_aux context (CicSubstitution.subst_meta l term) *)
1362         with CicUtil.Subst_not_found _ ->
1363           let (_,canonical_context,ty) = CicUtil.lookup_meta n metasenv in
1364           let ugraph1 = 
1365             check_metasenv_consistency ~logger
1366               ~subst metasenv context canonical_context l ugraph
1367           in
1368             ((CicSubstitution.subst_meta l ty),ugraph1))
1369       (* TASSI: CONSTRAINTS *)
1370     | C.Sort (C.CProp t) -> 
1371        let t' = CicUniv.fresh() in
1372        (try
1373          let ugraph1 = CicUniv.add_gt t' t ugraph in
1374            (C.Sort (C.Type t')),ugraph1
1375         with
1376          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1377     | C.Sort (C.Type t) -> 
1378        let t' = CicUniv.fresh() in
1379        (try
1380          let ugraph1 = CicUniv.add_gt t' t ugraph in
1381            (C.Sort (C.Type t')),ugraph1
1382         with
1383          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1384     | C.Sort (C.Prop|C.Set) -> (C.Sort (C.Type (CicUniv.fresh ()))),ugraph
1385     | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
1386     | C.Cast (te,ty) as t ->
1387        let _,ugraph1 = type_of_aux ~logger context ty ugraph in
1388        let ty_te,ugraph2 = type_of_aux ~logger context te ugraph1 in
1389        let b,ugraph3 = 
1390          R.are_convertible ~subst ~metasenv context ty_te ty ugraph2 
1391        in
1392          if b then
1393            ty,ugraph3
1394          else
1395            raise (TypeCheckerFailure
1396                     (lazy (sprintf "Invalid cast %s" (CicPp.ppterm t))))
1397     | C.Prod (name,s,t) ->
1398        let sort1,ugraph1 = type_of_aux ~logger context s ugraph in
1399        let sort2,ugraph2 = 
1400          type_of_aux ~logger  ((Some (name,(C.Decl s)))::context) t ugraph1 
1401        in
1402        sort_of_prod ~subst context (name,s) (sort1,sort2) ugraph2
1403    | C.Lambda (n,s,t) ->
1404        let sort1,ugraph1 = type_of_aux ~logger context s ugraph in
1405        (match R.whd ~subst context sort1 with
1406            C.Meta _
1407          | C.Sort _ -> ()
1408          | _ ->
1409            raise
1410             (TypeCheckerFailure (lazy (sprintf
1411               "Not well-typed lambda-abstraction: the source %s should be a type; instead it is a term of type %s" (CicPp.ppterm s)
1412                 (CicPp.ppterm sort1))))
1413        ) ;
1414        let type2,ugraph2 = 
1415          type_of_aux ~logger ((Some (n,(C.Decl s)))::context) t ugraph1 
1416        in
1417          (C.Prod (n,s,type2)),ugraph2
1418    | C.LetIn (n,s,ty,t) ->
1419       (* only to check if s is well-typed *)
1420       let ty',ugraph1 = type_of_aux ~logger context s ugraph in
1421       let _,ugraph1 = type_of_aux ~logger context ty ugraph1 in
1422       let b,ugraph1 =
1423        R.are_convertible ~subst ~metasenv context ty ty' ugraph1
1424       in 
1425        if not b then
1426         raise 
1427          (TypeCheckerFailure 
1428            (lazy (sprintf
1429              "The type of %s is %s but it is expected to be %s" 
1430                (CicPp.ppterm s) (CicPp.ppterm ty') (CicPp.ppterm ty))))
1431        else
1432        (* The type of a LetIn is a LetIn. Extremely slow since the computed
1433           LetIn is later reduced and maybe also re-checked.
1434        (C.LetIn (n,s, type_of_aux ((Some (n,(C.Def s)))::context) t))
1435        *)
1436        (* The type of the LetIn is reduced. Much faster than the previous
1437           solution. Moreover the inferred type is probably very different
1438           from the expected one.
1439        (CicReduction.whd ~subst context
1440         (C.LetIn (n,s, type_of_aux ((Some (n,(C.Def s)))::context) t)))
1441        *)
1442        (* One-step LetIn reduction. Even faster than the previous solution.
1443           Moreover the inferred type is closer to the expected one. *)
1444        let ty1,ugraph2 = 
1445          type_of_aux ~logger 
1446            ((Some (n,(C.Def (s,ty))))::context) t ugraph1 
1447        in
1448        (CicSubstitution.subst ~avoid_beta_redexes:true s ty1),ugraph2
1449    | C.Appl (he::tl) when List.length tl > 0 ->
1450        let hetype,ugraph1 = type_of_aux ~logger context he ugraph in
1451        let tlbody_and_type,ugraph2 = 
1452          List.fold_right (
1453            fun x (l,ugraph) -> 
1454              let ty,ugraph1 = type_of_aux ~logger context x ugraph in
1455              (*let _,ugraph1 = type_of_aux ~logger  context ty ugraph1 in*)
1456                ((x,ty)::l,ugraph1)) 
1457            tl ([],ugraph1) 
1458        in
1459          (* TASSI: questa c'era nel mio... ma non nel CVS... *)
1460          (* let _,ugraph2 = type_of_aux context hetype ugraph2 in *)
1461          eat_prods ~subst context hetype tlbody_and_type ugraph2
1462    | C.Appl _ -> raise (AssertFailure (lazy "Appl: no arguments"))
1463    | C.Const (uri,exp_named_subst) ->
1464        incr fdebug ;
1465        let ugraph1 = 
1466          check_exp_named_subst uri ~logger ~subst  context exp_named_subst ugraph 
1467        in
1468        let cty,ugraph2 = type_of_constant ~logger uri ugraph1 in
1469        let cty1 =
1470          CicSubstitution.subst_vars exp_named_subst cty
1471        in
1472          decr fdebug ;
1473          cty1,ugraph2
1474    | C.MutInd (uri,i,exp_named_subst) ->
1475       incr fdebug ;
1476        let ugraph1 = 
1477          check_exp_named_subst uri ~logger  ~subst context exp_named_subst ugraph 
1478        in
1479        let mty,ugraph2 = type_of_mutual_inductive_defs ~logger uri i ugraph1 in
1480        let cty =
1481          CicSubstitution.subst_vars exp_named_subst mty
1482        in
1483          decr fdebug ;
1484          cty,ugraph2
1485    | C.MutConstruct (uri,i,j,exp_named_subst) ->
1486        let ugraph1 = 
1487          check_exp_named_subst uri ~logger ~subst context exp_named_subst ugraph
1488        in
1489        let mty,ugraph2 = 
1490          type_of_mutual_inductive_constr ~logger uri i j ugraph1 
1491        in
1492        let cty =
1493          CicSubstitution.subst_vars exp_named_subst mty
1494        in
1495          cty,ugraph2
1496    | C.MutCase (uri,i,outtype,term,pl) ->
1497       let outsort,ugraph1 = type_of_aux ~logger context outtype ugraph in
1498       let (need_dummy, k) =
1499       let rec guess_args context t =
1500         let outtype = CicReduction.whd ~subst context t in
1501           match outtype with
1502               C.Sort _ -> (true, 0)
1503             | C.Prod (name, s, t) ->
1504                 let (b, n) = 
1505                   guess_args ((Some (name,(C.Decl s)))::context) t in
1506                   if n = 0 then
1507                   (* last prod before sort *)
1508                     match CicReduction.whd ~subst context s with
1509 (*CSC: for _ see comment below about the missing named_exp_subst ?????????? *)
1510                         C.MutInd (uri',i',_) when U.eq uri' uri && i' = i ->
1511                           (false, 1)
1512 (*CSC: for _ see comment below about the missing named_exp_subst ?????????? *)
1513                       | C.Appl ((C.MutInd (uri',i',_)) :: _)
1514                           when U.eq uri' uri && i' = i -> (false, 1)
1515                       | _ -> (true, 1)
1516                   else
1517                     (b, n + 1)
1518             | _ ->
1519                 raise 
1520                   (TypeCheckerFailure 
1521                      (lazy (sprintf
1522                         "Malformed case analasys' output type %s" 
1523                         (CicPp.ppterm outtype))))
1524       in
1525 (*
1526       let (parameters, arguments, exp_named_subst),ugraph2 =
1527         let ty,ugraph2 = type_of_aux context term ugraph1 in
1528           match R.whd ~subst context ty with
1529            (*CSC manca il caso dei CAST *)
1530 (*CSC: ma servono i parametri (uri,i)? Se si', perche' non serve anche il *)
1531 (*CSC: parametro exp_named_subst? Se no, perche' non li togliamo?         *)
1532 (*CSC: Hint: nella DTD servono per gli stylesheet.                        *)
1533               C.MutInd (uri',i',exp_named_subst) as typ ->
1534                 if U.eq uri uri' && i = i' then 
1535                   ([],[],exp_named_subst),ugraph2
1536                 else 
1537                   raise 
1538                     (TypeCheckerFailure 
1539                       (lazy (sprintf
1540                           ("Case analysys: analysed term type is %s, but is expected to be (an application of) %s#1/%d{_}")
1541                           (CicPp.ppterm typ) (U.string_of_uri uri) i)))
1542             | C.Appl 
1543                 ((C.MutInd (uri',i',exp_named_subst) as typ):: tl) as typ' ->
1544                 if U.eq uri uri' && i = i' then
1545                   let params,args =
1546                     split tl (List.length tl - k)
1547                   in (params,args,exp_named_subst),ugraph2
1548                 else 
1549                   raise 
1550                     (TypeCheckerFailure 
1551                       (lazy (sprintf 
1552                           ("Case analysys: analysed term type is %s, "^
1553                            "but is expected to be (an application of) "^
1554                            "%s#1/%d{_}")
1555                           (CicPp.ppterm typ') (U.string_of_uri uri) i)))
1556             | _ ->
1557                 raise 
1558                   (TypeCheckerFailure 
1559                     (lazy (sprintf
1560                         ("Case analysis: "^
1561                          "analysed term %s is not an inductive one")
1562                         (CicPp.ppterm term))))
1563 *)
1564       let (b, k) = guess_args context outsort in
1565           if not b then (b, k - 1) else (b, k) in
1566       let (parameters, arguments, exp_named_subst),ugraph2 =
1567         let ty,ugraph2 = type_of_aux ~logger context term ugraph1 in
1568         match R.whd ~subst context ty with
1569             C.MutInd (uri',i',exp_named_subst) as typ ->
1570               if U.eq uri uri' && i = i' then 
1571                 ([],[],exp_named_subst),ugraph2
1572               else raise 
1573                 (TypeCheckerFailure 
1574                   (lazy (sprintf
1575                       ("Case analysys: analysed term type is %s (%s#1/%d{_}), but is expected to be (an application of) %s#1/%d{_}")
1576                       (CicPp.ppterm typ) (U.string_of_uri uri') i' (U.string_of_uri uri) i)))
1577           | C.Appl ((C.MutInd (uri',i',exp_named_subst) as typ):: tl) ->
1578               if U.eq uri uri' && i = i' then
1579                 let params,args =
1580                   split tl (List.length tl - k)
1581                 in (params,args,exp_named_subst),ugraph2
1582               else raise 
1583                 (TypeCheckerFailure 
1584                   (lazy (sprintf
1585                       ("Case analysys: analysed term type is %s (%s#1/%d{_}), but is expected to be (an application of) %s#1/%d{_}")
1586                       (CicPp.ppterm typ) (U.string_of_uri uri') i' (U.string_of_uri uri) i)))
1587           | _ ->
1588               raise 
1589                 (TypeCheckerFailure 
1590                   (lazy (sprintf
1591                       "Case analysis: analysed term %s is not an inductive one"
1592                       (CicPp.ppterm term))))
1593       in
1594         (* 
1595            let's control if the sort elimination is allowed: 
1596            [(I q1 ... qr)|B] 
1597         *)
1598       let sort_of_ind_type =
1599         if parameters = [] then
1600           C.MutInd (uri,i,exp_named_subst)
1601         else
1602           C.Appl ((C.MutInd (uri,i,exp_named_subst))::parameters)
1603       in
1604       let type_of_sort_of_ind_ty,ugraph3 = 
1605         type_of_aux ~logger context sort_of_ind_type ugraph2 in
1606       let b,ugraph4 = 
1607         check_allowed_sort_elimination ~subst ~metasenv ~logger  context uri i
1608           need_dummy sort_of_ind_type type_of_sort_of_ind_ty outsort ugraph3 
1609       in
1610         if not b then
1611         raise
1612           (TypeCheckerFailure (lazy ("Case analysis: sort elimination not allowed")));
1613         (* let's check if the type of branches are right *)
1614       let parsno,constructorsno =
1615         let obj,_ =
1616           try
1617             CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
1618           with Not_found -> assert false
1619         in
1620         match obj with
1621             C.InductiveDefinition (il,_,parsno,_) ->
1622              let _,_,_,cl =
1623               try List.nth il i with Failure _ -> assert false
1624              in
1625               parsno, List.length cl
1626           | _ ->
1627               raise (TypeCheckerFailure
1628                 (lazy ("Unknown mutual inductive definition:" ^
1629                   UriManager.string_of_uri uri)))
1630       in
1631       if List.length pl <> constructorsno then
1632        raise (TypeCheckerFailure
1633         (lazy ("Wrong number of cases in case analysis"))) ;
1634       let (_,branches_ok,ugraph5) =
1635         List.fold_left
1636           (fun (j,b,ugraph) p ->
1637             if b then
1638               let cons =
1639                 if parameters = [] then
1640                   (C.MutConstruct (uri,i,j,exp_named_subst))
1641                 else
1642                   (C.Appl 
1643                      (C.MutConstruct (uri,i,j,exp_named_subst)::parameters))
1644               in
1645               let ty_p,ugraph1 = type_of_aux ~logger context p ugraph in
1646               let ty_cons,ugraph3 = type_of_aux ~logger context cons ugraph1 in
1647               (* 2 is skipped *)
1648               let ty_branch = 
1649                 type_of_branch ~subst context parsno need_dummy outtype cons 
1650                   ty_cons in
1651               let b1,ugraph4 =
1652                 R.are_convertible 
1653                   ~subst ~metasenv context ty_p ty_branch ugraph3 
1654               in 
1655 (* Debugging code
1656 if not b1 then
1657 begin
1658 prerr_endline ("\n!OUTTYPE= " ^ CicPp.ppterm outtype);
1659 prerr_endline ("!CONS= " ^ CicPp.ppterm cons);
1660 prerr_endline ("!TY_CONS= " ^ CicPp.ppterm ty_cons);
1661 prerr_endline ("#### " ^ CicPp.ppterm ty_p ^ "\n<==>\n" ^ CicPp.ppterm ty_branch);
1662 end;
1663 *)
1664               if not b1 then
1665                 debug_print (lazy
1666                   ("#### " ^ CicPp.ppterm ty_p ^ 
1667                   " <==> " ^ CicPp.ppterm ty_branch));
1668               (j + 1,b1,ugraph4)
1669             else
1670               (j,false,ugraph)
1671           ) (1,true,ugraph4) pl
1672          in
1673           if not branches_ok then
1674            raise
1675             (TypeCheckerFailure (lazy "Case analysys: wrong branch type"));
1676           let arguments' =
1677            if not need_dummy then outtype::arguments@[term]
1678            else outtype::arguments in
1679           let outtype =
1680            if need_dummy && arguments = [] then outtype
1681            else CicReduction.head_beta_reduce (C.Appl arguments')
1682           in
1683            outtype,ugraph5
1684    | C.Fix (i,fl) ->
1685       let types,kl,ugraph1,len =
1686         List.fold_left
1687           (fun (types,kl,ugraph,len) (n,k,ty,_) ->
1688             let _,ugraph1 = type_of_aux ~logger context ty ugraph in
1689              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1690               k::kl,ugraph1,len+1)
1691           ) ([],[],ugraph,0) fl
1692       in
1693       let ugraph2 = 
1694         List.fold_left
1695           (fun ugraph (name,x,ty,bo) ->
1696              let ty_bo,ugraph1 = 
1697                type_of_aux ~logger (types@context) bo ugraph 
1698              in
1699              let b,ugraph2 = 
1700                R.are_convertible ~subst ~metasenv (types@context) 
1701                  ty_bo (CicSubstitution.lift len ty) ugraph1 in
1702                if b then
1703                  begin
1704                    let (m, eaten, context') =
1705                      eat_lambdas ~subst (types @ context) (x + 1) bo
1706                    in
1707                    let rec_uri, rec_uri_len =
1708                     let he =
1709                      match List.hd context' with
1710                         Some (_,Cic.Decl he) -> he
1711                       | _ -> assert false
1712                     in
1713                      match CicReduction.whd ~subst (List.tl context') he with
1714                      | Cic.MutInd (uri,_,_)
1715                      | Cic.Appl (Cic.MutInd (uri,_,_)::_) ->
1716                          uri,
1717                            (match
1718                             CicEnvironment.get_obj
1719                              CicUniv.oblivion_ugraph uri
1720                            with
1721                            | Cic.InductiveDefinition (tl,_,_,_), _ ->
1722                                List.length tl
1723                            | _ -> assert false)
1724                      | _ -> assert false
1725                    in 
1726                      (*
1727                        let's control the guarded by 
1728                        destructors conditions D{f,k,x,M}
1729                      *)
1730                      if not (guarded_by_destructors ~logger ~metasenv ~subst 
1731                        rec_uri rec_uri_len context' eaten (len + eaten) kl 
1732                        1 [] m) 
1733                      then
1734                        raise
1735                          (TypeCheckerFailure 
1736                            (lazy ("Fix: not guarded by destructors:"^CicPp.ppterm t)))
1737                      else
1738                        ugraph2
1739                  end
1740                else
1741                  raise (TypeCheckerFailure (lazy ("Fix: ill-typed bodies")))
1742           ) ugraph1 fl in
1743         (*CSC: controlli mancanti solo su D{f,k,x,M} *)
1744       let (_,_,ty,_) = List.nth fl i in
1745         ty,ugraph2
1746    | C.CoFix (i,fl) ->
1747        let types,ugraph1,len =
1748          List.fold_left
1749            (fun (l,ugraph,len) (n,ty,_) -> 
1750               let _,ugraph1 = 
1751                 type_of_aux ~logger context ty ugraph in 
1752                 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::l,
1753                  ugraph1,len+1)
1754            ) ([],ugraph,0) fl
1755        in
1756        let ugraph2 = 
1757          List.fold_left
1758            (fun ugraph (_,ty,bo) ->
1759               let ty_bo,ugraph1 = 
1760                 type_of_aux ~logger (types @ context) bo ugraph 
1761               in
1762               let b,ugraph2 = 
1763                 R.are_convertible ~subst ~metasenv (types @ context) ty_bo
1764                   (CicSubstitution.lift len ty) ugraph1 
1765               in
1766                 if b then
1767                   begin
1768                     (* let's control that the returned type is coinductive *)
1769                     match returns_a_coinductive ~subst context ty with
1770                         None ->
1771                           raise
1772                           (TypeCheckerFailure
1773                             (lazy "CoFix: does not return a coinductive type"))
1774                       | Some uri ->
1775                           (*
1776                             let's control the guarded by constructors 
1777                             conditions C{f,M}
1778                           *)
1779                           if not (guarded_by_constructors ~logger ~subst ~metasenv uri
1780                  (types @ context) 0 len false bo) then
1781                             raise
1782                               (TypeCheckerFailure 
1783                                 (lazy "CoFix: not guarded by constructors"))
1784                           else
1785                           ugraph2
1786                   end
1787                 else
1788                   raise
1789                     (TypeCheckerFailure (lazy "CoFix: ill-typed bodies"))
1790            ) ugraph1 fl 
1791        in
1792        let (_,ty,_) = List.nth fl i in
1793          ty,ugraph2
1794
1795  and check_exp_named_subst uri ~logger ~subst context ens ugraph =
1796    let params =
1797     let obj,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1798     (match obj with
1799         Cic.Constant (_,_,_,params,_) -> params
1800       | Cic.Variable (_,_,_,params,_) -> params
1801       | Cic.CurrentProof (_,_,_,_,params,_) -> params
1802       | Cic.InductiveDefinition (_,params,_,_) -> params
1803     ) in
1804    let rec check_same_order params ens =
1805     match params,ens with
1806      | _,[] -> ()
1807      | [],_::_ ->
1808         raise (TypeCheckerFailure (lazy "Bad explicit named substitution"))
1809      | uri::tl,(uri',_)::tl' when UriManager.eq uri uri' ->
1810         check_same_order tl tl'
1811      | _::tl,l -> check_same_order tl l
1812    in
1813    let rec check_exp_named_subst_aux ~logger esubsts l ugraph =
1814      match l with
1815          [] -> ugraph
1816        | ((uri,t) as item)::tl ->
1817            let ty_uri,ugraph1 = type_of_variable ~logger uri ugraph in 
1818            let typeofvar =
1819              CicSubstitution.subst_vars esubsts ty_uri in
1820            let typeoft,ugraph2 = type_of_aux ~logger context t ugraph1 in
1821            let b,ugraph3 =
1822              CicReduction.are_convertible ~subst ~metasenv
1823                context typeoft typeofvar ugraph2 
1824            in
1825              if b then
1826                check_exp_named_subst_aux ~logger (esubsts@[item]) tl ugraph3
1827              else
1828                begin
1829                  CicReduction.fdebug := 0 ;
1830                  ignore 
1831                    (CicReduction.are_convertible 
1832                       ~subst ~metasenv context typeoft typeofvar ugraph2) ;
1833                  fdebug := 0 ;
1834                  debug typeoft [typeofvar] ;
1835                  raise (TypeCheckerFailure (lazy "Wrong Explicit Named Substitution"))
1836                end
1837    in
1838     check_same_order params ens ;
1839     check_exp_named_subst_aux ~logger [] ens ugraph
1840        
1841  and sort_of_prod ~subst context (name,s) (t1, t2) ugraph =
1842   let module C = Cic in
1843    let t1' = CicReduction.whd ~subst context t1 in
1844    let t2' = CicReduction.whd ~subst ((Some (name,C.Decl s))::context) t2 in
1845    match (t1', t2') with
1846     | (C.Sort s1, C.Sort (C.Prop | C.Set)) ->
1847          (* different from Coq manual!!! *)
1848          t2',ugraph
1849     | (C.Sort (C.Type t1), C.Sort (C.Type t2)) -> 
1850        let t' = CicUniv.fresh() in
1851         (try
1852          let ugraph1 = CicUniv.add_ge t' t1 ugraph in
1853          let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
1854           C.Sort (C.Type t'),ugraph2
1855         with
1856          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1857     | (C.Sort (C.CProp t1), C.Sort (C.CProp t2)) -> 
1858        let t' = CicUniv.fresh() in
1859         (try
1860          let ugraph1 = CicUniv.add_ge t' t1 ugraph in
1861          let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
1862           C.Sort (C.CProp t'),ugraph2
1863         with
1864          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1865     | (C.Sort (C.Type t1), C.Sort (C.CProp t2)) -> 
1866        let t' = CicUniv.fresh() in
1867         (try
1868          let ugraph1 = CicUniv.add_ge t' t1 ugraph in
1869          let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
1870           C.Sort (C.CProp t'),ugraph2
1871         with
1872          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1873     | (C.Sort (C.CProp t1), C.Sort (C.Type t2)) -> 
1874        let t' = CicUniv.fresh() in
1875         (try
1876          let ugraph1 = CicUniv.add_gt t' t1 ugraph in
1877          let ugraph2 = CicUniv.add_ge t' t2 ugraph1 in
1878           C.Sort (C.Type t'),ugraph2
1879         with
1880          CicUniv.UniverseInconsistency msg -> raise (TypeCheckerFailure msg))
1881     | (C.Sort _,C.Sort (C.Type t1)) -> C.Sort (C.Type t1),ugraph 
1882     | (C.Sort _,C.Sort (C.CProp t1)) -> C.Sort (C.CProp t1),ugraph 
1883     | (C.Meta _, C.Sort _) -> t2',ugraph
1884     | (C.Meta _, (C.Meta (_,_) as t))
1885     | (C.Sort _, (C.Meta (_,_) as t)) when CicUtil.is_closed t ->
1886         t2',ugraph
1887     | (_,_) -> raise (TypeCheckerFailure (lazy (sprintf
1888         "Prod: expected two sorts, found = %s, %s" (CicPp.ppterm t1')
1889           (CicPp.ppterm t2'))))
1890
1891  and eat_prods ~subst context hetype l ugraph =
1892    (*CSC: siamo sicuri che le are_convertible non lavorino con termini non *)
1893    (*CSC: cucinati                                                         *)
1894    match l with
1895        [] -> hetype,ugraph
1896      | (hete, hety)::tl ->
1897          (match (CicReduction.whd ~subst context hetype) with 
1898               Cic.Prod (n,s,t) ->
1899                 let b,ugraph1 = 
1900 (*if (match hety,s with Cic.Sort _,Cic.Sort _ -> false | _,_ -> true) && hety <> s then(
1901 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*)
1902                   CicReduction.are_convertible 
1903                     ~subst ~metasenv context hety s ugraph 
1904                 in        
1905                   if b then
1906                     begin
1907                       CicReduction.fdebug := -1 ;
1908                       eat_prods ~subst context 
1909                         (CicSubstitution.subst ~avoid_beta_redexes:true hete t)
1910                          tl ugraph1
1911                         (*TASSI: not sure *)
1912                     end
1913                   else
1914                     begin
1915                       CicReduction.fdebug := 0 ;
1916                       ignore (CicReduction.are_convertible 
1917                                 ~subst ~metasenv context s hety ugraph) ;
1918                       fdebug := 0 ;
1919                       debug s [hety] ;
1920                       raise 
1921                         (TypeCheckerFailure 
1922                           (lazy (sprintf
1923                               ("Appl: wrong parameter-type, expected %s, found %s")
1924                               (CicPp.ppterm hetype) (CicPp.ppterm s))))
1925                     end
1926             | _ ->
1927                 raise (TypeCheckerFailure
1928                         (lazy "Appl: this is not a function, it cannot be applied"))
1929          )
1930
1931  and returns_a_coinductive ~subst context ty =
1932   let module C = Cic in
1933    match CicReduction.whd ~subst context ty with
1934       C.MutInd (uri,i,_) ->
1935        (*CSC: definire una funzioncina per questo codice sempre replicato *)
1936         let obj,_ =
1937           try
1938             CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
1939           with Not_found -> assert false
1940         in
1941         (match obj with
1942            C.InductiveDefinition (itl,_,_,_) ->
1943             let (_,is_inductive,_,_) = List.nth itl i in
1944              if is_inductive then None else (Some uri)
1945          | _ ->
1946             raise (TypeCheckerFailure
1947               (lazy ("Unknown mutual inductive definition:" ^
1948               UriManager.string_of_uri uri)))
1949         )
1950     | C.Appl ((C.MutInd (uri,i,_))::_) ->
1951        (let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1952          match o with
1953            C.InductiveDefinition (itl,_,_,_) ->
1954             let (_,is_inductive,_,_) = List.nth itl i in
1955              if is_inductive then None else (Some uri)
1956          | _ ->
1957             raise (TypeCheckerFailure
1958               (lazy ("Unknown mutual inductive definition:" ^
1959               UriManager.string_of_uri uri)))
1960         )
1961     | C.Prod (n,so,de) ->
1962        returns_a_coinductive ~subst ((Some (n,C.Decl so))::context) de
1963     | _ -> None
1964
1965  in
1966 (*CSC
1967 debug_print (lazy ("INIZIO TYPE_OF_AUX " ^ CicPp.ppterm t)) ; flush stderr ;
1968 let res =
1969 *)
1970   type_of_aux ~logger context t ugraph
1971 (*
1972 in debug_print (lazy "FINE TYPE_OF_AUX") ; flush stderr ; res
1973 *)
1974
1975 (* is a small constructor? *)
1976 (*CSC: ottimizzare calcolando staticamente *)
1977 and is_small_or_non_informative ~condition ~logger context paramsno c ugraph =
1978  let rec is_small_or_non_informative_aux ~logger context c ugraph =
1979   let module C = Cic in
1980    match CicReduction.whd context c with
1981       C.Prod (n,so,de) ->
1982        let s,ugraph1 = type_of_aux' ~logger [] context so ugraph in
1983        let b = condition s in
1984        if b then
1985          is_small_or_non_informative_aux
1986           ~logger ((Some (n,(C.Decl so)))::context) de ugraph1
1987        else 
1988                 false,ugraph1
1989     | _ -> true,ugraph (*CSC: we trust the type-checker *)
1990  in
1991   let (context',dx) = split_prods ~subst:[] context paramsno c in
1992    is_small_or_non_informative_aux ~logger context' dx ugraph
1993
1994 and is_small ~logger =
1995  is_small_or_non_informative
1996   ~condition:(fun s -> s=Cic.Sort Cic.Prop || s=Cic.Sort Cic.Set)
1997   ~logger
1998
1999 and is_non_informative ~logger =
2000  is_small_or_non_informative
2001   ~condition:(fun s -> s=Cic.Sort Cic.Prop)
2002   ~logger
2003
2004 and type_of ~logger t ugraph =
2005 (*CSC
2006 debug_print (lazy ("INIZIO TYPE_OF_AUX' " ^ CicPp.ppterm t)) ; flush stderr ;
2007 let res =
2008 *)
2009  type_of_aux' ~logger [] [] t ugraph 
2010 (*CSC
2011 in debug_print (lazy "FINE TYPE_OF_AUX'") ; flush stderr ; res
2012 *)
2013 ;;
2014
2015 let typecheck_obj0 ~logger uri (obj,unchecked_ugraph) =
2016  let module C = Cic in
2017  let ugraph = CicUniv.empty_ugraph in
2018  let inferred_ugraph =
2019    match obj with
2020     | C.Constant (_,Some te,ty,_,_) ->
2021         let _,ugraph = type_of ~logger ty ugraph in
2022         let ty_te,ugraph = type_of ~logger te ugraph in
2023         let b,ugraph = (CicReduction.are_convertible [] ty_te ty ugraph) in
2024          if not b then
2025            raise (TypeCheckerFailure
2026             (lazy
2027               ("the type of the body is not the one expected:\n" ^
2028                CicPp.ppterm ty_te ^ "\nvs\n" ^
2029                CicPp.ppterm ty)))
2030          else
2031           ugraph
2032      | C.Constant (_,None,ty,_,_) ->
2033         (* only to check that ty is well-typed *)
2034         let _,ugraph = type_of ~logger ty ugraph in
2035          ugraph
2036      | C.CurrentProof (_,conjs,te,ty,_,_) ->
2037         (* this block is broken since the metasenv should 
2038          * be topologically sorted before typing metas *)
2039         ignore(assert false);
2040         let _,ugraph =
2041          List.fold_left
2042           (fun (metasenv,ugraph) ((_,context,ty) as conj) ->
2043             let _,ugraph = 
2044              type_of_aux' ~logger metasenv context ty ugraph 
2045             in
2046              metasenv @ [conj],ugraph
2047           ) ([],ugraph) conjs
2048         in
2049          let _,ugraph = type_of_aux' ~logger conjs [] ty ugraph in
2050          let type_of_te,ugraph = 
2051           type_of_aux' ~logger conjs [] te ugraph
2052          in
2053          let b,ugraph = CicReduction.are_convertible [] type_of_te ty ugraph in
2054           if not b then
2055             raise (TypeCheckerFailure (lazy (sprintf
2056              "the current proof is not well typed because the type %s of the body is not convertible to the declared type %s"
2057              (CicPp.ppterm type_of_te) (CicPp.ppterm ty))))
2058           else
2059            ugraph
2060      | C.Variable (_,bo,ty,_,_) ->
2061         (* only to check that ty is well-typed *)
2062         let _,ugraph = type_of ~logger ty ugraph in
2063          (match bo with
2064              None -> ugraph
2065            | Some bo ->
2066               let ty_bo,ugraph = type_of ~logger bo ugraph in
2067                 let b,ugraph = CicReduction.are_convertible [] ty_bo ty ugraph in
2068                if not b then
2069                 raise (TypeCheckerFailure
2070                  (lazy "the body is not the one expected"))
2071                else
2072                 ugraph
2073               )
2074      | (C.InductiveDefinition _ as obj) ->
2075         check_mutual_inductive_defs ~logger uri obj ugraph
2076  in
2077    check_and_clean_ugraph inferred_ugraph unchecked_ugraph uri obj
2078 ;;
2079
2080 let typecheck uri =
2081  let module C = Cic in
2082  let module R = CicReduction in
2083  let module U = UriManager in
2084  let logger = new CicLogger.logger in
2085    match CicEnvironment.is_type_checked ~trust:false CicUniv.empty_ugraph uri with
2086    | CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
2087    | CicEnvironment.UncheckedObj (uobj,unchecked_ugraph) ->
2088       (* let's typecheck the uncooked object *)
2089       logger#log (`Start_type_checking uri) ;
2090       let ugraph, ul, obj = typecheck_obj0 ~logger uri (uobj,unchecked_ugraph) in
2091       CicEnvironment.set_type_checking_info uri (obj,ugraph,ul);
2092       logger#log (`Type_checking_completed uri);
2093       match CicEnvironment.is_type_checked ~trust:false CicUniv.empty_ugraph uri with
2094       | CicEnvironment.CheckedObj (cobj,ugraph') -> cobj,ugraph'
2095       | _ -> raise CicEnvironmentError
2096 ;;
2097
2098 let typecheck_obj ~logger uri obj =
2099  let ugraph,univlist,obj = typecheck_obj0 ~logger uri (obj,None) in
2100  CicEnvironment.add_type_checked_obj uri (obj,ugraph,univlist)
2101
2102 (** wrappers which instantiate fresh loggers *)
2103
2104 let profiler = HExtlib.profile "K/CicTypeChecker.type_of_aux'"
2105
2106 let type_of_aux' ?(subst = []) metasenv context t ugraph =
2107   let logger = new CicLogger.logger in
2108   profiler.HExtlib.profile 
2109     (type_of_aux' ~logger ~subst metasenv context t) ugraph
2110
2111 let typecheck_obj uri obj =
2112  let logger = new CicLogger.logger in
2113  typecheck_obj ~logger uri obj
2114
2115 (* check_allowed_sort_elimination uri i s1 s2
2116    This function is used outside the kernel to determine in advance whether
2117    a MutCase will be allowed or not.
2118    [uri,i] is the type of the term to match
2119    [s1] is the sort of the term to eliminate (i.e. the head of the arity
2120         of the inductive type [uri,i])
2121    [s2] is the sort of the goal (i.e. the head of the type of the outtype
2122         of the MutCase) *)
2123 let check_allowed_sort_elimination uri i s1 s2 =
2124  fst (check_allowed_sort_elimination ~subst:[] ~metasenv:[]
2125   ~logger:(new CicLogger.logger) [] uri i true
2126   (Cic.Implicit None) (* never used *) (Cic.Sort s1) (Cic.Sort s2)
2127   CicUniv.empty_ugraph)
2128 ;;
2129
2130 Deannotate.type_of_aux' :=
2131  fun context t ->
2132   ignore (
2133   List.fold_right
2134    (fun el context ->
2135       (match el with
2136           None -> ()
2137         | Some (_,Cic.Decl ty) ->
2138            ignore (type_of_aux' [] context ty CicUniv.empty_ugraph)
2139         | Some (_,Cic.Def (bo,ty)) ->
2140            ignore (type_of_aux' [] context ty CicUniv.empty_ugraph);
2141            ignore (type_of_aux' [] context bo CicUniv.empty_ugraph));
2142       el::context
2143    ) context []);
2144   fst (type_of_aux' [] context t CicUniv.empty_ugraph);;