]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
New tactic clear; new syntax # _; to introduce and immediately clear an
[helm.git] / helm / software / components / ng_refiner / nCicRefiner.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 exception RefineFailure of (Stdpp.location * string) Lazy.t;;
15 exception Uncertain of (Stdpp.location * string) Lazy.t;;
16 exception AssertFailure of string Lazy.t;;
17
18 module C = NCic
19 module Ref = NReference
20
21 let indent = ref "";;
22 let inside c = indent := !indent ^ String.make 1 c;;
23 let outside () = indent := String.sub !indent 0 (String.length !indent -1);;
24
25
26 let pp s = 
27   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
28 ;;  
29
30 let pp _ = ();;
31
32 let wrap_exc msg = function
33   | NCicUnification.Uncertain _ -> Uncertain msg
34   | NCicUnification.UnificationFailure _ -> RefineFailure msg
35   | NCicTypeChecker.TypeCheckerFailure _ -> RefineFailure msg
36   | e -> raise e
37 ;;
38
39 let exp_implicit metasenv context expty =
40  let foo x = match expty with Some t -> `WithType t | None -> x in
41  function      
42   | `Closed -> NCicMetaSubst.mk_meta metasenv [] (foo `Term)
43   | `Type -> NCicMetaSubst.mk_meta metasenv context (foo `Type)
44   | `Term -> NCicMetaSubst.mk_meta metasenv context (foo `Term)
45   | _ -> assert false
46 ;;
47
48
49 let check_allowed_sort_elimination hdb localise r orig =
50    let mkapp he arg =
51      match he with
52      | C.Appl l -> C.Appl (l @ [arg])
53      | t -> C.Appl [t;arg] in
54    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
55    let rec aux metasenv subst context ind arity1 arity2 =
56      (*D*)inside 'S'; try let rc = 
57      let arity1 = NCicReduction.whd ~subst context arity1 in
58      pp (lazy(NCicPp.ppterm ~subst ~metasenv ~context arity1 ^ "   elimsto   " ^
59         NCicPp.ppterm ~subst ~metasenv ~context arity2 ^ "\nMENV:\n"^
60         NCicPp.ppmetasenv ~subst metasenv));
61      match arity1 with
62      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
63         let metasenv, _, meta, _ = 
64           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `Type 
65         in
66         let metasenv, subst = 
67           try NCicUnification.unify hdb metasenv subst context 
68                 arity2 (C.Prod (name, so1, meta)) 
69           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
70             "expected %s, found %s" (* XXX localizzare meglio *)
71             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod (name, so1, meta)))
72             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
73         in
74         aux metasenv subst ((name, C.Decl so1)::context)
75          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
76      | C.Sort _ (* , t ==?== C.Prod _ *) ->
77         let metasenv, _, meta, _ = NCicMetaSubst.mk_meta metasenv [] `Type in
78         let metasenv, subst = 
79           try NCicUnification.unify hdb metasenv subst context 
80                 arity2 (C.Prod ("_", ind, meta)) 
81           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
82             "expected %s, found %s" (* XXX localizzare meglio *)
83             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta)))
84             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
85         in
86         (try NCicTypeChecker.check_allowed_sort_elimination
87             ~metasenv ~subst r context ind arity1 arity2; 
88             metasenv, subst
89         with exc -> raise (wrap_exc (lazy (localise orig, 
90           "Sort elimination not allowed ")) exc))
91      | _ -> assert false
92      (*D*)in outside(); rc with exc -> outside (); raise exc
93    in
94     aux
95 ;;
96
97 let rec typeof hdb 
98   ?(localise=fun _ -> Stdpp.dummy_loc) 
99   ~look_for_coercion metasenv subst context term expty 
100 =
101   let force_ty skip_lambda metasenv subst context orig t infty expty =
102     (*D*)inside 'F'; try let rc = 
103     match expty with
104     | Some expty ->
105        (match t with
106        | C.Implicit _ -> assert false
107        | C.Lambda _ when skip_lambda -> metasenv, subst, t, expty
108        | _ ->
109           pp (lazy (
110           (NCicPp.ppterm ~metasenv ~subst ~context infty) ^  " === " ^
111           (NCicPp.ppterm ~metasenv ~subst:[] ~context expty)));
112            try 
113              let metasenv, subst =
114                NCicUnification.unify hdb metasenv subst context infty expty 
115              in
116              metasenv, subst, t, expty
117            with exc -> 
118              try_coercions hdb ~look_for_coercion ~localise 
119                metasenv subst context t orig infty expty true exc)
120     | None -> metasenv, subst, t, infty
121     (*D*)in outside(); rc with exc -> outside (); raise exc
122   in
123   let rec typeof_aux metasenv subst context expty = 
124     fun t as orig -> 
125     (*D*)inside 'R'; try let rc = 
126     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t));
127     pp (lazy (if expty = None then "NONE" else "SOME"));
128     if (List.exists (fun (i,_) -> i=29) subst) then 
129       pp (lazy (NCicPp.ppsubst ~metasenv subst));
130     let metasenv, subst, t, infty = 
131     match t with
132     | C.Rel n ->
133         let infty = 
134          (try
135            match List.nth context (n - 1) with
136            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
137            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
138          with Failure _ -> 
139            raise (RefineFailure (lazy (localise t,"unbound variable"))))
140         in
141         metasenv, subst, t, infty
142     | C.Sort (C.Type [false,u]) -> metasenv,subst,t,(C.Sort (C.Type [true, u]))
143     | C.Sort (C.Type _) -> 
144         raise (AssertFailure (lazy ("Cannot type an inferred type: "^
145           NCicPp.ppterm ~subst ~metasenv ~context t)))
146     | C.Sort _ -> metasenv,subst,t,(C.Sort (C.Type NCicEnvironment.type0))
147     | C.Implicit infos -> 
148          let metasenv,_,t,ty = exp_implicit metasenv context expty infos in
149          metasenv, subst, t, ty 
150     | C.Meta (n,l) as t -> 
151        let ty =
152         try
153          let _,_,_,ty = NCicUtils.lookup_subst n subst in ty 
154         with NCicUtils.Subst_not_found _ -> try
155          let _,_,ty = NCicUtils.lookup_meta n metasenv in 
156          match ty with C.Implicit _ -> 
157                  prerr_endline (string_of_int n);
158                  prerr_endline (NCicPp.ppmetasenv ~subst metasenv);
159                  prerr_endline (NCicPp.ppsubst ~metasenv subst);
160                  assert false | _ -> ty 
161         with NCicUtils.Meta_not_found _ ->
162          raise (AssertFailure (lazy (Printf.sprintf
163           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
164        in
165        metasenv, subst, t, NCicSubstitution.subst_meta l ty
166     | C.Const _ -> 
167        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
168     | C.Prod (name,(s as orig_s),(t as orig_t)) ->
169        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
170        let metasenv, subst, s, s1 = 
171          force_to_sort hdb ~look_for_coercion
172            metasenv subst context s orig_s localise s1 in
173        let context1 = (name,(C.Decl s))::context in
174        let metasenv, subst, t, s2 = typeof_aux metasenv subst context1 None t in
175        let metasenv, subst, t, s2 = 
176          force_to_sort hdb ~look_for_coercion
177            metasenv subst context1 t orig_t localise s2 in
178        let metasenv, subst, s, t, ty = 
179          sort_of_prod localise metasenv subst 
180            context orig_s orig_t (name,s) t (s1,s2)
181        in
182        metasenv, subst, NCic.Prod(name,s,t), ty
183     | C.Lambda (n,(s as orig_s),t) as orig ->
184        let exp_s, exp_ty_t, force_after =
185          match expty with
186          | None -> None, None, false
187          | Some expty -> 
188              match NCicReduction.whd ~subst context expty with
189              | C.Prod (_,s,t) -> Some s, Some t, false
190              | _ -> None, None, true 
191        in
192        let metasenv, subst, s, ty_s = 
193          typeof_aux metasenv subst context None s in
194        let metasenv, subst, s, _ = 
195          force_to_sort hdb ~look_for_coercion
196            metasenv subst context s orig_s localise ty_s in
197        let (metasenv,subst), exp_ty_t = 
198          match exp_s with 
199          | Some exp_s -> 
200              (try NCicUnification.unify hdb metasenv subst context s exp_s,exp_ty_t
201              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
202                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
203                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
204                exp_s))) exc))
205          | None -> (metasenv, subst), None
206        in
207        let context_for_t = (n,C.Decl s) :: context in
208        let metasenv, subst, t, ty_t = 
209          typeof_aux metasenv subst context_for_t exp_ty_t t 
210        in
211        if force_after then
212          force_ty false metasenv subst context orig 
213            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
214        else 
215          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
216     | C.LetIn (n,(ty as orig_ty),t,bo) ->
217        let metasenv, subst, ty, ty_ty = 
218          typeof_aux metasenv subst context None ty in
219        let metasenv, subst, ty, _ = 
220          force_to_sort hdb ~look_for_coercion
221            metasenv subst context ty orig_ty localise ty_ty in
222        let metasenv, subst, t, _ = 
223          typeof_aux metasenv subst context (Some ty) t in
224        let context1 = (n, C.Def (t,ty)) :: context in
225        let metasenv, subst, bo, bo_ty = 
226          typeof_aux metasenv subst context1 None bo 
227        in
228        let bo_ty = NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty in
229        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
230     | C.Appl ((he as orig_he)::(_::_ as args)) ->
231        let upto = 
232          match orig_he with C.Meta _ -> List.length args | _ -> 0
233        in
234        let metasenv, subst, he, ty_he = 
235          typeof_aux metasenv subst context None he in
236        let metasenv, subst, t, ty = 
237          eat_prods hdb ~localise ~look_for_coercion 
238            metasenv subst context orig_he he ty_he args
239        in
240        let t = if upto > 0 then NCicReduction.head_beta_reduce ~upto t else t in
241        metasenv, subst, t, ty
242    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
243    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
244           outtype,(term as orig_term),pl) as orig ->
245       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
246       let _, _, arity, cl = List.nth itl tyno in
247       let constructorsno = List.length cl in
248       let _, metasenv, args = 
249         NCicMetaSubst.saturate metasenv subst context arity 0 in
250       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
251       let metasenv, subst, term, _ = 
252         typeof_aux metasenv subst context (Some ind) term in
253       let parameters, arguments = HExtlib.split_nth leftno args in
254       let outtype =  
255         match outtype with
256         | C.Implicit _ as ot -> 
257              let rec aux = function
258                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
259                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
260              in
261                aux arguments
262         | _ -> outtype
263       in 
264       let metasenv, subst, outtype, outsort = 
265         typeof_aux metasenv subst context None outtype in
266       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
267       let ind =
268         if parameters = [] then C.Const r
269         else C.Appl ((C.Const r)::parameters) in
270       let metasenv, subst, ind, ind_ty = 
271         typeof_aux metasenv subst context None ind in
272       let metasenv, subst = 
273          check_allowed_sort_elimination hdb localise r orig_term metasenv subst 
274            context ind ind_ty outsort 
275       in
276       (* let's check if the type of branches are right *)
277       if List.length pl <> constructorsno then
278        raise (RefineFailure (lazy (localise orig, 
279          "Wrong number of cases in a match")));
280 (*
281       let metasenv, subst =
282         match expty with
283         | None -> metasenv, subst
284         | Some expty -> 
285            NCicUnification.unify hdb metasenv subst context resty expty 
286       in
287 *)
288       let _, metasenv, subst, pl_rev =
289         List.fold_left
290           (fun (j, metasenv, subst, branches) p ->
291               let cons = 
292                 let cons = Ref.mk_constructor j r in
293                 if parameters = [] then C.Const cons
294                 else C.Appl (C.Const cons::parameters)
295               in
296               let metasenv, subst, cons, ty_cons = 
297                 typeof_aux metasenv subst context None cons in
298               let ty_branch = 
299                 NCicTypeChecker.type_of_branch 
300                   ~subst context leftno outtype cons ty_cons in
301               pp (lazy ("TYPEOFBRANCH: " ^
302                NCicPp.ppterm ~metasenv ~subst ~context p ^ " ::: " ^
303                NCicPp.ppterm ~metasenv ~subst ~context ty_branch ));
304               let metasenv, subst, p, _ = 
305                 typeof_aux metasenv subst context (Some ty_branch) p in
306               j+1, metasenv, subst, p :: branches)
307           (1, metasenv, subst, []) pl
308       in
309       let resty = C.Appl (outtype::arguments@[term]) in
310       let resty = NCicReduction.head_beta_reduce ~subst resty in
311       metasenv, subst, C.Match (r, outtype, term, List.rev pl_rev),resty
312     | C.Match _ -> assert false
313     in
314     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " :: "^
315          NCicPp.ppterm ~metasenv ~subst ~context infty ));
316       force_ty true metasenv subst context orig t infty expty
317     (*D*)in outside(); rc with exc -> outside (); raise exc
318   in
319     typeof_aux metasenv subst context expty term
320
321 and try_coercions hdb 
322   ~localise ~look_for_coercion 
323   metasenv subst context t orig_t infty expty perform_unification exc 
324 =
325   (* we try with a coercion *)
326   let rec first exc = function
327   | [] ->         
328       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
329         "The term %s has type %s but is here used with type %s"
330         (NCicPp.ppterm ~metasenv ~subst ~context t)
331         (NCicPp.ppterm ~metasenv ~subst ~context infty)
332         (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
333   | (metasenv, newterm, newtype, meta)::tl ->
334       try 
335           pp (lazy ( "UNIFICATION in CTX:\n"^ 
336             NCicPp.ppcontext ~metasenv ~subst context
337             ^ "\nMENV: " ^
338             NCicPp.ppmetasenv metasenv ~subst
339             ^ "\nOF: " ^
340             NCicPp.ppterm ~metasenv ~subst ~context meta ^  " === " ^
341             NCicPp.ppterm ~metasenv ~subst ~context t ^ "\n"));
342         let metasenv, subst = 
343           NCicUnification.unify hdb metasenv subst context meta t
344         in
345           pp (lazy ( "UNIFICATION in CTX:\n"^ 
346             NCicPp.ppcontext ~metasenv ~subst context
347             ^ "\nMENV: " ^
348             NCicPp.ppmetasenv metasenv ~subst
349             ^ "\nOF: " ^
350             NCicPp.ppterm ~metasenv ~subst ~context newtype ^  " === " ^
351             NCicPp.ppterm ~metasenv ~subst ~context expty ^ "\n"));
352         let metasenv, subst = 
353           if perform_unification then
354             NCicUnification.unify hdb metasenv subst context newtype expty
355           else metasenv, subst
356         in
357         metasenv, subst, newterm, newtype
358       with 
359       | NCicUnification.UnificationFailure _ -> first exc tl
360       | NCicUnification.Uncertain _ as exc -> first exc tl
361   in 
362     first exc
363       (look_for_coercion metasenv subst context infty expty)
364
365 and force_to_sort hdb 
366   ~look_for_coercion metasenv subst context t orig_t localise ty 
367 =
368   match NCicReduction.whd ~subst context ty with
369   | C.Meta (_,(0,(C.Irl 0 | C.Ctx []))) as ty -> 
370      metasenv, subst, t, ty
371   | C.Meta (i,(_,(C.Irl 0 | C.Ctx []))) -> 
372      metasenv, subst, t, C.Meta(i,(0,C.Irl 0))
373   | C.Meta (i,(_,lc)) ->
374      let len = match lc with C.Irl len->len | C.Ctx l->List.length l in
375      let metasenv, subst, newmeta = 
376        if len > 0 then
377          NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 (len+1)) 
378        else metasenv, subst, i
379      in
380      metasenv, subst, t, C.Meta (newmeta,(0,C.Irl 0))
381   | C.Sort _ as ty -> metasenv, subst, t, ty 
382   | ty -> 
383       try_coercions hdb ~localise ~look_for_coercion metasenv subst context
384         t orig_t ty (NCic.Sort (NCic.Type NCicEnvironment.type0)) false 
385          (Uncertain (lazy (localise orig_t, 
386          "The type of " ^ NCicPp.ppterm ~metasenv ~subst ~context t
387          ^ " is not a sort: " ^ NCicPp.ppterm ~metasenv ~subst ~context ty)))
388
389 and sort_of_prod 
390   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
391 =
392    (* force to sort is done in the Prod case in typeof *)
393    match t1, t2 with
394    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
395    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
396         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
397    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
398    | C.Meta _, C.Sort _ 
399    | C.Meta _, C.Meta (_,(_,_))
400    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
401    | x, (C.Sort _ | C.Meta _) | _, x -> 
402       let y, context, orig = 
403         if x == t1 then s, context, orig_s 
404         else t, ((name,C.Decl s)::context), orig_t
405       in
406       raise (RefineFailure (lazy (localise orig,Printf.sprintf
407         "%s is expected to be a type, but its type is %s that is not a sort" 
408          (NCicPp.ppterm ~subst ~metasenv ~context y) 
409          (NCicPp.ppterm ~subst ~metasenv ~context x))))
410
411 and eat_prods hdb
412   ~localise ~look_for_coercion metasenv subst context orig_he he ty_he args 
413 =
414   (*D*)inside 'E'; try let rc = 
415   let rec aux metasenv subst args_so_far he ty_he = function 
416   | []->metasenv, subst, NCicUntrusted.mk_appl he (List.rev args_so_far), ty_he
417   | arg::tl ->
418       match NCicReduction.whd ~subst context ty_he with 
419       | C.Prod (_,s,t) ->
420           let metasenv, subst, arg, _ = 
421             typeof hdb ~look_for_coercion ~localise 
422               metasenv subst context arg (Some s) in
423           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
424           aux metasenv subst (arg :: args_so_far) he t tl
425       | C.Meta _
426       | C.Appl (C.Meta _ :: _) as t ->
427           let metasenv, subst, arg, ty_arg = 
428             typeof hdb ~look_for_coercion ~localise 
429               metasenv subst context arg None in
430           let metasenv, _, meta, _ = 
431             NCicMetaSubst.mk_meta metasenv 
432               (("_",C.Decl ty_arg) :: context) `Type
433           in
434           let flex_prod = C.Prod ("_", ty_arg, meta) in
435           (* next line grants that ty_args is a type *)
436           let metasenv,subst, flex_prod, _ =
437            typeof hdb ~look_for_coercion ~localise metasenv subst
438             context flex_prod None in
439           pp (lazy ( "UNIFICATION in CTX:\n"^ 
440             NCicPp.ppcontext ~metasenv ~subst context
441             ^ "\nOF: " ^
442             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
443             NCicPp.ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
444           let metasenv, subst = 
445              try NCicUnification.unify hdb metasenv subst context t flex_prod 
446              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
447               ("The term %s has an inferred type %s, but is applied to the" ^^
448                " argument %s of type %s")
449               (NCicPp.ppterm ~metasenv ~subst ~context he)
450               (NCicPp.ppterm ~metasenv ~subst ~context t)
451               (NCicPp.ppterm ~metasenv ~subst ~context arg)
452               (NCicPp.ppterm ~metasenv ~subst ~context ty_arg))) exc)
453               (* XXX coerce to funclass *)
454           in
455           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
456           aux metasenv subst (arg :: args_so_far) he meta tl
457       | C.Match (_,_,C.Meta _,_) 
458       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
459       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
460           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
461             ("The term %s is here applied to %d arguments but expects " ^^
462             "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
463             (List.length args) (List.length args_so_far))))
464       | ty ->
465           let metasenv, subst, newhead, newheadty = 
466             try_coercions hdb ~localise ~look_for_coercion metasenv subst context
467               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
468               (NCic.Prod ("_",NCic.Implicit `Term,NCic.Implicit `Term))
469               false
470               (RefineFailure (lazy (localise orig_he, Printf.sprintf
471                ("The term %s is here applied to %d arguments but expects " ^^
472                "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
473                (List.length args) (List.length args_so_far))))
474           in
475           aux metasenv subst [] newhead newheadty (arg :: tl)
476   in
477    aux metasenv subst [] he ty_he args
478   (*D*)in outside(); rc with exc -> outside (); raise exc
479 ;;
480
481 let rec first f l1 l2 =
482   match l1,l2 with
483   | x1::tl1, x2::tl2 -> 
484       (try f x1 x2 with Not_found -> first f tl1 tl2)
485   | _ -> raise Not_found
486 ;;
487
488 let rec find add dt t =
489   if dt == add then t
490   else
491     let dl, l = 
492       match dt, t with
493       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
494       | C.Appl dl,C.Appl l -> dl,l
495       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
496       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
497       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
498       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
499       | _ -> raise Not_found
500     in
501       first (find add) dl l
502 ;;
503
504 let relocalise old_localise dt t add = 
505   old_localise 
506     (try find add dt t with Not_found -> assert false)
507 ;;
508
509 let undebruijnate inductive ref t rev_fl =
510   NCicSubstitution.psubst (fun x -> x) 
511     (HExtlib.list_mapi 
512       (fun (_,_,rno,_,_,_) i -> 
513          NCic.Const 
514            (if inductive then NReference.mk_fix i rno ref
515             else NReference.mk_cofix i ref))
516       rev_fl)
517     t
518 ;; 
519
520
521 let typeof_obj hdb 
522   ?(localise=fun _ -> Stdpp.dummy_loc) 
523   ~look_for_coercion (uri,height,metasenv,subst, obj)
524
525   let check_type metasenv subst (ty as orig_ty) =  (* XXX fattorizza *)
526     let metasenv, subst, ty, sort = 
527       typeof hdb ~localise ~look_for_coercion metasenv subst [] ty None
528     in
529     let metasenv, subst, ty, _ = 
530       force_to_sort hdb ~look_for_coercion 
531         metasenv subst [] ty orig_ty localise sort
532     in
533       metasenv, subst, ty
534   in
535   match obj with 
536   | C.Constant (relevance, name, bo, ty , attr) ->
537        let metasenv, subst, ty = check_type metasenv subst ty in
538        let metasenv, subst, bo, ty, height = 
539          match bo with
540          | Some bo ->
541              let metasenv, subst, bo, ty = 
542                typeof hdb ~localise ~look_for_coercion 
543                  metasenv subst [] bo (Some ty)
544              in
545              let height = (* XXX recalculate *) height in
546                metasenv, subst, Some bo, ty, height
547          | None -> metasenv, subst, None, ty, 0
548        in
549        uri, height, metasenv, subst, 
550          C.Constant (relevance, name, bo, ty, attr)
551   | C.Fixpoint (inductive, fl, attr) -> 
552       let len = List.length fl in
553       let types, metasenv, subst, rev_fl =
554         List.fold_left
555          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
556            let metasenv, subst, ty = check_type metasenv subst ty in
557            let dbo = NCicTypeChecker.debruijn uri len [] bo in
558            let localise = relocalise localise dbo bo in
559             (name,C.Decl ty)::types,
560               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
561          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
562       in
563       let metasenv, subst, fl = 
564         List.fold_left 
565           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
566             let metasenv, subst, dbo, ty = 
567               typeof hdb ~localise ~look_for_coercion 
568                 metasenv subst types dbo (Some ty)
569             in
570             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
571           (metasenv, subst, []) rev_fl
572       in
573       let height = (* XXX recalculate *) height in
574       let fl =
575         List.map 
576           (fun (relevance,name,k,ty,dbo) ->
577             let bo = 
578               undebruijnate inductive 
579                (NReference.reference_of_spec uri 
580                  (if inductive then NReference.Fix (0,k,0) 
581                   else NReference.CoFix 0)) dbo rev_fl
582             in
583               relevance,name,k,ty,bo)
584           fl
585       in
586        uri, height, metasenv, subst, 
587          C.Fixpoint (inductive, fl, attr)
588
589   | C.Inductive (_ind, _leftno, _itl, _attr) ->  assert false
590 (*
591   (* let's check if the arity of the inductive types are well formed *)
592   List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
593   (* let's check if the types of the inductive constructors are well formed. *)
594   let len = List.length tyl in
595   let tys = List.rev_map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl in
596   ignore
597    (List.fold_right
598     (fun (it_relev,_,ty,cl) i ->
599        let context,ty_sort = split_prods ~subst [] ~-1 ty in
600        let sx_context_ty_rev,_ = HExtlib.split_nth leftno (List.rev context) in
601        List.iter
602          (fun (k_relev,_,te) ->
603            let _,k_relev = HExtlib.split_nth leftno k_relev in
604            let te = debruijn uri len [] te in
605            let context,te = split_prods ~subst tys leftno te in
606            let _,chopped_context_rev =
607             HExtlib.split_nth (List.length tys) (List.rev context) in
608            let sx_context_te_rev,_ =
609             HExtlib.split_nth leftno chopped_context_rev in
610            (try
611              ignore (List.fold_left2
612               (fun context item1 item2 ->
613                 let convertible =
614                  match item1,item2 with
615                    (n1,C.Decl ty1),(n2,C.Decl ty2) ->
616                      n1 = n2 && 
617                      R.are_convertible ~metasenv ~subst context ty1 ty2
618                  | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
619                      n1 = n2
620                      && R.are_convertible ~metasenv ~subst context ty1 ty2
621                      && R.are_convertible ~metasenv ~subst context bo1 bo2
622                  | _,_ -> false
623                 in
624                  if not convertible then
625                   raise (TypeCheckerFailure (lazy
626                    ("Mismatch between the left parameters of the constructor " ^
627                     "and those of its inductive type")))
628                  else
629                   item1::context
630               ) [] sx_context_ty_rev sx_context_te_rev)
631             with Invalid_argument "List.fold_left2" -> assert false);
632            let con_sort = typeof ~subst ~metasenv context te in
633            (match R.whd ~subst context con_sort, R.whd ~subst [] ty_sort with
634                (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
635                 if not (E.universe_leq u1 u2) then
636                  raise
637                   (TypeCheckerFailure
638                     (lazy ("The type " ^ PP.ppterm ~metasenv ~subst ~context s1^
639                       " of the constructor is not included in the inductive" ^
640                       " type sort " ^ PP.ppterm ~metasenv ~subst ~context s2)))
641              | C.Sort _, C.Sort C.Prop
642              | C.Sort _, C.Sort C.Type _ -> ()
643              | _, _ ->
644                 raise
645                  (TypeCheckerFailure
646                    (lazy ("Wrong constructor or inductive arity shape"))));
647            (* let's check also the positivity conditions *)
648            if 
649              not
650                (are_all_occurrences_positive ~subst context uri leftno
651                  (i+leftno) leftno (len+leftno) te) 
652            then
653              raise
654                (TypeCheckerFailure
655                  (lazy ("Non positive occurence in "^NUri.string_of_uri
656                  uri)))
657            else check_relevance ~subst ~metasenv context k_relev te) 
658          cl;
659         check_relevance ~subst ~metasenv [] it_relev ty;
660         i+1)
661     tyl 1)
662 *)
663
664
665 ;;
666
667
668
669 (* vim:set foldmethod=marker: *)