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