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