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