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