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