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