]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
some fixes here and there
[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 ~localise metasenv context expty t =
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   | `Vector ->
46       raise (RefineFailure (lazy (localise t, "A vector of implicit terms " ^
47        "can only be used in argument position")))
48   | _ -> assert false
49 ;;
50
51 let check_allowed_sort_elimination rdb localise r orig =
52    let mkapp he arg =
53      match he with
54      | C.Appl l -> C.Appl (l @ [arg])
55      | t -> C.Appl [t;arg] in
56    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
57    let rec aux metasenv subst context ind arity1 arity2 =
58      (*D*)inside 'S'; try let rc = 
59      let arity1 = NCicReduction.whd ~subst context arity1 in
60      pp (lazy(NCicPp.ppterm ~subst ~metasenv ~context arity1 ^ "   elimsto   " ^
61         NCicPp.ppterm ~subst ~metasenv ~context arity2 ^ "\nMENV:\n"^
62         NCicPp.ppmetasenv ~subst metasenv));
63      match arity1 with
64      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
65         let metasenv, _, meta, _ = 
66           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `Type 
67         in
68         let metasenv, subst = 
69           try NCicUnification.unify rdb metasenv subst context 
70                 arity2 (C.Prod (name, so1, meta)) 
71           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
72             "expected %s, found %s" (* XXX localizzare meglio *)
73             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod (name, so1, meta)))
74             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
75         in
76         aux metasenv subst ((name, C.Decl so1)::context)
77          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
78      | C.Sort _ (* , t ==?== C.Prod _ *) ->
79         let metasenv, _, meta, _ = NCicMetaSubst.mk_meta metasenv [] `Type in
80         let metasenv, subst = 
81           try NCicUnification.unify rdb metasenv subst context 
82                 arity2 (C.Prod ("_", ind, meta)) 
83           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
84             "expected %s, found %s" (* XXX localizzare meglio *)
85             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta)))
86             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
87         in
88         (try NCicTypeChecker.check_allowed_sort_elimination
89             ~metasenv ~subst r context ind arity1 arity2; 
90             metasenv, subst
91         with exc -> raise (wrap_exc (lazy (localise orig, 
92           "Sort elimination not allowed ")) exc))
93      | _ -> assert false
94      (*D*)in outside(); rc with exc -> outside (); raise exc
95    in
96     aux
97 ;;
98
99 let rec typeof rdb 
100   ?(localise=fun _ -> Stdpp.dummy_loc) 
101   metasenv subst context term expty 
102 =
103   let force_ty skip_lambda skip_appl metasenv subst context orig t infty expty =
104     (*D*)inside 'F'; try let rc = 
105     match expty with
106     | Some expty ->
107        (match t with
108        | C.Implicit _ -> assert false
109        | C.Lambda _ when skip_lambda -> metasenv, subst, t, expty
110        | C.Appl _ when skip_appl -> metasenv, subst, t, expty
111        | _ ->
112           pp (lazy (
113           (NCicPp.ppterm ~metasenv ~subst ~context infty) ^  " === " ^
114           (NCicPp.ppterm ~metasenv ~subst:[] ~context expty)));
115            try 
116              let metasenv, subst =
117                NCicUnification.unify rdb metasenv subst context infty expty 
118              in
119              metasenv, subst, t, expty
120            with exc -> 
121              try_coercions rdb ~localise 
122                metasenv subst context t orig infty expty true exc)
123     | None -> metasenv, subst, t, infty
124     (*D*)in outside(); rc with exc -> outside (); raise exc
125   in
126   let rec typeof_aux metasenv subst context expty = 
127     fun t as orig -> 
128     (*D*)inside 'R'; try let rc = 
129     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " expty= " ^
130        match expty with None -> "None" | Some e -> 
131        NCicPp.ppterm ~metasenv ~subst ~context e));
132     let metasenv, subst, t, infty = 
133     match t with
134     | C.Rel n ->
135         let infty = 
136          (try
137            match List.nth context (n - 1) with
138            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
139            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
140          with Failure _ -> 
141            raise (RefineFailure (lazy (localise t,"unbound variable"))))
142         in
143         metasenv, subst, t, infty
144     | C.Sort (C.Type [false,u]) -> metasenv,subst,t,(C.Sort (C.Type [true, u]))
145     | C.Sort (C.Type _) -> 
146         raise (AssertFailure (lazy ("Cannot type an inferred type: "^
147           NCicPp.ppterm ~subst ~metasenv ~context t)))
148     | C.Sort _ -> metasenv,subst,t,(C.Sort (C.Type NCicEnvironment.type0))
149     | C.Implicit infos -> 
150          let metasenv,_,t,ty =
151            exp_implicit ~localise metasenv context expty t infos
152          in
153           metasenv, subst, t, ty 
154     | C.Meta (n,l) as t -> 
155        let ty =
156         try
157          let _,_,_,ty = NCicUtils.lookup_subst n subst in ty 
158         with NCicUtils.Subst_not_found _ -> try
159          let _,_,ty = NCicUtils.lookup_meta n metasenv in 
160          match ty with C.Implicit _ -> 
161                  prerr_endline (string_of_int n);
162                  prerr_endline (NCicPp.ppmetasenv ~subst metasenv);
163                  prerr_endline (NCicPp.ppsubst ~metasenv subst);
164                  assert false | _ -> ty 
165         with NCicUtils.Meta_not_found _ ->
166          raise (AssertFailure (lazy (Printf.sprintf
167           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
168        in
169        metasenv, subst, t, NCicSubstitution.subst_meta l ty
170     | C.Const _ -> 
171        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
172     | C.Prod (name,(s as orig_s),(t as orig_t)) ->
173        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
174        let metasenv, subst, s, s1 = 
175          force_to_sort rdb 
176            metasenv subst context s orig_s localise s1 in
177        let context1 = (name,(C.Decl s))::context in
178        let metasenv, subst, t, s2 = typeof_aux metasenv subst context1 None t in
179        let metasenv, subst, t, s2 = 
180          force_to_sort rdb 
181            metasenv subst context1 t orig_t localise s2 in
182        let metasenv, subst, s, t, ty = 
183          sort_of_prod localise metasenv subst 
184            context orig_s orig_t (name,s) t (s1,s2)
185        in
186        metasenv, subst, NCic.Prod(name,s,t), ty
187     | C.Lambda (n,(s as orig_s),t) as orig ->
188        let exp_s, exp_ty_t, force_after =
189          match expty with
190          | None -> None, None, false
191          | Some expty -> 
192              match NCicReduction.whd ~subst context expty with
193              | C.Prod (_,s,t) -> Some s, Some t, false
194              | _ -> None, None, true 
195        in
196        let metasenv, subst, s, ty_s = 
197          typeof_aux metasenv subst context None s in
198        let metasenv, subst, s, _ = 
199          force_to_sort rdb 
200            metasenv subst context s orig_s localise ty_s in
201        let (metasenv,subst), exp_ty_t = 
202          match exp_s with 
203          | Some exp_s -> 
204              (try 
205                pp(lazy("Force source to: "^NCicPp.ppterm ~metasenv ~subst
206                   ~context exp_s));
207                NCicUnification.unify rdb metasenv subst context s exp_s,exp_ty_t
208              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
209                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
210                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
211                exp_s))) exc))
212          | None -> (metasenv, subst), None
213        in
214        let context_for_t = (n,C.Decl s) :: context in
215        let metasenv, subst, t, ty_t = 
216          typeof_aux metasenv subst context_for_t exp_ty_t t 
217        in
218        if force_after then
219          force_ty false true metasenv subst context orig 
220            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
221        else 
222          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
223     | C.LetIn (n,(ty as orig_ty),t,bo) ->
224        let metasenv, subst, ty, ty_ty = 
225          typeof_aux metasenv subst context None ty in
226        let metasenv, subst, ty, _ = 
227          force_to_sort rdb
228            metasenv subst context ty orig_ty localise ty_ty in
229        let metasenv, subst, t, _ = 
230          typeof_aux metasenv subst context (Some ty) t in
231        let context1 = (n, C.Def (t,ty)) :: context in
232        let metasenv, subst, bo, bo_ty = 
233          typeof_aux metasenv subst context1 None bo 
234        in
235        let bo_ty = NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty in
236        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
237     | C.Appl ((he as orig_he)::(_::_ as args)) ->
238        let upto = match orig_he with C.Meta _ -> List.length args | _ -> 0 in
239        let hbr t = 
240          if upto > 0 then NCicReduction.head_beta_reduce ~upto t else t 
241        in
242        let refine_appl () =
243          let metasenv, subst, he, ty_he = 
244             typeof_aux metasenv subst context None he in
245          let metasenv, subst, t, ty = 
246            eat_prods rdb ~localise force_ty metasenv subst context expty t
247             orig_he he ty_he args in
248          metasenv, subst, hbr t, ty
249        in
250        if args = [C.Implicit `Vector] && expty <> None then
251          (* we try here to expand the vector a 0 implicits, but we use
252           * the expected type *)
253          try
254            let metasenv, subst, he, ty_he = 
255               typeof_aux metasenv subst context expty he in
256            metasenv, subst, hbr he, ty_he
257          with Uncertain _ | RefineFailure _ -> refine_appl ()
258        else refine_appl ()
259    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
260    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
261           outtype,(term as orig_term),pl) as orig ->
262       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
263       let _, _, arity, cl = List.nth itl tyno in
264       let constructorsno = List.length cl in
265       let _, metasenv, args = 
266         NCicMetaSubst.saturate metasenv subst context arity 0 in
267       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
268       let metasenv, subst, term, _ = 
269         typeof_aux metasenv subst context (Some ind) term in
270       let parameters, arguments = HExtlib.split_nth leftno args in
271       let outtype =  
272         match outtype with
273         | C.Implicit _ as ot -> 
274              let rec aux = function
275                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
276                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
277              in
278                aux arguments
279         | _ -> outtype
280       in 
281       let metasenv, subst, outtype, outsort = 
282         typeof_aux metasenv subst context None outtype in
283
284       (* next lines are to do a subst-expansion of the outtype, so
285          that when it becomes a beta-abstraction, the beta-redex is
286          fired during substitution *)
287       (*CSC: this is instantiate! should we move it from tactics to the
288              refiner? I think so! *)
289       let metasenv,metanoouttype,newouttype,metaoutsort =
290        NCicMetaSubst.mk_meta metasenv context `Term in
291       let metasenv,subst =
292        NCicUnification.unify rdb metasenv subst context outsort metaoutsort in
293       let metasenv =
294        List.filter (function (j,_) -> j <> metanoouttype) metasenv in
295       let subst =
296        (metanoouttype,(Some "outtype",context,outtype,metaoutsort))::subst in
297       let outtype = newouttype in
298
299       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
300       let ind =
301         if parameters = [] then C.Const r
302         else C.Appl ((C.Const r)::parameters) in
303       let metasenv, subst, ind, ind_ty = 
304         typeof_aux metasenv subst context None ind in
305       let metasenv, subst = 
306          check_allowed_sort_elimination rdb localise r orig_term metasenv subst 
307            context ind ind_ty outsort 
308       in
309       (* let's check if the type of branches are right *)
310       if List.length pl <> constructorsno then
311        raise (RefineFailure (lazy (localise orig, 
312          "Wrong number of cases in a match")));
313 (*
314       let metasenv, subst =
315         match expty with
316         | None -> metasenv, subst
317         | Some expty -> 
318            NCicUnification.unify rdb metasenv subst context resty expty 
319       in
320 *)
321       let _, metasenv, subst, pl =
322         List.fold_right
323           (fun p (j, metasenv, subst, branches) ->
324               let cons = 
325                 let cons = Ref.mk_constructor j r in
326                 if parameters = [] then C.Const cons
327                 else C.Appl (C.Const cons::parameters)
328               in
329               let metasenv, subst, cons, ty_cons = 
330                 typeof_aux metasenv subst context None cons in
331               let ty_branch = 
332                 NCicTypeChecker.type_of_branch 
333                   ~subst context leftno outtype cons ty_cons in
334               pp (lazy ("TYPEOFBRANCH: " ^
335                NCicPp.ppterm ~metasenv ~subst ~context p ^ " ::: " ^
336                NCicPp.ppterm ~metasenv ~subst ~context ty_branch ));
337               let metasenv, subst, p, _ = 
338                 typeof_aux metasenv subst context (Some ty_branch) p in
339               j-1, metasenv, subst, p :: branches)
340           pl (List.length pl, metasenv, subst, [])
341       in
342       let resty = C.Appl (outtype::arguments@[term]) in
343       let resty = NCicReduction.head_beta_reduce ~subst resty in
344       metasenv, subst, C.Match (r, outtype, term, pl),resty
345     | C.Match _ -> assert false
346     in
347     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " :: "^
348          NCicPp.ppterm ~metasenv ~subst ~context infty ));
349       force_ty true true metasenv subst context orig t infty expty
350     (*D*)in outside(); rc with exc -> outside (); raise exc
351   in
352     typeof_aux metasenv subst context expty term
353
354 and try_coercions rdb 
355   ~localise 
356   metasenv subst context t orig_t infty expty perform_unification exc 
357 =
358   (* we try with a coercion *)
359   let rec first exc = function
360   | [] ->         
361       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
362         "The term %s has type %s but is here used with type %s"
363         (NCicPp.ppterm ~metasenv ~subst ~context t)
364         (NCicPp.ppterm ~metasenv ~subst ~context infty)
365         (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
366   | (_,metasenv, newterm, newtype, meta)::tl ->
367       try 
368           pp (lazy ( "UNIFICATION in CTX:\n"^ 
369             NCicPp.ppcontext ~metasenv ~subst context
370             ^ "\nMENV: " ^
371             NCicPp.ppmetasenv metasenv ~subst
372             ^ "\nOF: " ^
373             NCicPp.ppterm ~metasenv ~subst ~context meta ^  " === " ^
374             NCicPp.ppterm ~metasenv ~subst ~context t ^ "\n"));
375         let metasenv, subst = 
376           NCicUnification.unify rdb metasenv subst context meta t
377         in
378           pp (lazy ( "UNIFICATION in CTX:\n"^ 
379             NCicPp.ppcontext ~metasenv ~subst context
380             ^ "\nMENV: " ^
381             NCicPp.ppmetasenv metasenv ~subst
382             ^ "\nOF: " ^
383             NCicPp.ppterm ~metasenv ~subst ~context newtype ^  " === " ^
384             NCicPp.ppterm ~metasenv ~subst ~context expty ^ "\n"));
385         let metasenv, subst = 
386           if perform_unification then
387             NCicUnification.unify rdb metasenv subst context newtype expty
388           else metasenv, subst
389         in
390         metasenv, subst, newterm, newtype
391       with 
392       | NCicUnification.UnificationFailure _ -> first exc tl
393       | NCicUnification.Uncertain _ as exc -> first exc tl
394   in 
395   pp(lazy("try_coercion " ^ 
396     NCicPp.ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
397     NCicPp.ppterm ~metasenv ~subst ~context expty));
398     first exc
399       (NCicCoercion.look_for_coercion 
400         rdb metasenv subst context infty expty)
401
402 and force_to_sort rdb metasenv subst context t orig_t localise ty =
403   match NCicReduction.whd ~subst context ty with
404   | C.Meta (_,(0,(C.Irl 0 | C.Ctx []))) as ty -> 
405      metasenv, subst, t, ty
406   | C.Meta (_i,(_,(C.Irl 0 | C.Ctx []))) -> assert false (*CSC: ???
407      metasenv, subst, t, C.Meta(i,(0,C.Irl 0)) *)
408   | C.Meta (i,(_,lc)) ->
409      let len = match lc with C.Irl len->len | C.Ctx l->List.length l in
410      let metasenv, subst, newmeta = 
411        if len > 0 then
412          NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 (len+1)) 
413        else metasenv, subst, i
414      in
415      metasenv, subst, t, C.Meta (newmeta,(0,C.Irl 0))
416   | C.Sort _ as ty -> metasenv, subst, t, ty 
417   | ty -> 
418       try_coercions rdb ~localise metasenv subst context
419         t orig_t ty (NCic.Sort (NCic.Type NCicEnvironment.type0)) false 
420          (Uncertain (lazy (localise orig_t, 
421          "The type of " ^ NCicPp.ppterm ~metasenv ~subst ~context t
422          ^ " is not a sort: " ^ NCicPp.ppterm ~metasenv ~subst ~context ty)))
423
424 and sort_of_prod 
425   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
426 =
427    (* force to sort is done in the Prod case in typeof *)
428    match t1, t2 with
429    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
430    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
431         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
432    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
433    | C.Meta _, C.Sort _ 
434    | C.Meta _, C.Meta (_,(_,_))
435    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
436    | x, (C.Sort _ | C.Meta _) | _, x -> 
437       let y, context, orig = 
438         if x == t1 then s, context, orig_s 
439         else t, ((name,C.Decl s)::context), orig_t
440       in
441       raise (RefineFailure (lazy (localise orig,Printf.sprintf
442         "%s is expected to be a type, but its type is %s that is not a sort" 
443          (NCicPp.ppterm ~subst ~metasenv ~context y) 
444          (NCicPp.ppterm ~subst ~metasenv ~context x))))
445
446 and guess_name subst ctx ty = 
447   let aux initial = "#" ^ String.make 1 initial in
448   match ty with
449   | C.Const (NReference.Ref (u,_))
450   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
451       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
452   | C.Prod _ -> aux 'f' 
453   | C.Meta (n,lc) -> 
454       (try
455          let _,_,t,_ = NCicUtils.lookup_subst n subst in
456          guess_name subst ctx (NCicSubstitution.subst_meta lc t)
457       with NCicUtils.Subst_not_found _ -> aux 'M')
458   | _ -> aux 'H' 
459
460 and eat_prods rdb ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
461   (*D*)inside 'E'; try let rc = 
462   let rec aux metasenv subst args_so_far he ty_he = function 
463   | [] ->
464      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
465      pp(lazy("FORCE FINAL APPL: " ^ 
466        NCicPp.ppterm ~metasenv ~subst ~context res ^
467        " of type " ^ NCicPp.ppterm ~metasenv ~subst ~context ty_he
468        ^ " to type " ^ match expty with None -> "None" | Some x -> 
469        NCicPp.ppterm ~metasenv ~subst ~context x));
470       force_ty true false metasenv subst context orig_t res ty_he expty
471   | NCic.Implicit `Vector::tl ->
472       let has_some_more_pis x =
473         match NCicReduction.whd ~subst context x with
474         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
475         | _ -> true
476       in
477      (try
478        aux metasenv subst args_so_far he ty_he tl
479       with
480       | Uncertain _
481       | RefineFailure _ as exc when has_some_more_pis ty_he ->
482           (try
483            aux metasenv subst args_so_far he ty_he
484             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
485           with
486            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc)))
487   | arg::tl ->
488       match NCicReduction.whd ~subst context ty_he with 
489       | C.Prod (_,s,t) ->
490           let metasenv, subst, arg, _ = 
491             typeof rdb ~localise 
492               metasenv subst context arg (Some s) in
493           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
494           aux metasenv subst (arg :: args_so_far) he t tl
495       | C.Meta _
496       | C.Appl (C.Meta _ :: _) as t ->
497           let metasenv, subst, arg, ty_arg = 
498             typeof rdb ~localise 
499               metasenv subst context arg None in
500           let name = guess_name subst context ty_arg in
501           let metasenv, _, meta, _ = 
502             NCicMetaSubst.mk_meta metasenv 
503               ((name,C.Decl ty_arg) :: context) `Type
504           in
505           let flex_prod = C.Prod (name, ty_arg, meta) in
506           (* next line grants that ty_args is a type *)
507           let metasenv,subst, flex_prod, _ =
508            typeof rdb ~localise metasenv subst
509             context flex_prod None in
510           pp (lazy ( "UNIFICATION in CTX:\n"^ 
511             NCicPp.ppcontext ~metasenv ~subst context
512             ^ "\nOF: " ^
513             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
514             NCicPp.ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
515           let metasenv, subst =
516              try NCicUnification.unify rdb metasenv subst context t flex_prod 
517              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
518               ("The term %s has an inferred type %s, but is applied to the" ^^
519                " argument %s of type %s")
520               (NCicPp.ppterm ~metasenv ~subst ~context he)
521               (NCicPp.ppterm ~metasenv ~subst ~context t)
522               (NCicPp.ppterm ~metasenv ~subst ~context arg)
523               (NCicPp.ppterm ~metasenv ~subst ~context ty_arg))) exc)
524               (* XXX coerce to funclass *)
525           in
526           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
527           aux metasenv subst (arg :: args_so_far) he meta tl
528       | C.Match (_,_,C.Meta _,_) 
529       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
530       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
531           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
532             ("The term %s is here applied to %d arguments but expects " ^^
533             "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
534             (List.length args) (List.length args_so_far))))
535       | ty ->
536           let metasenv, subst, newhead, newheadty = 
537             try_coercions rdb ~localise metasenv subst context
538               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
539               (NCic.Prod ("_",NCic.Implicit `Term,NCic.Implicit `Term))
540               false
541               (RefineFailure (lazy (localise orig_he, Printf.sprintf
542                ("The term %s is here applied to %d arguments but expects " ^^
543                "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
544                (List.length args) (List.length args_so_far))))
545           in
546            aux metasenv subst [] newhead newheadty (arg :: tl)
547   in
548    (* We need to reverse the order of the new created metas since they
549       are pushed on top of the metasenv in the wrong order *)
550    let highest_meta = NCicMetaSubst.maxmeta () in
551    let metasenv, subst, newhead, newheadty = 
552     aux metasenv subst [] he ty_he args in
553    let metasenv_old,metasenv_new =
554     List.partition (fun (i,_) -> i <= highest_meta) metasenv
555    in
556     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
557   (*D*)in outside(); rc with exc -> outside (); raise exc
558 ;;
559
560 let rec first f l1 l2 =
561   match l1,l2 with
562   | x1::tl1, x2::tl2 -> 
563       (try f x1 x2 with Not_found -> first f tl1 tl2)
564   | _ -> raise Not_found
565 ;;
566
567 let rec find add dt t =
568   if dt == add then t
569   else
570     let dl, l = 
571       match dt, t with
572       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
573       | C.Appl dl,C.Appl l -> dl,l
574       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
575       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
576       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
577       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
578       | _ -> raise Not_found
579     in
580       first (find add) dl l
581 ;;
582
583 let relocalise old_localise dt t add = 
584   old_localise 
585     (try find add dt t with Not_found -> assert false)
586 ;;
587
588 let undebruijnate inductive ref t rev_fl =
589   NCicSubstitution.psubst (fun x -> x) 
590    (List.rev (HExtlib.list_mapi 
591       (fun (_,_,rno,_,_,_) i -> 
592          NCic.Const 
593            (if inductive then NReference.mk_fix i rno ref
594             else NReference.mk_cofix i ref))
595       rev_fl))
596     t
597 ;; 
598
599
600 let typeof_obj 
601   rdb ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
602
603   let check_type metasenv subst context (ty as orig_ty) =  (* XXX fattorizza *)
604     let metasenv, subst, ty, sort = 
605       typeof rdb ~localise metasenv subst context ty None
606     in
607     let metasenv, subst, ty, sort = 
608       force_to_sort rdb metasenv subst context ty orig_ty localise sort
609     in
610       metasenv, subst, ty, sort
611   in
612   match obj with 
613   | C.Constant (relevance, name, bo, ty , attr) ->
614        let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
615        let metasenv, subst, bo, ty, height = 
616          match bo with
617          | Some bo ->
618              let metasenv, subst, bo, ty = 
619                typeof rdb ~localise metasenv subst [] bo (Some ty) in
620              let height = (* XXX recalculate *) height in
621                metasenv, subst, Some bo, ty, height
622          | None -> metasenv, subst, None, ty, 0
623        in
624        uri, height, metasenv, subst, 
625          C.Constant (relevance, name, bo, ty, attr)
626   | C.Fixpoint (inductive, fl, attr) -> 
627       let len = List.length fl in
628       let types, metasenv, subst, rev_fl =
629         List.fold_left
630          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
631            let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
632            let dbo = NCicTypeChecker.debruijn uri len [] ~subst bo in
633            let localise = relocalise localise dbo bo in
634             (name,C.Decl ty)::types,
635               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
636          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
637       in
638       let metasenv, subst, fl = 
639         List.fold_left 
640           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
641             let metasenv, subst, dbo, ty = 
642               typeof rdb ~localise metasenv subst types dbo (Some ty)
643             in
644             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
645           (metasenv, subst, []) rev_fl
646       in
647       let height = (* XXX recalculate *) height in
648       let fl =
649         List.map 
650           (fun (relevance,name,k,ty,dbo) ->
651             let bo = 
652               undebruijnate inductive 
653                (NReference.reference_of_spec uri 
654                  (if inductive then NReference.Fix (0,k,0) 
655                   else NReference.CoFix 0)) dbo rev_fl
656             in
657               relevance,name,k,ty,bo)
658           fl
659       in
660        uri, height, metasenv, subst, 
661          C.Fixpoint (inductive, fl, attr)
662   | C.Inductive (ind, leftno, itl, attr) ->
663      let len = List.length itl in
664      let metasenv,subst,rev_itl,tys =
665       List.fold_left
666        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
667           let metasenv, subst, ty, _ = check_type metasenv subst [] ty in
668           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
669        ) (metasenv,subst,[],[]) itl in
670      let metasenv,subst,itl,_ =
671       List.fold_left
672        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
673          let context,ty_sort = NCicReduction.split_prods ~subst [] ~-1 ty in
674          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
675          let metasenv,subst,cl =
676           List.fold_right
677            (fun (k_relev,n,te) (metasenv,subst,res) ->
678              let k_relev =
679               try snd (HExtlib.split_nth leftno k_relev)
680               with Failure _ -> k_relev in
681              let te = NCicTypeChecker.debruijn uri len [] ~subst te in
682              let metasenv, subst, te, _ = check_type metasenv subst tys te in
683              let context,te = NCicReduction.split_prods ~subst tys leftno te in
684              let _,chopped_context_rev =
685               HExtlib.split_nth (List.length tys) (List.rev context) in
686              let sx_context_te_rev,_ =
687               HExtlib.split_nth leftno chopped_context_rev in
688              let metasenv,subst,_ =
689               try
690                List.fold_left2
691                 (fun (metasenv,subst,context) item1 item2 ->
692                   let (metasenv,subst),convertible =
693                    try
694                     match item1,item2 with
695                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
696                         if n1 = n2 then
697                          NCicUnification.unify rdb ~test_eq_only:true metasenv
698                           subst context ty1 ty2,true
699                         else
700                          (metasenv,subst),false
701                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
702                         if n1 = n2 then
703                          let metasenv,subst =
704                           NCicUnification.unify rdb ~test_eq_only:true metasenv
705                            subst context ty1 ty2
706                          in
707                           NCicUnification.unify rdb ~test_eq_only:true metasenv
708                            subst context bo1 bo2,true
709                         else
710                          (metasenv,subst),false
711                     | _,_ -> (metasenv,subst),false
712                    with
713                    | NCicUnification.Uncertain _
714                    | NCicUnification.UnificationFailure _ ->
715                       (metasenv,subst),false
716                   in
717                    let term2 =
718                     match item2 with
719                        _,C.Decl t -> t
720                      | _,C.Def (b,_) -> b in
721                    if not convertible then
722                     raise (RefineFailure (lazy (localise term2,
723                      ("Mismatch between the left parameters of the constructor " ^
724                       "and those of its inductive type"))))
725                    else
726                     metasenv,subst,item1::context
727                 ) (metasenv,subst,[]) sx_context_ty_rev sx_context_te_rev
728               with Invalid_argument "List.fold_left2" -> assert false in
729              let con_sort= NCicTypeChecker.typeof ~subst ~metasenv context te in
730               (match
731                 NCicReduction.whd ~subst context con_sort,
732                 NCicReduction.whd ~subst [] ty_sort
733                with
734                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
735                    if not (NCicEnvironment.universe_leq u1 u2) then
736                     raise
737                      (RefineFailure
738                        (lazy(localise te, "The type " ^
739                          NCicPp.ppterm ~metasenv ~subst ~context s1 ^
740                          " of the constructor is not included in the inductive"^
741                          " type sort " ^
742                          NCicPp.ppterm ~metasenv ~subst ~context s2)))
743                 | C.Sort _, C.Sort C.Prop
744                 | C.Sort _, C.Sort C.Type _ -> ()
745                 | _, _ ->
746                    raise
747                     (RefineFailure
748                       (lazy (localise te,
749                         "Wrong constructor or inductive arity shape"))));
750               (* let's check also the positivity conditions *)
751               if 
752                not
753                (NCicTypeChecker.are_all_occurrences_positive
754                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
755               then
756                 raise
757                   (RefineFailure
758                     (lazy (localise te,
759                       "Non positive occurence in " ^
760                         NCicPp.ppterm ~metasenv ~subst ~context te)))
761               else
762                let relsno = List.length itl + leftno in
763                let te = 
764                  NCicSubstitution.psubst 
765                   (fun i ->
766                     if i <= leftno  then
767                      NCic.Rel i
768                     else
769                      NCic.Const (NReference.reference_of_spec uri
770                       (NReference.Ind (ind,relsno - i,leftno))))
771                   (HExtlib.list_seq 1 (relsno+1))
772                    te in
773                let te =
774                 List.fold_right
775                  (fun (name,decl) te ->
776                    match decl with
777                       NCic.Decl ty -> NCic.Prod (name,ty,te)
778                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
779                  ) sx_context_te_rev te
780                in
781                 metasenv,subst,(k_relev,n,te)::res
782               ) cl (metasenv,subst,[])
783          in
784           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
785        ) (metasenv,subst,[],1) rev_itl
786      in
787       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
788 ;;
789
790 NCicUnification.set_refiner_typeof typeof;;
791
792 (* vim:set foldmethod=marker: *)