]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_refiner/nCicRefiner.ml
Propagation of left expected parameters in typeof.
[helm.git] / matita / components / ng_refiner / nCicRefiner.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 exception RefineFailure of (Stdpp.location * string) Lazy.t;;
15 exception Uncertain of (Stdpp.location * string) Lazy.t;;
16 exception AssertFailure of string Lazy.t;;
17
18 module C = NCic
19 module Ref = NReference
20
21 let debug = ref false;;
22 let indent = ref "";;
23 let times = ref [];;
24 let pp s =
25  if !debug then
26   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
27 ;;
28 let inside c =
29  if !debug then
30   begin
31    let time1 = Unix.gettimeofday () in
32    indent := !indent ^ String.make 1 c;
33    times := time1 :: !times;
34    prerr_endline ("{{{" ^ !indent ^ " ")
35   end
36 ;;
37 let outside ok =
38  if !debug then
39   begin
40    let time2 = Unix.gettimeofday () in
41    let time1 =
42     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
43    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
44    if not ok then prerr_endline "exception raised!";
45    try
46     indent := String.sub !indent 0 (String.length !indent -1)
47    with
48     Invalid_argument _ -> indent := "??"; ()
49  end
50 ;;
51
52
53 let wrap_exc msg = function
54   | NCicUnification.Uncertain _ -> Uncertain msg
55   | NCicUnification.UnificationFailure _ -> RefineFailure msg
56   | NCicTypeChecker.TypeCheckerFailure _ -> RefineFailure msg
57   | e -> raise e
58 ;;
59
60 let exp_implicit rdb ~localise metasenv subst context with_type t =
61  function      
62   | `Closed ->
63       let metasenv,subst,expty =
64        match with_type with
65           None -> metasenv,subst,None
66         | Some typ ->
67            let (metasenv,subst),typ =
68             try
69              NCicMetaSubst.delift
70               ~unify:(fun m s c t1 t2 ->
71                 try Some (NCicUnification.unify rdb m s c t1 t2)
72                 with NCicUnification.UnificationFailure _ | NCicUnification.Uncertain _ -> None)
73               metasenv subst context 0 (0,NCic.Irl 0) typ
74             with
75               NCicMetaSubst.MetaSubstFailure _
76             | NCicMetaSubst.Uncertain _ ->
77                raise (RefineFailure (lazy (localise t,"Trying to create a closed meta with a non closed type: " ^ NCicPp.ppterm ~metasenv ~subst ~context typ)))
78
79            in
80             metasenv,subst,Some typ
81       in
82        NCicMetaSubst.mk_meta metasenv [] ?with_type:expty `IsTerm,subst
83   | `Type -> NCicMetaSubst.mk_meta metasenv context ?with_type `IsType,subst
84   | `Term -> NCicMetaSubst.mk_meta metasenv context ?with_type `IsTerm,subst
85   | `Tagged s ->
86       NCicMetaSubst.mk_meta 
87         ~attrs:[`Name s] metasenv context ?with_type `IsTerm,subst
88   | `Vector ->
89       raise (RefineFailure (lazy (localise t, "A vector of implicit terms " ^
90        "can only be used in argument position")))
91   | _ -> assert false
92 ;;
93
94 let check_allowed_sort_elimination rdb localise r orig =
95    let mkapp he arg =
96      match he with
97      | C.Appl l -> C.Appl (l @ [arg])
98      | t -> C.Appl [t;arg] in
99    (* ctx, ind_type @ lefts, sort_of_ind_ty@lefts, outsort *)
100    let rec aux metasenv subst context ind arity1 arity2 =
101      (*D*)inside 'S'; try let rc = 
102      let arity1 = NCicReduction.whd ~subst context arity1 in
103      pp (lazy(NCicPp.ppterm ~subst ~metasenv ~context arity1 ^ "   elimsto   " ^
104         NCicPp.ppterm ~subst ~metasenv ~context arity2 ^ "\nMENV:\n"^
105         NCicPp.ppmetasenv ~subst metasenv));
106      match arity1 with
107      | C.Prod (name,so1,de1) (* , t ==?== C.Prod _ *) ->
108         let metasenv, _, meta, _ = 
109           NCicMetaSubst.mk_meta metasenv ((name,C.Decl so1)::context) `IsType 
110         in
111         let metasenv, subst = 
112           try NCicUnification.unify rdb metasenv subst context 
113                 arity2 (C.Prod (name, so1, meta)) 
114           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
115             "expected %s, found %s" (* XXX localizzare meglio *)
116             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod (name, so1, meta)))
117             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
118         in
119         aux metasenv subst ((name, C.Decl so1)::context)
120          (mkapp (NCicSubstitution.lift 1 ind) (C.Rel 1)) de1 meta
121      | C.Sort _ (* , t ==?== C.Prod _ *) ->
122         let metasenv, _, meta, _ = NCicMetaSubst.mk_meta metasenv [] `IsSort in
123         let metasenv, subst = 
124           try NCicUnification.unify rdb metasenv subst context 
125                 arity2 (C.Prod ("_", ind, meta)) 
126           with exc -> raise (wrap_exc (lazy (localise orig, Printf.sprintf
127             "expected %s, found %s" (* XXX localizzare meglio *)
128             (NCicPp.ppterm ~subst ~metasenv ~context (C.Prod ("_", ind, meta)))
129             (NCicPp.ppterm ~subst ~metasenv ~context arity2))) exc)
130         in
131         (try NCicTypeChecker.check_allowed_sort_elimination
132             ~metasenv ~subst r context ind arity1 arity2; 
133             metasenv, subst
134         with exc -> raise (wrap_exc (lazy (localise orig, 
135           "Sort elimination not allowed ")) exc))
136      | _ -> assert false
137      (*D*)in outside true; rc with exc -> outside false; raise exc
138    in
139     aux
140 ;;
141
142 let rec typeof rdb 
143   ?(localise=fun _ -> Stdpp.dummy_loc) 
144   metasenv subst context term expty 
145 =
146   let force_ty skip_lambda skip_appl metasenv subst context orig t infty expty =
147     (*D*)inside 'F'; try let rc = 
148     match expty with
149     | Some expty ->
150        (match t with
151        | C.Implicit _ -> assert false
152        | C.Lambda _ when skip_lambda -> metasenv, subst, t, expty
153        | C.Appl _ when skip_appl -> metasenv, subst, t, expty
154        | _ ->
155           pp (lazy ("forcing infty=expty: "^
156           (NCicPp.ppterm ~metasenv ~subst ~context infty) ^  " === " ^
157           (NCicPp.ppterm ~metasenv ~subst:[] ~context expty)));
158            try 
159              let metasenv, subst =
160     (*D*)inside 'U'; try let rc = 
161                NCicUnification.unify rdb metasenv subst context infty expty 
162     (*D*)in outside true; rc with exc -> outside false; raise exc
163              in
164              metasenv, subst, t, expty
165            with 
166            | NCicUnification.Uncertain _ 
167            | NCicUnification.UnificationFailure _ as exc -> 
168              try_coercions rdb ~localise 
169                metasenv subst context t orig infty expty true exc)
170     | None -> metasenv, subst, t, infty
171     (*D*)in outside true; rc with exc -> outside false; raise exc
172   in
173   let rec typeof_aux metasenv subst context expty = 
174     fun t as orig -> 
175     (*D*)inside 'R'; try let rc = 
176     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " ::exp:: " ^
177        match expty with None -> "None" | Some e -> 
178        NCicPp.ppterm ~metasenv ~subst ~context e));
179     let metasenv, subst, t, infty = 
180     match t with
181     | C.Rel n ->
182         let infty = 
183          (try
184            match List.nth context (n - 1) with
185            | (_,C.Decl ty) -> NCicSubstitution.lift n ty
186            | (_,C.Def (_,ty)) -> NCicSubstitution.lift n ty
187          with Failure _ -> 
188            raise (RefineFailure (lazy (localise t,"unbound variable"))))
189         in
190         metasenv, subst, t, infty
191     | C.Sort s -> 
192          (try metasenv, subst, t, C.Sort (NCicEnvironment.typeof_sort s)
193          with 
194          | NCicEnvironment.UntypableSort msg -> 
195               raise (RefineFailure (lazy (localise t, Lazy.force msg)))
196          | NCicEnvironment.AssertFailure msg -> raise (AssertFailure msg))
197     | C.Implicit infos -> 
198          let (metasenv,_,t,ty),subst =
199            exp_implicit rdb ~localise metasenv subst context expty t infos
200          in
201          if expty = None then
202           typeof_aux metasenv subst context None t
203          else
204           metasenv, subst, t, ty 
205     | C.Meta (n,l) as t -> 
206        let metasenv, ty =
207         try
208          let _,_,_,ty = NCicUtils.lookup_subst n subst in metasenv, ty 
209         with NCicUtils.Subst_not_found _ ->
210          NCicMetaSubst.extend_meta metasenv n
211        in
212        metasenv, subst, t, NCicSubstitution.subst_meta l ty
213     | C.Const _ -> 
214        metasenv, subst, t, NCicTypeChecker.typeof ~subst ~metasenv context t
215     | C.Prod (name,(s as orig_s),(t as orig_t)) ->
216        let metasenv, subst, s, s1 = typeof_aux metasenv subst context None s in
217        let metasenv, subst, s, s1 = 
218          force_to_sort rdb 
219            metasenv subst context s orig_s localise s1 in
220        let context1 = (name,(C.Decl s))::context in
221        let metasenv, subst, t, s2 = typeof_aux metasenv subst context1 None t in
222        let metasenv, subst, t, s2 = 
223          force_to_sort rdb 
224            metasenv subst context1 t orig_t localise s2 in
225        let metasenv, subst, s, t, ty = 
226          sort_of_prod localise metasenv subst 
227            context orig_s orig_t (name,s) t (s1,s2)
228        in
229        metasenv, subst, NCic.Prod(name,s,t), ty
230     | C.Lambda (n,(s as orig_s),t) as orig ->
231        let exp_s, exp_ty_t, force_after =
232          match expty with
233          | None -> None, None, false
234          | Some expty -> 
235              match NCicReduction.whd ~subst context expty with
236              | C.Prod (_,s,t) -> Some s, Some t, false
237              | _ -> None, None, true 
238        in
239        let (metasenv,subst), s = 
240          match exp_s with 
241          | Some exp_s ->
242              (* optimized case: implicit and implicitly typed meta
243               * the optimization prevents proliferation of metas  *)
244              (match s with
245               | C.Implicit _ -> (metasenv,subst),exp_s
246               | _ ->
247                   let metasenv, subst, s = match s with 
248                     | C.Meta (n,_) 
249                         when (try (match NCicUtils.lookup_meta n metasenv with
250                               | _,_,C.Implicit (`Typeof _) -> true
251                               | _ -> false)
252                         with 
253                           | _ -> false) -> metasenv, subst, s
254                     | _ ->  check_type rdb ~localise metasenv subst context s in
255                   (try 
256                     pp(lazy("Force source to: "^NCicPp.ppterm ~metasenv ~subst
257                        ~context exp_s));
258                     NCicUnification.unify ~test_eq_only:true rdb metasenv subst context s exp_s,s
259                   with exc -> raise (wrap_exc (lazy (localise orig_s, Printf.sprintf
260                     "Source type %s was expected to be %s" (NCicPp.ppterm ~metasenv
261                     ~subst ~context s) (NCicPp.ppterm ~metasenv ~subst ~context
262                     exp_s))) exc)))
263          | None -> 
264              let metasenv, subst, s = 
265                check_type rdb ~localise metasenv subst context s in
266              (metasenv, subst), s
267        in
268        let context_for_t = (n,C.Decl s) :: context in
269        let metasenv, subst, t, ty_t = 
270          typeof_aux metasenv subst context_for_t exp_ty_t t 
271        in
272        if force_after then
273          force_ty false true metasenv subst context orig 
274            (C.Lambda(n,s,t)) (C.Prod (n,s,ty_t)) expty
275        else 
276          metasenv, subst, C.Lambda(n,s,t), C.Prod (n,s,ty_t)
277     | C.LetIn (n,ty,t,bo) ->
278        let metasenv, subst, ty = 
279          check_type rdb ~localise metasenv subst context ty in
280        let metasenv, subst, t, _ = 
281          typeof_aux metasenv subst context (Some ty) t in
282        let context1 = (n, C.Def (t,ty)) :: context in
283        let metasenv, subst, expty1 = 
284          match expty with 
285          | None -> metasenv, subst, None 
286          | Some x -> 
287              let m, s, x = 
288                NCicUnification.delift_type_wrt_terms 
289                 rdb metasenv subst context1 (NCicSubstitution.lift 1 x)
290                 [NCicSubstitution.lift 1 t]
291              in
292                m, s, Some x
293        in
294        let metasenv, subst, bo, bo_ty = 
295          typeof_aux metasenv subst context1 expty1 bo 
296        in
297        let bo_ty = NCicSubstitution.subst ~avoid_beta_redexes:true t bo_ty in
298        metasenv, subst, C.LetIn (n, ty, t, bo), bo_ty
299     | C.Appl ((he as orig_he)::(_::_ as args)) ->
300        let upto = match orig_he with C.Meta _ -> List.length args | _ -> 0 in
301        let hbr t = 
302          if upto > 0 then NCicReduction.head_beta_reduce ~upto t else t 
303        in
304        let refine_appl metasenv subst args =
305          let metasenv, subst, he, ty_he = 
306             typeof_aux metasenv subst context None he in
307          let metasenv, subst, t, ty = 
308            eat_prods rdb ~localise force_ty metasenv subst context expty t
309             orig_he he ty_he args in
310          metasenv, subst, hbr t, ty
311        in
312        if args = [C.Implicit `Vector] && expty <> None then
313          (* we try here to expand the vector a 0 implicits, but we use
314           * the expected type *)
315          try
316            let metasenv, subst, he, ty_he = 
317               typeof_aux metasenv subst context expty he in
318            metasenv, subst, hbr he, ty_he
319          with Uncertain _ | RefineFailure _ -> refine_appl metasenv subst args
320        else
321         (* CSC: whd can be useful on he and expty ... *)
322         (match he, expty with
323             C.Const (Ref.Ref (uri1,Ref.Con _)),
324              Some (C.Appl (C.Const (Ref.Ref (uri2,Ref.Ind _) as ref)::expargs))
325              when NUri.eq uri1 uri2 ->
326               (try
327                let _,leftno,_,_,_ = NCicEnvironment.get_checked_indtys ref in
328                let leftargs,rightargs = HExtlib.split_nth leftno args in
329                let leftexpargs,_ = HExtlib.split_nth leftno expargs in
330                let metasenv,subst,leftargs_rev =
331                 List.fold_left2
332                  (fun (metasenv,subst,args) arg exparg ->
333                    let metasenv,subst,arg,_ =
334                     typeof_aux metasenv subst context None arg in
335                    let metasenv,subst =
336                     NCicUnification.unify rdb metasenv subst context arg exparg
337                    in
338                     metasenv,subst,arg::args
339                  ) (metasenv,subst,[]) leftargs leftexpargs
340                in
341                 (* some checks are re-done here, but it would be complex to
342                  * avoid them (e.g. we did not check yet that the constructor
343                  * is a construtor for that inductive type) *)
344                 refine_appl metasenv subst ((List.rev leftargs_rev)@rightargs)
345               with
346                | Sys.Break as exn -> raise exn
347                | _ -> refine_appl metasenv subst args (* to try coercions *))
348           | _ -> refine_appl metasenv subst args)
349    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
350    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as r,
351           outtype,(term as orig_term),pl) as orig ->
352       let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
353       let _, _, arity, cl = List.nth itl tyno in
354       let constructorsno = List.length cl in
355       let _, metasenv, args = 
356         NCicMetaSubst.saturate metasenv subst context arity 0 in
357       let ind = if args = [] then C.Const r else C.Appl (C.Const r::args) in
358       let metasenv, subst, term, _ = 
359         typeof_aux metasenv subst context (Some ind) term in
360       let parameters, arguments = HExtlib.split_nth leftno args in
361       let outtype =  
362         match outtype with
363         | C.Implicit _ as ot -> 
364              let rec aux = function
365                | [] -> NCic.Lambda ("_",NCic.Implicit `Type,ot)
366                | _::tl -> NCic.Lambda ("_",NCic.Implicit `Type,aux tl)
367              in
368                aux arguments
369         | _ -> outtype
370       in 
371       let metasenv, subst, outtype, outsort = 
372         typeof_aux metasenv subst context None outtype in
373
374       (* next lines are to do a subst-expansion of the outtype, so
375          that when it becomes a beta-abstraction, the beta-redex is
376          fired during substitution *)
377       let _,fresh_metanoouttype,newouttype,_ =
378        NCicMetaSubst.mk_meta metasenv context `IsTerm in
379       let subst =
380        (fresh_metanoouttype,([`Name "outtype"],context,outtype,outsort))
381          ::subst in
382       let outtype = newouttype in
383
384       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
385       let ind =
386         if parameters = [] then C.Const r
387         else C.Appl ((C.Const r)::parameters) in
388       let metasenv, subst, ind, ind_ty = 
389         typeof_aux metasenv subst context None ind in
390       let metasenv, subst = 
391          check_allowed_sort_elimination rdb localise r orig_term metasenv subst 
392            context ind ind_ty outsort 
393       in
394       (* let's check if the type of branches are right *)
395       if List.length pl <> constructorsno then
396        raise (RefineFailure (lazy (localise orig, 
397          "Wrong number of cases in a match")));
398 (*
399       let metasenv, subst =
400         match expty with
401         | None -> metasenv, subst
402         | Some expty -> 
403            NCicUnification.unify rdb metasenv subst context resty expty 
404       in
405 *)
406       let _, metasenv, subst, pl =
407         List.fold_right
408           (fun p (j, metasenv, subst, branches) ->
409               let cons = 
410                 let cons = Ref.mk_constructor j r in
411                 if parameters = [] then C.Const cons
412                 else C.Appl (C.Const cons::parameters)
413               in
414               let metasenv, subst, cons, ty_cons = 
415                 typeof_aux metasenv subst context None cons in
416               let ty_branch = 
417                 NCicTypeChecker.type_of_branch 
418                   ~subst context leftno outtype cons ty_cons in
419               pp (lazy ("TYPEOFBRANCH: " ^
420                NCicPp.ppterm ~metasenv ~subst ~context p ^ " ::inf:: " ^
421                NCicPp.ppterm ~metasenv ~subst ~context ty_branch ));
422               let metasenv, subst, p, _ = 
423                 typeof_aux metasenv subst context (Some ty_branch) p in
424               j-1, metasenv, subst, p :: branches)
425           pl (List.length pl, metasenv, subst, [])
426       in
427       let resty = C.Appl (outtype::arguments@[term]) in
428       let resty = NCicReduction.head_beta_reduce ~subst resty in
429       metasenv, subst, C.Match (r, outtype, term, pl),resty
430     | C.Match _ -> assert false
431     in
432     pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context t ^ " ::inf:: "^
433          NCicPp.ppterm ~metasenv ~subst ~context infty ));
434       force_ty true true metasenv subst context orig t infty expty
435     (*D*)in outside true; rc with exc -> outside false; raise exc
436   in
437     typeof_aux metasenv subst context expty term
438
439 and check_type rdb ~localise metasenv subst context (ty as orig_ty) =
440   let metasenv, subst, ty, sort = 
441     typeof rdb ~localise metasenv subst context ty None
442   in
443   let metasenv, subst, ty, _ = 
444     force_to_sort rdb metasenv subst context ty orig_ty localise sort
445   in
446     metasenv, subst, ty
447
448 and try_coercions rdb 
449   ~localise 
450   metasenv subst context t orig_t infty expty perform_unification exc 
451 =
452   let cs_subst = NCicSubstitution.subst ~avoid_beta_redexes:true in
453   try 
454     pp (lazy "WWW: trying coercions -- preliminary unification");
455     let metasenv, subst = 
456       NCicUnification.unify rdb metasenv subst context infty expty
457     in metasenv, subst, t, expty
458   with
459   | exn ->
460   (* we try with a coercion *)
461   let rec first exc = function
462   | [] ->   
463       pp (lazy "WWW: no more coercions!");      
464       raise (wrap_exc (lazy (localise orig_t, Printf.sprintf
465         "The term\n%s\nhas type\n%s\nbut is here used with type\n%s"
466         (NCicPp.ppterm ~metasenv ~subst ~context t)
467         (NCicPp.ppterm ~metasenv ~subst ~context infty)
468         (NCicPp.ppterm ~metasenv ~subst ~context expty))) exc)
469   | (_,metasenv, newterm, newtype, meta)::tl ->
470       try 
471           pp (lazy("K=" ^ NCicPp.ppterm ~metasenv ~subst ~context newterm));
472           pp (lazy ( "UNIFICATION in CTX:\n"^ 
473             NCicPp.ppcontext ~metasenv ~subst context
474             ^ "\nMENV: " ^
475             NCicPp.ppmetasenv metasenv ~subst
476             ^ "\nOF: " ^
477             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
478             NCicPp.ppterm ~metasenv ~subst ~context meta ^ "\n"));
479         let metasenv, subst = 
480           NCicUnification.unify rdb metasenv subst context t meta
481         in
482           pp (lazy ( "UNIFICATION in CTX:\n"^ 
483             NCicPp.ppcontext ~metasenv ~subst context
484             ^ "\nMENV: " ^
485             NCicPp.ppmetasenv metasenv ~subst
486             ^ "\nOF: " ^
487             NCicPp.ppterm ~metasenv ~subst ~context newtype ^  " === " ^
488             NCicPp.ppterm ~metasenv ~subst ~context expty ^ "\n"));
489         let metasenv, subst = 
490           if perform_unification then
491             NCicUnification.unify rdb metasenv subst context newtype expty
492           else metasenv, subst
493         in
494         metasenv, subst, newterm, newtype
495       with 
496       | NCicUnification.UnificationFailure _ -> first exc tl
497       | NCicUnification.Uncertain _ as exc -> first exc tl
498   in
499   
500   try 
501     pp (lazy "WWW: trying coercions -- inner check");
502     match infty, expty, t with
503     | _,_, NCic.Match (Ref.Ref (_,Ref.Ind (_,tyno,leftno)) as r,outty,m,pl) ->
504         (*{{{*) pp (lazy "CASE");
505         (* {{{ helper functions *)
506         let get_cl_and_left_p refit outty =
507           match refit with
508           | NReference.Ref (uri, NReference.Ind (_,tyno,leftno)) ->
509              let _, leftno, itl, _, _ = NCicEnvironment.get_checked_indtys r in
510              let _, _, ty, cl = List.nth itl tyno in
511              let constructorsno = List.length cl in
512               let count_pis t =
513                 let rec aux ctx t = 
514                   match NCicReduction.whd ~subst ~delta:max_int ctx t with
515                   | NCic.Prod (name,src,tgt) ->
516                       let ctx = (name, (NCic.Decl src)) :: ctx in
517                       1 + aux ctx tgt
518                   | _ -> 0
519                 in
520                   aux [] t
521               in
522               let rec skip_lambda_delifting t n =
523                 match t,n with
524                 | _,0 -> t
525                 | NCic.Lambda (_,_,t),n ->
526                     pp (lazy ("WWW: failing term? "^ NCicPp.ppterm ~subst:[] ~metasenv:[] ~context:[] t)); 
527                     skip_lambda_delifting
528                       (* substitute dangling indices with a dummy *)
529                       (NCicSubstitution.subst (NCic.Sort NCic.Prop) t) (n - 1)
530                 | _ -> assert false
531               in
532               let get_l_r_p n = function
533                 | NCic.Lambda (_,NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))),_) -> [],[]
534                 | NCic.Lambda (_,NCic.Appl 
535                     (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) :: args),_) ->
536                     HExtlib.split_nth n args
537                 | _ -> assert false
538               in
539               let pis = count_pis ty in
540               let rno = pis - leftno in
541               let t = skip_lambda_delifting outty rno in
542               let left_p, _ = get_l_r_p leftno t in
543               let instantiate_with_left cl =
544                 List.map 
545                   (fun ty -> 
546                     List.fold_left 
547                       (fun t p -> match t with
548                         | NCic.Prod (_,_,t) ->
549                             cs_subst p t
550                         | _-> assert false)
551                       ty left_p) 
552                   cl 
553               in
554               let cl = instantiate_with_left (List.map (fun (_,_,x) -> x) cl) in
555               cl, left_p, leftno, rno
556           | _ -> raise exn
557         in
558         let rec keep_lambdas_and_put_expty ctx t bo right_p matched n =
559           match t,n with
560           | _,0 ->
561             let rec mkr n = function 
562               | [] -> [] | _::tl -> NCic.Rel n :: mkr (n+1) tl
563             in
564             pp (lazy ("input replace: " ^ NCicPp.ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
565             let bo =
566             NCicRefineUtil.replace_lifting
567               ~equality:(fun _ -> NCicRefineUtil.alpha_equivalence)
568               ~context:ctx
569               ~what:(matched::right_p)
570               ~with_what:(NCic.Rel 1::List.rev (mkr 2 right_p))
571               ~where:bo
572             in
573             pp (lazy ("output replace: " ^ NCicPp.ppterm ~context:ctx ~metasenv:[] ~subst:[] bo));
574             bo
575           | NCic.Lambda (name, src, tgt),_ ->
576               NCic.Lambda (name, src,
577                keep_lambdas_and_put_expty 
578                 ((name, NCic.Decl src)::ctx) tgt (NCicSubstitution.lift 1 bo)
579                 (List.map (NCicSubstitution.lift 1) right_p) (NCicSubstitution.lift 1 matched) (n-1))
580           | _ -> assert false
581         in
582         (*let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.ind(1,0,2)")) in
583         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/equality/eq.con(0,1,2)")) in*)
584         let eq = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/jmeq/jmeq.ind(1,0,2)")) in
585         let eq_refl = NCic.Const (NReference.reference_of_string ("cic:/matita/ng/Plogic/jmeq/jmeq.con(0,1,2)")) in
586         let add_params 
587           metasenv subst context cty outty mty m i 
588         =
589           let rec aux context outty par j mty m = function
590             | NCic.Prod (name, src, tgt) ->
591                 let t,k = 
592                   aux 
593                     ((name, NCic.Decl src) :: context)
594                     (NCicSubstitution.lift 1 outty) (NCic.Rel j::par) (j+1) 
595                     (NCicSubstitution.lift 1 mty) (NCicSubstitution.lift 1 m) tgt
596                 in
597                 NCic.Prod (name, src, t), k
598             | NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r) ->
599                 let k = 
600                   let k = NCic.Const(Ref.mk_constructor i r) in
601                   NCicUntrusted.mk_appl k par
602                 in
603                 (* the type has no parameters, so kty = mty
604                 let kty = 
605                   try NCicTypechecker.typeof ~subst ~metasenv context k
606                   with NCicTypeChecker.TypeCheckerFailure _ -> assert false
607                 in *)
608                 NCic.Prod ("p", 
609                  NCic.Appl [eq; mty; m; mty; k],
610                  (NCicSubstitution.lift 1
611                   (NCicReduction.head_beta_reduce ~delta:max_int 
612                    (NCicUntrusted.mk_appl outty [k])))),[mty,m,mty,k]
613             | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,leftno)) as r)::pl) ->
614                 let left_p,right_p = HExtlib.split_nth leftno pl in
615                 let has_rights = right_p <> [] in
616                 let k = 
617                   let k = NCic.Const(Ref.mk_constructor i r) in
618                   NCicUntrusted.mk_appl k (left_p@par)
619                 in
620                 let right_p = 
621                   try match 
622                     NCicTypeChecker.typeof ~subst ~metasenv context k
623                   with
624                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
625                       snd (HExtlib.split_nth leftno args)
626                   | _ -> assert false
627                   with NCicTypeChecker.TypeCheckerFailure _-> assert false
628                 in
629                 let orig_right_p =
630                   match mty with
631                   | NCic.Appl (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))::args) ->
632                       snd (HExtlib.split_nth leftno args)
633                   | _ -> assert false
634                 in
635                 List.fold_right2 
636                   (fun x y (tacc,pacc) ->
637                     let xty = 
638                     try NCicTypeChecker.typeof ~subst ~metasenv context x
639                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
640                     in
641                     let yty = 
642                     try NCicTypeChecker.typeof ~subst ~metasenv context y
643                       with NCicTypeChecker.TypeCheckerFailure _ -> assert false
644                     in
645                     NCic.Prod ("_", NCic.Appl [eq;xty;x;yty;y],
646                      NCicSubstitution.lift 1 tacc), (xty,x,yty,y)::pacc) 
647                   (orig_right_p @ [m]) (right_p @ [k]) 
648                   (NCicReduction.head_beta_reduce ~delta:max_int
649                       (NCicUntrusted.mk_appl outty (right_p@[k])), [])  
650
651   (*              if has_rights then
652                   NCicReduction.head_beta_reduce ~delta:max_int
653                     (NCic.Appl (outty ::right_p @ [k])),k
654                 else
655                   NCic.Prod ("p", 
656                    NCic.Appl [eq; mty; m; k],
657                    (NCicSubstitution.lift 1
658                     (NCicReduction.head_beta_reduce ~delta:max_int 
659                      (NCic.Appl (outty ::right_p @ [k]))))),k*)
660             | _ -> assert false
661           in
662             aux context outty [] 1 mty m cty
663         in
664         let add_lambda_for_refl_m pbo eqs cty =
665           (* k lives in the right context *)
666           (* if rno <> 0 then pbo else *)
667           let rec aux = function 
668             | NCic.Lambda (name,src,bo), NCic.Prod (_,_,ty) ->
669                 NCic.Lambda (name,src,
670                 (aux (bo,ty)))
671             | t,_ -> snd (List.fold_right
672                 (fun (xty,x,yty,y) (n,acc) -> n+1, NCic.Lambda ("p" ^ string_of_int n,
673                   NCic.Appl [eq; xty; x; yty; y],
674                   NCicSubstitution.lift 1 acc)) eqs (1,t))
675                 (*NCic.Lambda ("p",
676                   NCic.Appl [eq; mty; m; k],NCicSubstitution.lift 1 t)*)
677           in
678           aux (pbo,cty)
679         in
680         let add_pi_for_refl_m context new_outty mty m lno rno =
681           (*if rno <> 0 then new_outty else*)
682             let rec aux context mty m = function
683               | NCic.Lambda (name, src, tgt) ->
684                   let context = (name, NCic.Decl src)::context in
685                   NCic.Lambda (name, src, aux context (NCicSubstitution.lift 1 mty) (NCicSubstitution.lift 1 m) tgt)
686               | t -> 
687                   let lhs =
688                     match mty with
689                     | NCic.Appl (_::params) -> (snd (HExtlib.split_nth lno params))@[m]
690                     | _ -> [m]
691                   in
692                   let rhs = 
693                     List.map (fun x -> NCic.Rel x) 
694                       (List.rev (HExtlib.list_seq 1 (rno+2))) in
695                   List.fold_right2
696                     (fun x y acc ->
697                       let xty = 
698                     try NCicTypeChecker.typeof ~subst ~metasenv context x
699                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
700                       in
701                       let yty = 
702                     try NCicTypeChecker.typeof ~subst ~metasenv context y
703                         with NCicTypeChecker.TypeCheckerFailure _ -> assert false
704                       in
705                       NCic.Prod
706                       ("_", NCic.Appl [eq;xty;x;yty;y],
707                        (NCicSubstitution.lift 1 acc)))
708                     lhs rhs t
709   (*                NCic.Prod 
710                     ("_", NCic.Appl [eq;mty;m;NCic.Rel 1],
711                     NCicSubstitution.lift 1 t)*)
712             in
713               aux context mty m new_outty
714         in (* }}} end helper functions *)
715         (* constructors types with left params already instantiated *)
716         let outty = NCicUntrusted.apply_subst subst context outty in
717         let cl, left_p, leftno,rno = 
718           get_cl_and_left_p r outty
719         in
720         let right_p, mty = 
721           try
722             match 
723               NCicTypeChecker.typeof ~subst ~metasenv context m
724             with
725             | (NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_))) | NCic.Meta _) as mty -> [], mty
726             | NCic.Appl ((NCic.Const (Ref.Ref (_,Ref.Ind (_,_,_)))|NCic.Meta _)::args) as mty ->
727                 snd (HExtlib.split_nth leftno args), mty
728             | _ -> assert false
729           with NCicTypeChecker.TypeCheckerFailure _ -> 
730              raise (AssertFailure(lazy "already ill-typed matched term"))
731         in
732         let mty = NCicUntrusted.apply_subst subst context mty in
733         let outty = NCicUntrusted.apply_subst subst context outty in
734         let expty = NCicUntrusted.apply_subst subst context expty in
735         let new_outty =
736          keep_lambdas_and_put_expty context outty expty right_p m (rno+1)
737         in
738         pp 
739           (lazy ("CASE: new_outty: " ^ NCicPp.ppterm 
740            ~context ~metasenv ~subst new_outty));
741         let _,pl,subst,metasenv = 
742           List.fold_right2
743             (fun cty pbo (i, acc, s, menv) -> 
744                pp (lazy ("begin iteration"));
745               (* Pi k_par, (Pi H:m=(K_i left_par k_par)), 
746                *   (new_)outty right_par (K_i left_par k_par) *)
747                let infty_pbo, _ = 
748                  add_params menv s context cty outty mty m i in
749                pp 
750                 (lazy ("CASE: infty_pbo: "^ NCicPp.ppterm
751                  ~context ~metasenv ~subst infty_pbo));
752                let expty_pbo, eqs = (* k is (K_i left_par k_par) *)
753                  add_params menv s context cty new_outty mty m i in
754                pp 
755                 (lazy ("CASE: expty_pbo: "^ NCicPp.ppterm
756                  ~context ~metasenv ~subst expty_pbo));
757                let pbo = add_lambda_for_refl_m pbo eqs cty in
758                pp 
759                  (lazy ("CASE: pbo: " ^ NCicPp.ppterm
760                  ~context ~metasenv ~subst pbo));
761                let metasenv, subst, pbo, _ =
762                  try_coercions rdb ~localise menv s context pbo 
763                  orig_t (*??*) infty_pbo expty_pbo perform_unification exc
764                in
765                pp 
766                  (lazy ("CASE: pbo2: " ^ NCicPp.ppterm 
767                  ~context ~metasenv ~subst pbo));
768                (i-1, pbo::acc, subst, metasenv))
769             cl pl (List.length pl, [], subst, metasenv)
770         in
771         (*let metasenv, subst = 
772           try 
773             NCicUnification.unify rdb metasenv subst context outty new_outty 
774           with _ -> raise (RefineFailure (lazy (localise orig_t, "try_coercions")))
775         in*)
776         let new_outty = add_pi_for_refl_m context new_outty mty m leftno rno in
777         pp (lazy ("CASE: new_outty: " ^ (NCicPp.ppterm 
778            ~metasenv ~subst ~context new_outty)));
779         let right_tys = 
780           List.map 
781             (fun t -> NCicTypeChecker.typeof ~subst ~metasenv context t) right_p in
782         let eqs = 
783           List.map2 (fun x y -> NCic.Appl[eq_refl;x;y]) (right_tys@[mty]) 
784             (right_p@[m]) in
785         let t = NCic.Appl (NCic.Match(r,new_outty,m,pl) :: eqs) 
786         in
787         metasenv, subst, t, expty (*}}}*)
788     | NCic.Prod (nameprod, src, ty),NCic.Prod (_, src2, ty2), _ -> 
789         let rec mk_fresh_name ctx firstch n =
790           let candidate = (String.make 1 firstch) ^ (string_of_int n) in
791           if (List.for_all (fun (s,_) -> s <> candidate) ctx) then candidate
792           else mk_fresh_name ctx firstch (n+1)
793         in
794         (*{{{*) pp (lazy "LAM");
795         pp (lazy ("LAM: t = " ^ NCicPp.ppterm ~metasenv ~subst ~context t));
796         let name_con = mk_fresh_name context 'c' 0
797           (*FreshNamesGenerator.mk_fresh_name 
798             ~subst metasenv context ~typ:src2 Cic.Anonymous*)
799         in
800         let context_src2 = ((name_con, NCic.Decl src2) :: context) in
801         (* contravariant part: the argument of f:src->ty *)
802         let metasenv, subst, rel1, _ = 
803           try_coercions rdb ~localise metasenv subst context_src2
804            (NCic.Rel 1) orig_t (NCicSubstitution.lift 1 src2) 
805            (NCicSubstitution.lift 1 src) perform_unification exc
806         in
807         (* covariant part: the result of f(c x); x:src2; (c x):src *)
808         let name_t, bo = 
809           match t with
810           | NCic.Lambda (n,_,bo) -> n, cs_subst rel1 (NCicSubstitution.lift_from 2 1 bo)
811           | _ -> name_con, NCicUntrusted.mk_appl (NCicSubstitution.lift 1 t) [rel1]
812         in
813         (* we fix the possible dependency problem in the source ty *)
814         let ty = cs_subst rel1 (NCicSubstitution.lift_from 2 1 ty) in
815         let metasenv, subst, bo, _ = 
816           try_coercions rdb ~localise metasenv subst context_src2
817             bo orig_t ty ty2 perform_unification exc
818         in
819         let coerced = NCic.Lambda (name_t,src2, bo) in
820         pp (lazy ("LAM: coerced = " ^ NCicPp.ppterm ~metasenv ~subst ~context coerced));
821         metasenv, subst, coerced, expty (*}}}*)
822     | _ -> raise exc
823   with exc2 ->    
824   pp(lazy("try_coercion " ^ 
825     NCicPp.ppterm ~metasenv ~subst ~context infty ^ " |---> " ^
826     NCicPp.ppterm ~metasenv ~subst ~context expty));
827     first exc
828       (NCicCoercion.look_for_coercion 
829         rdb metasenv subst context infty expty)
830
831 and force_to_sort rdb metasenv subst context t orig_t localise ty =
832   try 
833     let metasenv, subst, ty = 
834       NCicUnification.sortfy (Failure "sortfy") metasenv subst context ty in
835       metasenv, subst, t, ty
836   with
837       Failure _ -> 
838         let ty = NCicReduction.whd ~subst context ty in
839           try_coercions rdb ~localise metasenv subst context
840             t orig_t ty (NCic.Sort (NCic.Type 
841               (match NCicEnvironment.get_universes () with
842                | x::_ -> x 
843                | _ -> assert false))) false 
844              (Uncertain (lazy (localise orig_t, 
845              "The type of " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^
846              " is not a sort: " ^ NCicPp.ppterm ~metasenv ~subst ~context ty)))
847
848 and sort_of_prod 
849   localise metasenv subst context orig_s orig_t (name,s) t (t1, t2) 
850 =
851    (* force to sort is done in the Prod case in typeof *)
852    match t1, t2 with
853    | C.Sort _, C.Sort C.Prop -> metasenv, subst, s, t, t2
854    | C.Sort (C.Type u1), C.Sort (C.Type u2) ->
855         metasenv, subst, s, t, C.Sort (C.Type (NCicEnvironment.max u1 u2)) 
856    | C.Sort C.Prop,C.Sort (C.Type _) -> metasenv, subst, s, t, t2
857    | C.Meta _, C.Sort _ 
858    | C.Meta _, C.Meta (_,(_,_))
859    | C.Sort _, C.Meta (_,(_,_)) -> metasenv, subst, s, t, t2 
860    | x, (C.Sort _ | C.Meta _) | _, x -> 
861       let y, context, orig = 
862         if x == t1 then s, context, orig_s 
863         else t, ((name,C.Decl s)::context), orig_t
864       in
865       raise (RefineFailure (lazy (localise orig,Printf.sprintf
866         "%s is expected to be a type, but its type is %s that is not a sort" 
867          (NCicPp.ppterm ~subst ~metasenv ~context y) 
868          (NCicPp.ppterm ~subst ~metasenv ~context x))))
869
870 and guess_name subst ctx ty = 
871   let aux initial = "#" ^ String.make 1 initial in
872   match ty with
873   | C.Const (NReference.Ref (u,_))
874   | C.Appl (C.Const (NReference.Ref (u,_)) :: _) ->
875       aux (String.sub (NUri.name_of_uri u) 0 1).[0] 
876   | C.Prod _ -> aux 'f' 
877   | C.Meta (n,lc) -> 
878       (try
879          let _,_,t,_ = NCicUtils.lookup_subst n subst in
880          guess_name subst ctx (NCicSubstitution.subst_meta lc t)
881       with NCicUtils.Subst_not_found _ -> aux 'M')
882   | _ -> aux 'H' 
883
884 and eat_prods rdb ~localise force_ty metasenv subst context expty orig_t orig_he he ty_he args =
885   (*D*)inside 'E'; try let rc = 
886   let rec aux metasenv subst args_so_far he ty_he xxx =
887   (*D*)inside 'V'; try let rc = 
888    match xxx with
889   | [] ->
890      let res = NCicUntrusted.mk_appl he (List.rev args_so_far) in
891      pp(lazy("FORCE FINAL APPL: " ^ 
892        NCicPp.ppterm ~metasenv ~subst ~context res ^
893        " of type " ^ NCicPp.ppterm ~metasenv ~subst ~context ty_he
894        ^ " to type " ^ match expty with None -> "None" | Some x -> 
895        NCicPp.ppterm ~metasenv ~subst ~context x));
896      (* whatever the term is, we force the type. in case of ((Lambda..) ?...)
897       * the application may also be a lambda! *)
898      force_ty false false metasenv subst context orig_t res ty_he expty
899   | NCic.Implicit `Vector::tl ->
900       let has_some_more_pis x =
901         match NCicReduction.whd ~subst context x with
902         |  NCic.Meta _ | NCic.Appl (NCic.Meta _::_) -> false
903         | _ -> true
904       in
905      (try
906        aux metasenv subst args_so_far he ty_he tl
907       with
908       | Uncertain _
909       | RefineFailure _ as exc when has_some_more_pis ty_he ->
910           (try
911            aux metasenv subst args_so_far he ty_he
912             (NCic.Implicit `Term :: NCic.Implicit `Vector :: tl)
913           with
914            Uncertain msg | RefineFailure msg -> raise (wrap_exc msg exc))
915      | RefineFailure msg when not (has_some_more_pis ty_he) ->
916         (* instantiating the head could change the has_some_more_pis flag *)
917         raise (Uncertain msg))
918   | arg::tl ->
919       match NCicReduction.whd ~subst context ty_he with 
920       | C.Prod (_,s,t) ->
921           let metasenv, subst, arg, _ = 
922             typeof rdb ~localise metasenv subst context arg (Some s) in
923           let t = NCicSubstitution.subst ~avoid_beta_redexes:true arg t in
924           aux metasenv subst (arg :: args_so_far) he t tl
925       | C.Meta _
926       | C.Appl (C.Meta _ :: _) as t ->
927           let metasenv, subst, arg, ty_arg = 
928             typeof rdb ~localise metasenv subst context arg None in
929           let name = guess_name subst context ty_arg in
930           let metasenv, _, meta, _ = 
931             NCicMetaSubst.mk_meta metasenv 
932               ((name,C.Decl ty_arg) :: context) `IsType
933           in
934           let flex_prod = C.Prod (name, ty_arg, meta) in
935           (* next line grants that ty_args is a type *)
936           let metasenv,subst, flex_prod, _ =
937            typeof rdb ~localise metasenv subst context flex_prod None in
938 (*
939           pp (lazy ( "UNIFICATION in CTX:\n"^ 
940             NCicPp.ppcontext ~metasenv ~subst context
941             ^ "\nOF: " ^
942             NCicPp.ppterm ~metasenv ~subst ~context t ^  " === " ^
943             NCicPp.ppterm ~metasenv ~subst ~context flex_prod ^ "\n"));
944 *)
945           let metasenv, subst =
946              try NCicUnification.unify rdb metasenv subst context t flex_prod 
947              with exc -> raise (wrap_exc (lazy (localise orig_he, Printf.sprintf
948               ("The term %s has an inferred type %s, but is applied to the" ^^
949                " argument %s of type %s")
950               (NCicPp.ppterm ~metasenv ~subst ~context he)
951               (NCicPp.ppterm ~metasenv ~subst ~context t)
952               (NCicPp.ppterm ~metasenv ~subst ~context arg)
953               (NCicPp.ppterm ~metasenv ~subst ~context ty_arg))) 
954                  (match exc with
955                  | NCicUnification.UnificationFailure m -> 
956                      NCicUnification.Uncertain m
957                  | x -> x))
958               (* XXX coerce to funclass *)
959           in
960           let meta = NCicSubstitution.subst ~avoid_beta_redexes:true arg meta in
961           aux metasenv subst (arg :: args_so_far) he meta tl
962       | C.Match (_,_,C.Meta _,_) 
963       | C.Match (_,_,C.Appl (C.Meta _ :: _),_) 
964       | C.Appl (C.Const (NReference.Ref (_, NReference.Fix _)) :: _) ->
965           raise (Uncertain (lazy (localise orig_he, Printf.sprintf
966             ("The term %s is here applied to %d arguments but expects " ^^
967             "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
968             (List.length args) (List.length args_so_far))))
969       | ty ->
970           let metasenv, subst, newhead, newheadty = 
971             try_coercions rdb ~localise metasenv subst context
972               (NCicUntrusted.mk_appl he (List.rev args_so_far)) orig_he ty
973               (NCic.Prod ("_",NCic.Implicit `Term,NCic.Implicit `Term))
974               false
975               (RefineFailure (lazy (localise orig_he, Printf.sprintf
976                ("The term %s is here applied to %d arguments but expects " ^^
977                "only %d arguments") (NCicPp.ppterm ~metasenv ~subst ~context he)
978                (List.length args) (List.length args_so_far))))
979           in
980            aux metasenv subst [] newhead newheadty (arg :: tl)
981   (*D*)in outside true; rc with exc -> outside false; raise exc
982   in
983    (* We need to reverse the order of the new created metas since they
984       are pushed on top of the metasenv in the wrong order *)
985    let highest_meta = NCicMetaSubst.maxmeta () in
986    let metasenv, subst, newhead, newheadty = 
987     aux metasenv subst [] he ty_he args in
988    let metasenv_old,metasenv_new =
989     List.partition (fun (i,_) -> i <= highest_meta) metasenv
990    in
991     (List.rev metasenv_new) @ metasenv_old, subst, newhead, newheadty
992   (*D*)in outside true; rc with exc -> outside false; raise exc
993 ;;
994
995 let rec first f l1 l2 =
996   match l1,l2 with
997   | x1::tl1, x2::tl2 -> 
998       (try f x1 x2 with Not_found -> first f tl1 tl2)
999   | _ -> raise Not_found
1000 ;;
1001
1002 let rec find add dt t =
1003   if dt == add then t
1004   else
1005     let dl, l = 
1006       match dt, t with
1007       | C.Meta (_,(_,C.Ctx dl)), C.Meta (_,(_,C.Ctx l))
1008       | C.Appl dl,C.Appl l -> dl,l
1009       | C.Lambda (_,ds,dt), C.Lambda (_,s,t) 
1010       | C.Prod (_,ds,dt), C.Prod (_,s,t) -> [ds;dt],[s;t]
1011       | C.LetIn (_,ds,db,dt), C.LetIn (_,s,b,t) -> [ds;db;dt],[s;b;t] 
1012       | C.Match (_,dot,dt,dl),  C.Match (_,ot,t,l) -> (dot::dt::dl),(ot::t::l)
1013       | _ -> raise Not_found
1014     in
1015       first (find add) dl l
1016 ;;
1017
1018 let relocalise old_localise dt t add = 
1019   old_localise 
1020     (try find add dt t with Not_found -> assert false)
1021 ;;
1022
1023 let undebruijnate inductive ref t rev_fl =
1024   let len = List.length rev_fl in 
1025   NCicSubstitution.psubst (fun x -> x) 
1026    (HExtlib.list_mapi 
1027       (fun (_,_,rno,_,_,_) i -> 
1028          let i = len - i - 1 in
1029          NCic.Const 
1030            (if inductive then NReference.mk_fix i rno ref
1031             else NReference.mk_cofix i ref))
1032       rev_fl)
1033     t
1034 ;; 
1035
1036
1037 let typeof_obj 
1038   rdb ?(localise=fun _ -> Stdpp.dummy_loc) (uri,height,metasenv,subst,obj)
1039
1040   match obj with 
1041   | C.Constant (relevance, name, bo, ty, attr) ->
1042        let metasenv, subst, ty = 
1043          check_type rdb ~localise metasenv subst [] ty in
1044        let metasenv, subst, bo, ty, height = 
1045          match bo with
1046          | Some bo ->
1047              let metasenv, subst, bo, ty = 
1048                typeof rdb ~localise metasenv subst [] bo (Some ty) in
1049              let height = (* XXX recalculate *) height in
1050                metasenv, subst, Some bo, ty, height
1051          | None -> metasenv, subst, None, ty, 0
1052        in
1053        uri, height, metasenv, subst, 
1054          C.Constant (relevance, name, bo, ty, attr)
1055   | C.Fixpoint (inductive, fl, attr) -> 
1056       let len = List.length fl in
1057       let types, metasenv, subst, rev_fl =
1058         List.fold_left
1059          (fun (types, metasenv, subst, fl) (relevance,name,k,ty,bo) ->
1060            let metasenv, subst, ty = 
1061              check_type rdb ~localise metasenv subst [] ty in
1062            let dbo = NCicTypeChecker.debruijn uri len [] ~subst bo in
1063            let localise = relocalise localise dbo bo in
1064             (name,C.Decl ty)::types,
1065               metasenv, subst, (relevance,name,k,ty,dbo,localise)::fl
1066          ) ([], metasenv, subst, []) fl (* XXX kl rimosso nel nucleo *)
1067       in
1068       let metasenv, subst, fl = 
1069         List.fold_left 
1070           (fun (metasenv,subst,fl) (relevance,name,k,ty,dbo,localise) ->
1071             let metasenv, subst, dbo, ty = 
1072               typeof rdb ~localise metasenv subst types dbo (Some ty)
1073             in
1074             metasenv, subst, (relevance,name,k,ty,dbo)::fl)
1075           (metasenv, subst, []) rev_fl
1076       in
1077       let height = (* XXX recalculate *) height in
1078       let fl =
1079         List.map 
1080           (fun (relevance,name,k,ty,dbo) ->
1081             let bo = 
1082               undebruijnate inductive 
1083                (NReference.reference_of_spec uri 
1084                  (if inductive then NReference.Fix (0,k,0) 
1085                   else NReference.CoFix 0)) dbo rev_fl
1086             in
1087               relevance,name,k,ty,bo)
1088           fl
1089       in
1090        uri, height, metasenv, subst, 
1091          C.Fixpoint (inductive, fl, attr)
1092   | C.Inductive (ind, leftno, itl, attr) ->
1093      let len = List.length itl in
1094      let metasenv,subst,rev_itl,tys =
1095       List.fold_left
1096        (fun (metasenv,subst,res,ctx) (relevance,n,ty,cl) ->
1097           let metasenv, subst, ty = 
1098             check_type rdb ~localise metasenv subst [] ty in
1099           metasenv,subst,(relevance,n,ty,cl)::res,(n,NCic.Decl ty)::ctx
1100        ) (metasenv,subst,[],[]) itl in
1101      let metasenv,subst,itl,_ =
1102       List.fold_left
1103        (fun (metasenv,subst,res,i) (it_relev,n,ty,cl) ->
1104          let context,ty_sort = NCicReduction.split_prods ~subst [] ~-1 ty in
1105          let sx_context_ty_rev,_= HExtlib.split_nth leftno (List.rev context) in
1106          let metasenv,subst,cl =
1107           List.fold_right
1108            (fun (k_relev,n,te) (metasenv,subst,res) ->
1109              let k_relev =
1110               try snd (HExtlib.split_nth leftno k_relev)
1111               with Failure _ -> k_relev in
1112              let te = NCicTypeChecker.debruijn uri len [] ~subst te in
1113              let metasenv, subst, te = 
1114                check_type rdb ~localise metasenv subst tys te in
1115              let context,te = NCicReduction.split_prods ~subst tys leftno te in
1116              let _,chopped_context_rev =
1117               HExtlib.split_nth (List.length tys) (List.rev context) in
1118              let sx_context_te_rev,_ =
1119               HExtlib.split_nth leftno chopped_context_rev in
1120              let metasenv,subst,_ =
1121               try
1122                List.fold_left2
1123                 (fun (metasenv,subst,context) item1 item2 ->
1124                   let (metasenv,subst),convertible =
1125                    try
1126                     match item1,item2 with
1127                       (n1,C.Decl ty1),(n2,C.Decl ty2) ->
1128                         if n1 = n2 then
1129                          NCicUnification.unify rdb ~test_eq_only:true metasenv
1130                           subst context ty1 ty2,true
1131                         else
1132                          (metasenv,subst),false
1133                     | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
1134                         if n1 = n2 then
1135                          let metasenv,subst =
1136                           NCicUnification.unify rdb ~test_eq_only:true metasenv
1137                            subst context ty1 ty2
1138                          in
1139                           NCicUnification.unify rdb ~test_eq_only:true metasenv
1140                            subst context bo1 bo2,true
1141                         else
1142                          (metasenv,subst),false
1143                     | _,_ -> (metasenv,subst),false
1144                    with
1145                    | NCicUnification.Uncertain _
1146                    | NCicUnification.UnificationFailure _ ->
1147                       (metasenv,subst),false
1148                   in
1149                    let term2 =
1150                     match item2 with
1151                        _,C.Decl t -> t
1152                      | _,C.Def (b,_) -> b in
1153                    if not convertible then
1154                     raise (RefineFailure (lazy (localise term2,
1155                      ("Mismatch between the left parameters of the constructor " ^
1156                       "and those of its inductive type"))))
1157                    else
1158                     metasenv,subst,item1::context
1159                 ) (metasenv,subst,tys) sx_context_ty_rev sx_context_te_rev
1160               with Invalid_argument "List.fold_left2" -> assert false in
1161              let metasenv, subst =
1162                 let rec aux context (metasenv,subst) = function
1163                   | NCic.Meta _ -> metasenv, subst
1164                   | NCic.Implicit _ -> metasenv, subst
1165                   | NCic.Appl (NCic.Rel i :: args) as t
1166                       when i > List.length context - len ->
1167                       let lefts, _ = HExtlib.split_nth leftno args in
1168                       let ctxlen = List.length context in
1169                       let (metasenv, subst), _ = 
1170                         List.fold_left
1171                         (fun ((metasenv, subst),l) arg ->
1172                           NCicUnification.unify rdb 
1173                            ~test_eq_only:true metasenv subst context arg 
1174                              (NCic.Rel (ctxlen - len - l)), l+1
1175                           )
1176                         ((metasenv, subst), 0) lefts
1177                       in
1178                       metasenv, subst
1179                   | t -> NCicUtils.fold (fun e c -> e::c) context aux
1180                   (metasenv,subst) t
1181                 in
1182                aux context (metasenv,subst) te
1183              in
1184              let con_sort= NCicTypeChecker.typeof ~subst ~metasenv context te in
1185               (match
1186                 NCicReduction.whd ~subst context con_sort,
1187                 NCicReduction.whd ~subst [] ty_sort
1188                with
1189                   (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
1190                    if not (NCicEnvironment.universe_leq u1 u2) then
1191                     raise
1192                      (RefineFailure
1193                        (lazy(localise te, "The type " ^
1194                          NCicPp.ppterm ~metasenv ~subst ~context s1 ^
1195                          " of the constructor is not included in the inductive"^
1196                          " type sort " ^
1197                          NCicPp.ppterm ~metasenv ~subst ~context s2)))
1198                 | C.Sort _, C.Sort C.Prop
1199                 | C.Sort _, C.Sort C.Type _ -> ()
1200                 | _, _ ->
1201                    raise
1202                     (RefineFailure
1203                       (lazy (localise te,
1204                         "Wrong constructor or inductive arity shape"))));
1205               (* let's check also the positivity conditions *)
1206               if 
1207                not
1208                (NCicTypeChecker.are_all_occurrences_positive
1209                  ~subst context uri leftno (i+leftno) leftno (len+leftno) te) 
1210               then
1211                 raise
1212                   (RefineFailure
1213                     (lazy (localise te,
1214                       "Non positive occurence in " ^
1215                         NCicPp.ppterm ~metasenv ~subst ~context te)))
1216               else
1217                let relsno = List.length itl + leftno in
1218                let te = 
1219                  NCicSubstitution.psubst 
1220                   (fun i ->
1221                     if i <= leftno  then
1222                      NCic.Rel i
1223                     else
1224                      NCic.Const (NReference.reference_of_spec uri
1225                       (NReference.Ind (ind,relsno - i,leftno))))
1226                   (HExtlib.list_seq 1 (relsno+1))
1227                    te in
1228                let te =
1229                 List.fold_right
1230                  (fun (name,decl) te ->
1231                    match decl with
1232                       NCic.Decl ty -> NCic.Prod (name,ty,te)
1233                     | NCic.Def (bo,ty) -> NCic.LetIn (name,ty,bo,te)
1234                  ) sx_context_te_rev te
1235                in
1236                 metasenv,subst,(k_relev,n,te)::res
1237               ) cl (metasenv,subst,[])
1238          in
1239           metasenv,subst,(it_relev,n,ty,cl)::res,i+1
1240        ) (metasenv,subst,[],1) rev_itl
1241      in
1242       uri, height, metasenv, subst, C.Inductive (ind, leftno, itl, attr)
1243 ;;
1244
1245 (* vim:set foldmethod=marker: *)