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