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