]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicRefiner.ml
Code factorization for check_type.
[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          check_type rdb ~localise metasenv subst context s in
241        let (metasenv,subst), exp_ty_t = 
242          match exp_s with 
243          | Some exp_s -> 
244              (try 
245                pp(lazy("Force source to: "^NCicPp.ppterm ~metasenv ~subst
246                   ~context exp_s));
247                NCicUnification.unify ~test_eq_only:true rdb metasenv subst context s exp_s,exp_ty_t
248              with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
249                "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
250                ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
251                exp_s))) exc))
252          | None -> (metasenv, subst), None
253        in
254        let context_for_t = (n,C.Decl s) :: context in
255        let metasenv, subst, t, ty_t = 
256          typeof_aux metasenv subst context_for_t exp_ty_t t 
257        in
258        if force_after then
259          force_ty false true metasenv subst context orig 
260            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
261        else 
262          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
263     | C.LetIn (n,(ty as orig_ty),t,bo) ->
264        let metasenv, subst, ty = 
265          check_type rdb ~localise metasenv subst context ty in
266        let metasenv, subst, t, _ = 
267          typeof_aux metasenv subst context (Some ty) t in
268        let context1 = (n, C.Def (t,ty)) :: context in
269        let metasenv, subst, expty1 = 
270          match expty with 
271          | None -> metasenv, subst, None 
272          | Some x -> 
273              let m, s, x = 
274                NCicUnification.delift_type_wrt_terms 
275                 rdb metasenv subst context1 (NCicSubstitution.lift 1 x)
276                 [NCicSubstitution.lift 1 t]
277              in
278                m, s, Some x
279        in
280        let metasenv, subst, bo, bo_ty = 
281          typeof_aux metasenv subst context1 expty1 bo 
282        in
283        let bo_ty = NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty in
284        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
285     | C.Appl ((he as orig_he)::(_::_ as args)) ->
286        let upto = match orig_he with C.Meta _ -> List.length args | _ -> 0 in
287        let hbr t = 
288          if upto > 0 then NCicReduction.head_beta_reduce ~upto t else t 
289        in
290        let refine_appl () =
291          let metasenv, subst, he, ty_he = 
292             typeof_aux metasenv subst context None he in
293          let metasenv, subst, t, ty = 
294            eat_prods rdb ~localise force_ty metasenv subst context expty t
295             orig_he he ty_he args in
296          metasenv, subst, hbr t, ty
297        in
298        if args = [C.Implicit `Vector] && expty <> None then
299          (* we try here to expand the vector a 0 implicits, but we use
300           * the expected type *)
301          try
302            let metasenv, subst, he, ty_he = 
303               typeof_aux metasenv subst context expty he in
304            metasenv, subst, hbr he, ty_he
305          with Uncertain _ | RefineFailure _ -> refine_appl ()
306        else refine_appl ()
307    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
308    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
309           outtype,(term as orig_term),pl) as orig ->
310       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
311       let _, _, arity, cl = List.nth itl tyno in
312       let constructorsno = List.length cl in
313       let _, metasenv, args = 
314         NCicMetaSubst.saturate metasenv subst context arity 0 in
315       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
316       let metasenv, subst, term, _ = 
317         typeof_aux metasenv subst context (Some ind) term in
318       let parameters, arguments = HExtlib.split_nth leftno args in
319       let outtype =  
320         match outtype with
321         | C.Implicit _ as ot -> 
322              let rec aux = function
323                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
324                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
325              in
326                aux arguments
327         | _ -> outtype
328       in 
329       let metasenv, subst, outtype, outsort = 
330         typeof_aux metasenv subst context None outtype in
331
332       (* next lines are to do a subst-expansion of the outtype, so
333          that when it becomes a beta-abstraction, the beta-redex is
334          fired during substitution *)
335       let _,fresh_metanoouttype,newouttype,_ =
336        NCicMetaSubst.mk_meta metasenv context `IsTerm in
337       let subst =
338        (fresh_metanoouttype,([`Name "outtype"],context,outtype,outsort))
339          ::subst in
340       let outtype = newouttype in
341
342       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
343       let ind =
344         if parameters = [] then C.Const r
345         else C.Appl ((C.Const r)::parameters) in
346       let metasenv, subst, ind, ind_ty = 
347         typeof_aux metasenv subst context None ind in
348       let metasenv, subst = 
349          check_allowed_sort_elimination rdb localise r orig_term metasenv subst 
350            context ind ind_ty outsort 
351       in
352       (* let's check if the type of branches are right *)
353       if List.length pl <> constructorsno then
354        raise (RefineFailure (lazy (localise orig, 
355          "Wrong number of cases in a match")));
356 (*
357       let metasenv, subst =
358         match expty with
359         | None -> metasenv, subst
360         | Some expty -> 
361            NCicUnification.unify rdb metasenv subst context resty expty 
362       in
363 *)
364       let _, metasenv, subst, pl =
365         List.fold_right
366           (fun p (j, metasenv, subst, branches) ->
367               let cons = 
368                 let cons = Ref.mk_constructor j r in
369                 if parameters = [] then C.Const cons
370                 else C.Appl (C.Const cons::parameters)
371               in
372               let metasenv, subst, cons, ty_cons = 
373                 typeof_aux metasenv subst context None cons in
374               let ty_branch = 
375                 NCicTypeChecker.type_of_branch 
376                   ~subst context leftno outtype cons ty_cons in
377               pp (lazy ("TYPEOFBRANCH: " ^
378                NCicPp.ppterm ~metasenv ~subst ~context p ^ " ::inf:: " ^
379                NCicPp.ppterm ~metasenv ~subst ~context ty_branch ));
380               let metasenv, subst, p, _ = 
381                 typeof_aux metasenv subst context (Some ty_branch) p in
382               j-1, metasenv, subst, p :: branches)
383           pl (List.length pl, metasenv, subst, [])
384       in
385       let resty = C.Appl (outtype::arguments@[term]) in
386       let resty = NCicReduction.head_beta_reduce ~subst resty in
387       metasenv, subst, C.Match (r, outtype, term, pl),resty
388     | C.Match _ -> assert false
389     in
390     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " ::inf:: "^
391          NCicPp.ppterm ~metasenv ~subst ~context infty ));
392       force_ty true true metasenv subst context orig t infty expty
393     (*D*)in outside true; rc with exc -> outside false; raise exc
394   in
395     typeof_aux metasenv subst context expty term
396
397 and check_type rdb ~localise metasenv subst context (ty as orig_ty) =
398   let metasenv, subst, ty, sort = 
399     typeof rdb ~localise metasenv subst context ty None
400   in
401   let metasenv, subst, ty, _ = 
402     force_to_sort rdb metasenv subst context ty orig_ty localise sort
403   in
404     metasenv, subst, ty
405
406 and try_coercions rdb 
407   ~localise 
408   metasenv subst context t orig_t infty expty perform_unification exc 
409 =
410   (* we try with a coercion *)
411   let rec first exc = function
412   | [] ->         
413       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
414         "The term\n%s\nhas type\n%s\nbut is here used with type\n%s"
415         (NCicPp.ppterm ~metasenv ~subst ~context t)
416         (NCicPp.ppterm ~metasenv ~subst ~context infty)
417         (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
418   | (_,metasenv, newterm, newtype, meta)::tl ->
419       try 
420           pp (lazy("K=" ^ NCicPp.ppterm ~metasenv ~subst ~context newterm));
421           pp (lazy ( "UNIFICATION in CTX:\n"^ 
422             NCicPp.ppcontext ~metasenv ~subst context
423             ^ "\nMENV: " ^
424             NCicPp.ppmetasenv metasenv ~subst
425             ^ "\nOF: " ^
426             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
427             NCicPp.ppterm ~metasenv ~subst ~context meta ^ "\n"));
428         let metasenv, subst = 
429           NCicUnification.unify rdb metasenv subst context t meta
430         in
431           pp (lazy ( "UNIFICATION in CTX:\n"^ 
432             NCicPp.ppcontext ~metasenv ~subst context
433             ^ "\nMENV: " ^
434             NCicPp.ppmetasenv metasenv ~subst
435             ^ "\nOF: " ^
436             NCicPp.ppterm ~metasenv ~subst ~context newtype ^  " === " ^
437             NCicPp.ppterm ~metasenv ~subst ~context expty ^ "\n"));
438         let metasenv, subst = 
439           if perform_unification then
440             NCicUnification.unify rdb metasenv subst context newtype expty
441           else metasenv, subst
442         in
443         metasenv, subst, newterm, newtype
444       with 
445       | NCicUnification.UnificationFailure _ -> first exc tl
446       | NCicUnification.Uncertain _ as exc -> first exc tl
447   in 
448   pp(lazy("try_coercion " ^ 
449     NCicPp.ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
450     NCicPp.ppterm ~metasenv ~subst ~context expty));
451     first exc
452       (NCicCoercion.look_for_coercion 
453         rdb metasenv subst context infty expty)
454
455 and force_to_sort rdb metasenv subst context t orig_t localise ty =
456   match NCicReduction.whd ~subst context ty with
457   | C.Meta (_,(0,(C.Irl 0 | C.Ctx []))) as ty -> 
458      metasenv, subst, t, ty
459   | C.Meta (_i,(_,(C.Irl 0 | C.Ctx []))) -> assert false (*CSC: ???
460      metasenv, subst, t, C.Meta(i,(0,C.Irl 0)) *)
461   | C.Meta (i,(_,lc)) ->
462      let len = match lc with C.Irl len->len | C.Ctx l->List.length l in
463      let metasenv, subst, newmeta, _ = 
464        if len > 0 then
465          NCicMetaSubst.restrict metasenv subst i (HExtlib.list_seq 1 (len+1))
466        else metasenv, subst, i, []
467      in
468      metasenv, subst, t, C.Meta (newmeta,(0,C.Irl 0))
469   | C.Sort _ as ty -> metasenv, subst, t, ty 
470   | ty -> 
471       try_coercions rdb ~localise metasenv subst context
472         t orig_t ty (NCic.Sort (NCic.Type 
473           (match NCicEnvironment.get_universes () with
474            | x::_ -> x 
475            | _ -> assert false))) false 
476          (Uncertain (lazy (localise orig_t, 
477          "The type of " ^ NCicPp.ppterm ~metasenv ~subst ~context t
478          ^ " is not a sort: " ^ NCicPp.ppterm ~metasenv ~subst ~context ty)))
479
480 and sort_of_prod 
481   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
482 =
483    (* force to sort is done in the Prod case in typeof *)
484    match t1, t2 with
485    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
486    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
487         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
488    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
489    | C.Meta _, C.Sort _ 
490    | C.Meta _, C.Meta (_,(_,_))
491    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
492    | x, (C.Sort _ | C.Meta _) | _, x -> 
493       let y, context, orig = 
494         if x == t1 then s, context, orig_s 
495         else t, ((name,C.Decl s)::context), orig_t
496       in
497       raise (RefineFailure (lazy (localise orig,Printf.sprintf
498         "%s is expected to be a type, but its type is %s that is not a sort" 
499          (NCicPp.ppterm ~subst ~metasenv ~context y) 
500          (NCicPp.ppterm ~subst ~metasenv ~context x))))
501
502 and guess_name subst ctx ty = 
503   let aux initial = "#" ^ String.make 1 initial in
504   match ty with
505   | C.Const (NReference.Ref (u,_))
506   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
507       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
508   | C.Prod _ -> aux 'f' 
509   | C.Meta (n,lc) -> 
510       (try
511          let _,_,t,_ = NCicUtils.lookup_subst n subst in
512          guess_name subst ctx (NCicSubstitution.subst_meta lc t)
513       with NCicUtils.Subst_not_found _ -> aux 'M')
514   | _ -> aux 'H' 
515
516 and eat_prods rdb ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
517   (*D*)inside 'E'; try let rc = 
518   let rec aux metasenv subst args_so_far he ty_he xxx =
519   (*D*)inside 'V'; try let rc = 
520    match xxx with
521   | [] ->
522      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
523      pp(lazy("FORCE FINAL APPL: " ^ 
524        NCicPp.ppterm ~metasenv ~subst ~context res ^
525        " of type " ^ NCicPp.ppterm ~metasenv ~subst ~context ty_he
526        ^ " to type " ^ match expty with None -> "None" | Some x -> 
527        NCicPp.ppterm ~metasenv ~subst ~context x));
528      (* whatever the term is, we force the type. in case of ((Lambda..) ?...)
529       * the application may also be a lambda! *)
530      force_ty false false metasenv subst context orig_t res ty_he expty
531   | NCic.Implicit `Vector::tl ->
532       let has_some_more_pis x =
533         match NCicReduction.whd ~subst context x with
534         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
535         | _ -> true
536       in
537      (try
538        aux metasenv subst args_so_far he ty_he tl
539       with
540       | Uncertain _
541       | RefineFailure _ as exc when has_some_more_pis ty_he ->
542           (try
543            aux metasenv subst args_so_far he ty_he
544             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
545           with
546            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc))
547      | RefineFailure msg when not (has_some_more_pis ty_he) ->
548         (* instantiating the head could change the has_some_more_pis flag *)
549         raise (Uncertain msg))
550   | arg::tl ->
551       match NCicReduction.whd ~subst context ty_he with 
552       | C.Prod (_,s,t) ->
553           let metasenv, subst, arg, _ = 
554             typeof rdb ~localise metasenv subst context arg (Some s) in
555           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
556           aux metasenv subst (arg :: args_so_far) he t tl
557       | C.Meta _
558       | C.Appl (C.Meta _ :: _) as t ->
559           let metasenv, subst, arg, ty_arg = 
560             typeof rdb ~localise metasenv subst context arg None in
561           let name = guess_name subst context ty_arg in
562           let metasenv, _, meta, _ = 
563             NCicMetaSubst.mk_meta metasenv 
564               ((name,C.Decl ty_arg) :: context) `IsType
565           in
566           let flex_prod = C.Prod (name, ty_arg, meta) in
567           (* next line grants that ty_args is a type *)
568           let metasenv,subst, flex_prod, _ =
569            typeof rdb ~localise metasenv subst context flex_prod None in
570 (*
571           pp (lazy ( "UNIFICATION in CTX:\n"^ 
572             NCicPp.ppcontext ~metasenv ~subst context
573             ^ "\nOF: " ^
574             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
575             NCicPp.ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
576 *)
577           let metasenv, subst =
578              try NCicUnification.unify rdb metasenv subst context t flex_prod 
579              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
580               ("The term %s has an inferred type %s, but is applied to the" ^^
581                " argument %s of type %s")
582               (NCicPp.ppterm ~metasenv ~subst ~context he)
583               (NCicPp.ppterm ~metasenv ~subst ~context t)
584               (NCicPp.ppterm ~metasenv ~subst ~context arg)
585               (NCicPp.ppterm ~metasenv ~subst ~context ty_arg))) 
586                  (match exc with
587                  | NCicUnification.UnificationFailure m -> 
588                      NCicUnification.Uncertain m
589                  | x -> x))
590               (* XXX coerce to funclass *)
591           in
592           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
593           aux metasenv subst (arg :: args_so_far) he meta tl
594       | C.Match (_,_,C.Meta _,_) 
595       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
596       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
597           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
598             ("The term %s is here applied to %d arguments but expects " ^^
599             "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
600             (List.length args) (List.length args_so_far))))
601       | ty ->
602           let metasenv, subst, newhead, newheadty = 
603             try_coercions rdb ~localise metasenv subst context
604               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
605               (NCic.Prod ("_",NCic.Implicit `Term,NCic.Implicit `Term))
606               false
607               (RefineFailure (lazy (localise orig_he, Printf.sprintf
608                ("The term %s is here applied to %d arguments but expects " ^^
609                "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
610                (List.length args) (List.length args_so_far))))
611           in
612            aux metasenv subst [] newhead newheadty (arg :: tl)
613   (*D*)in outside true; rc with exc -> outside false; raise exc
614   in
615    (* We need to reverse the order of the new created metas since they
616       are pushed on top of the metasenv in the wrong order *)
617    let highest_meta = NCicMetaSubst.maxmeta () in
618    let metasenv, subst, newhead, newheadty = 
619     aux metasenv subst [] he ty_he args in
620    let metasenv_old,metasenv_new =
621     List.partition (fun (i,_) -> i <= highest_meta) metasenv
622    in
623     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
624   (*D*)in outside true; rc with exc -> outside false; raise exc
625 ;;
626
627 let rec first f l1 l2 =
628   match l1,l2 with
629   | x1::tl1, x2::tl2 -> 
630       (try f x1 x2 with Not_found -> first f tl1 tl2)
631   | _ -> raise Not_found
632 ;;
633
634 let rec find add dt t =
635   if dt == add then t
636   else
637     let dl, l = 
638       match dt, t with
639       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
640       | C.Appl dl,C.Appl l -> dl,l
641       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
642       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
643       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
644       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
645       | _ -> raise Not_found
646     in
647       first (find add) dl l
648 ;;
649
650 let relocalise old_localise dt t add = 
651   old_localise 
652     (try find add dt t with Not_found -> assert false)
653 ;;
654
655 let undebruijnate inductive ref t rev_fl =
656   NCicSubstitution.psubst (fun x -> x) 
657    (List.rev (HExtlib.list_mapi 
658       (fun (_,_,rno,_,_,_) i -> 
659          NCic.Const 
660            (if inductive then NReference.mk_fix i rno ref
661             else NReference.mk_cofix i ref))
662       rev_fl))
663     t
664 ;; 
665
666
667 let typeof_obj 
668   rdb ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
669
670   match obj with 
671   | C.Constant (relevance, name, bo, ty, attr) ->
672        let metasenv, subst, ty = 
673          check_type rdb ~localise metasenv subst [] ty in
674        let metasenv, subst, bo, ty, height = 
675          match bo with
676          | Some bo ->
677              let metasenv, subst, bo, ty = 
678                typeof rdb ~localise metasenv subst [] bo (Some ty) in
679              let height = (* XXX recalculate *) height in
680                metasenv, subst, Some bo, ty, height
681          | None -> metasenv, subst, None, ty, 0
682        in
683        uri, height, metasenv, subst, 
684          C.Constant (relevance, name, bo, ty, attr)
685   | C.Fixpoint (inductive, fl, attr) -> 
686       let len = List.length fl in
687       let types, metasenv, subst, rev_fl =
688         List.fold_left
689          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
690            let metasenv, subst, ty = 
691              check_type rdb ~localise metasenv subst [] ty in
692            let dbo = NCicTypeChecker.debruijn uri len [] ~subst bo in
693            let localise = relocalise localise dbo bo in
694             (name,C.Decl ty)::types,
695               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
696          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
697       in
698       let metasenv, subst, fl = 
699         List.fold_left 
700           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
701             let metasenv, subst, dbo, ty = 
702               typeof rdb ~localise metasenv subst types dbo (Some ty)
703             in
704             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
705           (metasenv, subst, []) rev_fl
706       in
707       let height = (* XXX recalculate *) height in
708       let fl =
709         List.map 
710           (fun (relevance,name,k,ty,dbo) ->
711             let bo = 
712               undebruijnate inductive 
713                (NReference.reference_of_spec uri 
714                  (if inductive then NReference.Fix (0,k,0) 
715                   else NReference.CoFix 0)) dbo rev_fl
716             in
717               relevance,name,k,ty,bo)
718           fl
719       in
720        uri, height, metasenv, subst, 
721          C.Fixpoint (inductive, fl, attr)
722   | C.Inductive (ind, leftno, itl, attr) ->
723      let len = List.length itl in
724      let metasenv,subst,rev_itl,tys =
725       List.fold_left
726        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
727           let metasenv, subst, ty = 
728             check_type rdb ~localise metasenv subst [] ty in
729           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
730        ) (metasenv,subst,[],[]) itl in
731      let metasenv,subst,itl,_ =
732       List.fold_left
733        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
734          let context,ty_sort = NCicReduction.split_prods ~subst [] ~-1 ty in
735          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
736          let metasenv,subst,cl =
737           List.fold_right
738            (fun (k_relev,n,te) (metasenv,subst,res) ->
739              let k_relev =
740               try snd (HExtlib.split_nth leftno k_relev)
741               with Failure _ -> k_relev in
742              let te = NCicTypeChecker.debruijn uri len [] ~subst te in
743              let metasenv, subst, te = 
744                check_type rdb ~localise metasenv subst tys te in
745              let context,te = NCicReduction.split_prods ~subst tys leftno te in
746              let _,chopped_context_rev =
747               HExtlib.split_nth (List.length tys) (List.rev context) in
748              let sx_context_te_rev,_ =
749               HExtlib.split_nth leftno chopped_context_rev in
750              let metasenv,subst,_ =
751               try
752                List.fold_left2
753                 (fun (metasenv,subst,context) item1 item2 ->
754                   let (metasenv,subst),convertible =
755                    try
756                     match item1,item2 with
757                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
758                         if n1 = n2 then
759                          NCicUnification.unify rdb ~test_eq_only:true metasenv
760                           subst context ty1 ty2,true
761                         else
762                          (metasenv,subst),false
763                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
764                         if n1 = n2 then
765                          let metasenv,subst =
766                           NCicUnification.unify rdb ~test_eq_only:true metasenv
767                            subst context ty1 ty2
768                          in
769                           NCicUnification.unify rdb ~test_eq_only:true metasenv
770                            subst context bo1 bo2,true
771                         else
772                          (metasenv,subst),false
773                     | _,_ -> (metasenv,subst),false
774                    with
775                    | NCicUnification.Uncertain _
776                    | NCicUnification.UnificationFailure _ ->
777                       (metasenv,subst),false
778                   in
779                    let term2 =
780                     match item2 with
781                        _,C.Decl t -> t
782                      | _,C.Def (b,_) -> b in
783                    if not convertible then
784                     raise (RefineFailure (lazy (localise term2,
785                      ("Mismatch between the left parameters of the constructor " ^
786                       "and those of its inductive type"))))
787                    else
788                     metasenv,subst,item1::context
789                 ) (metasenv,subst,tys) sx_context_ty_rev sx_context_te_rev
790               with Invalid_argument "List.fold_left2" -> assert false in
791              let con_sort= NCicTypeChecker.typeof ~subst ~metasenv context te in
792               (match
793                 NCicReduction.whd ~subst context con_sort,
794                 NCicReduction.whd ~subst [] ty_sort
795                with
796                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
797                    if not (NCicEnvironment.universe_leq u1 u2) then
798                     raise
799                      (RefineFailure
800                        (lazy(localise te, "The type " ^
801                          NCicPp.ppterm ~metasenv ~subst ~context s1 ^
802                          " of the constructor is not included in the inductive"^
803                          " type sort " ^
804                          NCicPp.ppterm ~metasenv ~subst ~context s2)))
805                 | C.Sort _, C.Sort C.Prop
806                 | C.Sort _, C.Sort C.Type _ -> ()
807                 | _, _ ->
808                    raise
809                     (RefineFailure
810                       (lazy (localise te,
811                         "Wrong constructor or inductive arity shape"))));
812               (* let's check also the positivity conditions *)
813               if 
814                not
815                (NCicTypeChecker.are_all_occurrences_positive
816                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
817               then
818                 raise
819                   (RefineFailure
820                     (lazy (localise te,
821                       "Non positive occurence in " ^
822                         NCicPp.ppterm ~metasenv ~subst ~context te)))
823               else
824                let relsno = List.length itl + leftno in
825                let te = 
826                  NCicSubstitution.psubst 
827                   (fun i ->
828                     if i <= leftno  then
829                      NCic.Rel i
830                     else
831                      NCic.Const (NReference.reference_of_spec uri
832                       (NReference.Ind (ind,relsno - i,leftno))))
833                   (HExtlib.list_seq 1 (relsno+1))
834                    te in
835                let te =
836                 List.fold_right
837                  (fun (name,decl) te ->
838                    match decl with
839                       NCic.Decl ty -> NCic.Prod (name,ty,te)
840                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
841                  ) sx_context_te_rev te
842                in
843                 metasenv,subst,(k_relev,n,te)::res
844               ) cl (metasenv,subst,[])
845          in
846           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
847        ) (metasenv,subst,[],1) rev_itl
848      in
849       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
850 ;;
851
852 (* vim:set foldmethod=marker: *)