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