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