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