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