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