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