]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
The unification does not longer use the refiner (urrah!)
[helm.git] / helm / software / components / ng_refiner / nCicUnification.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 UnificationFailure of string Lazy.t;;
15 exception Uncertain of string Lazy.t;;
16 exception AssertFailure of string Lazy.t;;
17
18 let (===) x y = Pervasives.compare x y = 0 ;;
19
20 let uncert_exc metasenv subst context t1 t2 = 
21   Uncertain (lazy (
22   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
23   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2))
24 ;;
25
26 let fail_exc metasenv subst context t1 t2 = 
27   UnificationFailure (lazy (
28   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
29   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2));
30 ;;
31
32 let mk_appl ~upto hd tl =
33   NCicReduction.head_beta_reduce ~upto
34     (match hd with
35     | NCic.Appl l -> NCic.Appl (l@tl)
36     | _ -> NCic.Appl (hd :: tl))
37 ;;
38
39 exception WrongShape;;
40
41 let eta_reduce subst t = 
42   let delift_if_not_occur body =
43     try 
44         Some (NCicSubstitution.psubst ~avoid_beta_redexes:true
45           (fun () -> raise WrongShape) [()] body)
46     with WrongShape -> None
47   in 
48   let rec eat_lambdas ctx = function
49     | NCic.Lambda (name, src, tgt) -> 
50         eat_lambdas ((name, src) :: ctx) tgt
51     | NCic.Meta (i,lc) as t->
52         (try 
53           let _,_,t,_ = NCicUtils.lookup_subst i subst in
54           let t = NCicSubstitution.subst_meta lc t in
55           eat_lambdas ctx t
56         with Not_found -> ctx, t)
57     | t -> ctx, t
58   in
59   let context_body = eat_lambdas [] t in
60   let rec aux = function
61     | [],body -> body
62     | (name, src)::ctx, (NCic.Appl (hd::[NCic.Rel 1]) as bo) -> 
63         (match delift_if_not_occur hd with
64         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
65         | Some bo -> aux (ctx,bo))
66     | (name, src)::ctx, (NCic.Appl args as bo) 
67       when HExtlib.list_last args = NCic.Rel 1 -> 
68         let args, _ = HExtlib.split_nth (List.length args - 1) args in
69         (match delift_if_not_occur (NCic.Appl args) with
70         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
71         | Some bo -> aux (ctx,bo))
72     | (name, src) :: ctx, t ->
73         aux (ctx,NCic.Lambda(name,src, t)) 
74   in
75     aux context_body
76 ;;
77
78 module C = NCic;;
79 module Ref = NReference;;
80
81 let indent = ref "";;
82 let inside c = indent := !indent ^ String.make 1 c;;
83 let outside () =
84  try
85   indent := String.sub !indent 0 (String.length !indent -1)
86  with
87   Invalid_argument _ -> indent := "??"; ()
88 ;;
89
90 let pp s = 
91   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
92 ;;
93
94 let pp _ = ();;
95
96 let ppcontext ~metasenv ~subst c = 
97       "\nctx:\n"^ NCicPp.ppcontext ~metasenv ~subst c
98 ;;
99 let ppmetasenv ~subst m = "\nmenv:\n" ^ NCicPp.ppmetasenv ~subst m;;
100
101 let ppcontext ~metasenv:_metasenv ~subst:_subst _context = "";;
102 let ppmetasenv ~subst:_subst _metasenv = "";;
103
104 let fix_sorts swap exc t =
105   let rec aux () = function
106     | NCic.Sort (NCic.Type u) as orig ->
107         if swap then
108          match NCicEnvironment.sup u with
109          | None ->
110             prerr_endline ("no sup for " ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] orig) ;
111             raise exc
112          | Some u1 -> if u = u1 then orig else NCic.Sort (NCic.Type u1)
113         else
114          NCic.Sort (NCic.Type (
115            match NCicEnvironment.sup NCicEnvironment.type0 with 
116            | Some x -> x
117            | _ -> assert false))
118     | NCic.Meta _ as orig -> orig
119     | t -> NCicUtils.map (fun _ _ -> ()) () aux t
120   in
121     aux () t
122 ;;
123
124 let is_locked n subst =
125    try
126      match NCicUtils.lookup_subst n subst with
127      | Some tag, _,_,_ when NCicMetaSubst.is_out_scope_tag tag -> true
128      | _ -> false
129    with NCicUtils.Subst_not_found _ -> false
130 ;;
131
132 let rec mk_irl =
133  function
134     0 -> []
135   | n -> NCic.Rel n :: mk_irl (n-1)
136 ;;
137
138 let rec lambda_intros rdb metasenv subst context t args =
139  let tty = NCicTypeChecker.typeof ~metasenv ~subst context t in
140  let argsty =
141   List.map
142   (fun arg -> arg, NCicTypeChecker.typeof ~metasenv ~subst context arg) args in
143  let context_of_args = context in
144  let rec mk_lambda metasenv subst context n processed_args = function
145    | [] ->
146        let metasenv, _, bo, _ = 
147          NCicMetaSubst.mk_meta metasenv context 
148            (`WithType (NCicSubstitution.lift n tty))
149        in
150        metasenv, subst, bo
151    | (arg,ty)::tail ->
152        pp(lazy("arg{ " ^ 
153          NCicPp.ppterm ~metasenv ~subst ~context:context_of_args arg ^  ":" ^
154          NCicPp.ppterm ~metasenv ~subst ~context:context_of_args ty));
155        let metasenv, subst, telescopic_ty = 
156          if processed_args = [] then metasenv, subst, ty else
157          let _ = pp(lazy("delift")) in
158          delift_type_wrt_terms rdb metasenv subst context_of_args ty 
159            (List.rev processed_args)
160        in
161        pp(lazy("arg}"));
162        let name = "HBeta"^string_of_int n in
163        let metasenv, subst, bo =
164         mk_lambda metasenv subst ((name,NCic.Decl telescopic_ty)::context) (n+1)
165          (arg::processed_args) tail
166        in
167         metasenv, subst, NCic.Lambda (name, telescopic_ty, bo)
168  in
169  pp(lazy("LAMBDA_INTROS{ " ^ 
170    NCicPp.ppterm ~metasenv ~subst ~context t ^  ":" ^
171    NCicPp.ppterm ~metasenv ~subst ~context tty ^ " over " ^ 
172    String.concat "," (List.map (NCicPp.ppterm ~metasenv ~subst ~context)args)));
173  let rc = mk_lambda metasenv subst context 0 [] argsty in
174  pp(lazy("LAMBDA_INTROS}"));
175  rc
176
177 and instantiate rdb test_eq_only metasenv subst context n lc t swap =
178  (*D*)  inside 'I'; try let rc =  
179          pp (lazy(string_of_int n ^ " :=?= "^
180            NCicPp.ppterm ~metasenv ~subst ~context t));
181   let unify test_eq_only m s c t1 t2 = 
182     if swap then unify rdb test_eq_only m s c t2 t1 
183     else unify rdb test_eq_only m s c t1 t2
184   in
185   let name, ctx, ty = NCicUtils.lookup_meta n metasenv in
186   let metasenv, subst, t = 
187     match ty with 
188     | NCic.Implicit (`Typeof _) -> 
189        metasenv,subst, t
190          (* fix_sorts swap metasenv subst context (NCic.Meta(n,lc)) t *)
191     | _ ->
192        pp (lazy (
193                "typeof: " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^
194           ppcontext ~metasenv ~subst context ^ 
195           ppmetasenv ~subst metasenv));
196        let exc_to_be = fail_exc metasenv subst context (NCic.Meta (n,lc)) t in
197        let t, ty_t = 
198          try t, NCicTypeChecker.typeof ~subst ~metasenv context t 
199          with 
200          | NCicTypeChecker.AssertFailure msg -> 
201            (pp (lazy "fine typeof (fallimento)");
202            let ft = fix_sorts swap exc_to_be t in
203            if ft == t then 
204              (prerr_endline ( ("ILLTYPED: " ^ 
205                 NCicPp.ppterm ~metasenv ~subst ~context t
206             ^ "\nBECAUSE:" ^ Lazy.force msg ^ 
207             ppcontext ~metasenv ~subst context ^ 
208             ppmetasenv ~subst metasenv
209             ));
210                      assert false)
211            else
212             try 
213               pp (lazy ("typeof: " ^ 
214                 NCicPp.ppterm ~metasenv ~subst ~context ft));
215               ft, NCicTypeChecker.typeof ~subst ~metasenv context ft 
216             with NCicTypeChecker.AssertFailure _ -> 
217               assert false)
218          | NCicTypeChecker.TypeCheckerFailure msg ->
219               prerr_endline (Lazy.force msg);
220        prerr_endline (
221                "typeof: " ^ NCicPp.ppterm ~metasenv ~subst ~context t ^
222           ppcontext ~metasenv ~subst context ^ 
223           ppmetasenv ~subst metasenv);
224               pp msg; assert false
225        in
226        let lty = NCicSubstitution.subst_meta lc ty in
227        match ty_t with
228        | NCic.Implicit _ -> 
229            raise (UnificationFailure 
230              (lazy "trying to unify a term with a type"))
231        | ty_t -> 
232           pp (lazy ("On the types: " ^
233            NCicPp.ppterm ~metasenv ~subst ~context:ctx ty ^ " ~~~ " ^
234            NCicPp.ppterm ~metasenv ~subst ~context lty ^ " === "
235             ^ NCicPp.ppterm ~metasenv ~subst ~context ty_t)); 
236           let metasenv,subst = 
237            try
238             unify test_eq_only metasenv subst context lty ty_t
239            with NCicEnvironment.BadConstraint _ as exc ->
240             let ty_t = fix_sorts swap exc_to_be ty_t in 
241              try unify test_eq_only metasenv subst context lty ty_t
242              with _ -> raise exc in
243           metasenv, subst, t
244   in
245          pp (lazy(string_of_int n ^ " := 111 = "^
246            NCicPp.ppterm ~metasenv ~subst ~context t));
247   let (metasenv, subst), t = 
248     try 
249       NCicMetaSubst.delift 
250        ~unify:(fun m s c t1 t2 -> 
251          let ind = !indent in
252          let res = 
253            try Some (unify test_eq_only m s c t1 t2 )
254            with UnificationFailure _ | Uncertain _ -> None
255          in
256          indent := ind; res) 
257        metasenv subst context n lc t
258     with NCicMetaSubst.Uncertain msg -> 
259          pp (lazy ("delift fails: " ^ Lazy.force msg));
260          raise (Uncertain msg)
261     | NCicMetaSubst.MetaSubstFailure msg -> 
262          pp (lazy ("delift fails: " ^ Lazy.force msg));
263          raise (UnificationFailure msg)
264   in
265          pp (lazy(string_of_int n ^ " := 222 = "^
266            NCicPp.ppterm ~metasenv ~subst ~context:ctx t
267          ^ ppmetasenv ~subst metasenv));
268   (* Unifying the types may have already instantiated n. *)
269   try
270     let _, _,oldt,_ = NCicUtils.lookup_subst n subst in
271     let oldt = NCicSubstitution.subst_meta lc oldt in
272     let t = NCicSubstitution.subst_meta lc t in
273     (* conjecture: always fail --> occur check *)
274     unify test_eq_only metasenv subst context oldt t
275   with NCicUtils.Subst_not_found _ -> 
276     (* by cumulativity when unify(?,Type_i) 
277      * we could ? := Type_j with j <= i... *)
278     let subst = (n, (name, ctx, t, ty)) :: subst in
279     pp (lazy ("?"^string_of_int n^" := "^NCicPp.ppterm
280       ~metasenv ~subst ~context (NCicSubstitution.subst_meta lc t)));
281     let metasenv = 
282       List.filter (fun (m,_) -> not (n = m)) metasenv 
283     in
284     metasenv, subst
285  (*D*)  in outside(); rc with exn -> outside (); raise exn 
286
287 and unify rdb test_eq_only metasenv subst context t1 t2 =
288  (*D*) inside 'U'; try let rc =
289    let fo_unif test_eq_only metasenv subst t1 t2 =
290     (*D*) inside 'F'; try let rc =  
291      pp (lazy("  " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
292          NCicPp.ppterm ~metasenv ~subst ~context t2 ^ ppmetasenv
293          ~subst metasenv));
294      if t1 === t2 then
295        metasenv, subst
296      else
297        match (t1,t2) with
298        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
299        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
300            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
301            assert false 
302        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
303            if NCicEnvironment.universe_leq a b then metasenv, subst
304            else raise (fail_exc metasenv subst context t1 t2)
305        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
306            if NCicEnvironment.universe_eq a b then metasenv, subst
307            else raise (fail_exc metasenv subst context t1 t2)
308        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
309            if (not test_eq_only) then metasenv, subst
310            else raise (fail_exc metasenv subst context t1 t2)
311
312        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
313        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
314            let metasenv, subst = unify rdb true metasenv subst context s1 s2 in
315            unify rdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
316        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
317            let metasenv,subst=unify rdb test_eq_only metasenv subst context ty1 ty2 in
318            let metasenv,subst=unify rdb test_eq_only metasenv subst context s1 s2 in
319            let context = (name1, C.Def (s1,ty1))::context in
320            unify rdb test_eq_only metasenv subst context t1 t2
321
322        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
323           (try 
324            let l1 = NCicUtils.expand_local_context l1 in
325            let l2 = NCicUtils.expand_local_context l2 in
326            let metasenv, subst, to_restrict, _ =
327             List.fold_right2 
328              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
329                 try 
330                   let metasenv, subst = 
331                    unify rdb test_eq_only metasenv subst context 
332                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
333                   in
334                   metasenv, subst, to_restrict, i-1  
335                 with UnificationFailure _ | Uncertain _ ->
336                   metasenv, subst, i::to_restrict, i-1)
337              l1 l2 (metasenv, subst, [], List.length l1)
338            in
339            if to_restrict <> [] then
340              let metasenv, subst, _ = 
341                NCicMetaSubst.restrict metasenv subst n1 to_restrict
342              in
343                metasenv, subst
344            else metasenv, subst
345           with 
346            | Invalid_argument _ -> assert false
347            | NCicMetaSubst.MetaSubstFailure msg ->
348               try 
349                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
350                 let term1 = NCicSubstitution.subst_meta lc1 term in
351                 let term2 = NCicSubstitution.subst_meta lc2 term in
352                   unify rdb test_eq_only metasenv subst context term1 term2
353               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
354        
355        | _, NCic.Meta (n, _) when is_locked n subst ->
356            (let (metasenv, subst), i = 
357               match NCicReduction.whd ~subst context t1 with
358               | NCic.Appl (NCic.Meta (i,l)::args) ->
359                  let metasenv, subst, lambda_Mj =
360                    lambda_intros rdb metasenv subst context t1 args
361                  in
362                    unify rdb test_eq_only metasenv subst context 
363                     (C.Meta (i,l)) lambda_Mj,
364                    i
365               | NCic.Meta (i,_) -> (metasenv, subst), i
366               | _ ->
367                  raise (UnificationFailure (lazy "Locked term vs non
368                   flexible term; probably not saturated enough yet!"))
369              in
370               let t1 = NCicReduction.whd ~subst context t1 in
371               let j, lj = 
372                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
373               in
374               let metasenv, subst = 
375                 instantiate rdb test_eq_only metasenv subst context j lj t2 true
376               in
377               (* We need to remove the out_scope_tags to avoid propagation of
378                  them that triggers again the ad-hoc case *)
379               let subst =
380                List.map (fun (i,(tag,ctx,bo,ty)) ->
381                 let tag =
382                  match tag with
383                     Some tag when
384                         tag = NCicMetaSubst.in_scope_tag
385                      || NCicMetaSubst.is_out_scope_tag tag -> None
386                   | _ -> tag
387                 in
388                   i,(tag,ctx,bo,ty)
389                 ) subst
390               in
391               (try
392                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
393                 let term = eta_reduce subst term in
394                 let subst = List.filter (fun (j,_) -> j <> i) subst in
395                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
396               with Not_found -> assert false))
397
398        | C.Meta (n,lc), t -> 
399            (try 
400              let _,_,term,_ = NCicUtils.lookup_subst n subst in
401              let term = NCicSubstitution.subst_meta lc term in
402                unify rdb test_eq_only metasenv subst context term t
403            with NCicUtils.Subst_not_found _-> 
404              instantiate rdb test_eq_only metasenv subst context n lc 
405                (NCicReduction.head_beta_reduce ~subst t) false)
406
407        | t, C.Meta (n,lc) -> 
408            (try 
409              let _,_,term,_ = NCicUtils.lookup_subst n subst in
410              let term = NCicSubstitution.subst_meta lc term in
411                unify rdb test_eq_only metasenv subst context t term
412            with NCicUtils.Subst_not_found _-> 
413              instantiate rdb test_eq_only metasenv subst context n lc 
414               (NCicReduction.head_beta_reduce ~subst t) true)
415
416        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
417             let _,_,term,_ = NCicUtils.lookup_subst i subst in
418             let term = NCicSubstitution.subst_meta l term in
419               unify rdb test_eq_only metasenv subst context 
420                 (mk_appl ~upto:(List.length args) term args) t2
421
422        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
423             let _,_,term,_ = NCicUtils.lookup_subst i subst in
424             let term = NCicSubstitution.subst_meta l term in
425               unify rdb test_eq_only metasenv subst context t1 
426                 (mk_appl ~upto:(List.length args) term args)
427
428        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
429           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
430             (try
431               List.fold_left2 
432                 (fun (metasenv, subst) t1 t2 ->
433                   unify rdb test_eq_only metasenv subst context t1 t2)
434                 (metasenv,subst) l1 l2
435             with Invalid_argument _ -> 
436               raise (fail_exc metasenv subst context t1 t2))
437
438        | NCic.Appl (NCic.Meta (i,l)::args), _ ->
439           let metasenv, subst, lambda_Mj =
440             lambda_intros rdb metasenv subst context t1 args
441           in
442           let metasenv, subst = 
443             unify rdb test_eq_only metasenv subst context 
444               (C.Meta (i,l)) lambda_Mj
445           in
446           let metasenv, subst = 
447             unify rdb test_eq_only metasenv subst context t1 t2 
448           in
449           (try
450             let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
451             let term = eta_reduce subst term in
452             let subst = List.filter (fun (j,_) -> j <> i) subst in
453             metasenv, ((i, (name, ctx, term, ty)) :: subst)
454           with Not_found -> assert false)
455
456        | _, NCic.Appl (NCic.Meta (i,l)::args) ->
457          let metasenv, subst, lambda_Mj =
458            lambda_intros rdb metasenv subst context t2 args
459          in
460          let metasenv, subst =
461            unify rdb test_eq_only metasenv subst context 
462             lambda_Mj (C.Meta (i,l))
463          in
464          let metasenv, subst = 
465            unify rdb test_eq_only metasenv subst context t1 t2 
466          in
467          (try
468            let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
469            let term = eta_reduce subst term in
470            let subst = List.filter (fun (j,_) -> j <> i) subst in
471            metasenv, ((i, (name, ctx, term, ty)) :: subst)
472          with Not_found -> assert false)
473
474        (* processing this case here we avoid a useless small delta step *)
475        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
476          when Ref.eq r1 r2 ->
477            let relevance = NCicEnvironment.get_relevance r1 in
478            let relevance = match r1 with
479              | Ref.Ref (_,Ref.Con (_,_,lno)) ->
480                  let relevance =
481                   try snd (HExtlib.split_nth lno relevance)
482                   with Failure _ -> []
483                  in
484                    HExtlib.mk_list false lno @ relevance
485              | _ -> relevance
486            in
487            let metasenv, subst, _ = 
488              try
489                List.fold_left2 
490                  (fun (metasenv, subst, relevance) t1 t2 ->
491                     let b, relevance = 
492                       match relevance with b::tl -> b,tl | _ -> true, [] in
493                     let metasenv, subst = 
494                       try unify rdb test_eq_only metasenv subst context t1 t2
495                       with UnificationFailure _ | Uncertain _ when not b ->
496                         metasenv, subst
497                     in
498                       metasenv, subst, relevance)
499                  (metasenv, subst, relevance) tl1 tl2
500              with Invalid_argument _ -> 
501                raise (uncert_exc metasenv subst context t1 t2)
502            in 
503              metasenv, subst
504
505        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
506           C.Match (ref2,outtype2,term2,pl2)) ->
507            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
508            let _,_,ty,_ = List.nth itl tyno in
509            let rec remove_prods ~subst context ty = 
510              let ty = NCicReduction.whd ~subst context ty in
511              match ty with
512              | C.Sort _ -> ty
513              | C.Prod (name,so,ta) -> 
514                    remove_prods ~subst ((name,(C.Decl so))::context) ta
515              | _ -> assert false
516            in
517            let is_prop = 
518              match remove_prods ~subst [] ty with
519              | C.Sort C.Prop -> true
520              | _ -> false 
521            in
522            if not (Ref.eq ref1 ref2) then 
523              raise (uncert_exc metasenv subst context t1 t2) 
524            else
525              let metasenv, subst = 
526               unify rdb test_eq_only metasenv subst context outtype1 outtype2 in
527              let metasenv, subst = 
528                try unify rdb test_eq_only metasenv subst context term1 term2 
529                with UnificationFailure _ | Uncertain _ when is_prop -> 
530                  metasenv, subst
531              in
532              (try
533               List.fold_left2 
534                (fun (metasenv,subst) -> 
535                   unify rdb test_eq_only metasenv subst context)
536                (metasenv, subst) pl1 pl2
537              with Invalid_argument _ -> 
538                raise (uncert_exc metasenv subst context t1 t2))
539        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
540        | _ when NCicUntrusted.metas_of_term subst context t1 = [] && 
541                 NCicUntrusted.metas_of_term subst context t2 = [] -> 
542                   raise (fail_exc metasenv subst context t1 t2)
543        | _ -> raise (uncert_exc metasenv subst context t1 t2)
544      (*D*)  in outside(); rc with exn -> outside (); raise exn 
545     in
546     let try_hints metasenv subst t1 t2 (* exc*) =
547 (*
548       prerr_endline ("\nProblema:\n" ^
549         NCicPp.ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
550         NCicPp.ppterm ~metasenv ~subst ~context t2);
551 *)
552       let candidates = 
553         NCicUnifHint.look_for_hint rdb metasenv subst context t1 t2
554       in
555       let rec cand_iter = function
556         | [] -> None (* raise exc *)
557         | (metasenv,(c1,c2),premises)::tl -> 
558 (*
559             prerr_endline ("\nProvo il candidato:\n" ^ 
560               String.concat "\n"
561                 (List.map 
562                   (fun (a,b) ->
563                    NCicPp.ppterm ~metasenv ~subst ~context a ^  " =?= " ^
564                    NCicPp.ppterm ~metasenv ~subst ~context b) premises) ^
565               "\n-------------------------------------------\n"^
566               NCicPp.ppterm ~metasenv ~subst ~context c1 ^  " = " ^
567               NCicPp.ppterm ~metasenv ~subst ~context c2);
568 *)
569             try 
570               let metasenv,subst = 
571                 fo_unif test_eq_only metasenv subst t1 c1 in
572               let metasenv,subst = 
573                 fo_unif test_eq_only metasenv subst c2 t2 in
574               let metasenv,subst = 
575                 List.fold_left 
576                   (fun (metasenv, subst) (x,y) ->
577                      unify rdb test_eq_only metasenv subst context x y)
578                   (metasenv, subst) premises
579               in
580               Some (metasenv, subst)
581             with
582               UnificationFailure _ | Uncertain _ ->
583                 cand_iter tl
584       in
585         cand_iter candidates
586     in
587     let height_of = function
588      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
589      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
590      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
591      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
592      | _ -> 0
593     in
594     let put_in_whd m1 m2 =
595       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
596       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
597     in
598     let small_delta_step ~subst  
599       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
600     =
601      assert (not (norm1 && norm2));
602      if norm1 then
603       x1,NCicReduction.reduce_machine ~delta:(height_of t2 -1) ~subst context m2
604      else if norm2 then
605       NCicReduction.reduce_machine ~delta:(height_of t1 -1) ~subst context m1,x2
606      else 
607       let h1 = height_of t1 in 
608       let h2 = height_of t2 in
609       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
610       NCicReduction.reduce_machine ~delta ~subst context m1,
611       NCicReduction.reduce_machine ~delta ~subst context m2
612     in
613     let rec unif_machines metasenv subst = 
614       function
615       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
616      (*D*) inside 'M'; try let rc = 
617          pp (lazy("UM: " ^
618            NCicPp.ppterm ~metasenv ~subst ~context 
619              (NCicReduction.unwind (k1,e1,t1,s1)) ^
620            " === " ^ 
621            NCicPp.ppterm ~metasenv ~subst ~context 
622              (NCicReduction.unwind (k2,e2,t2,s2))));
623 pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
624           let relevance = [] (* TO BE UNDERSTOOD 
625             match t1 with
626             | C.Const r -> NCicEnvironment.get_relevance r
627             | _ -> [] *) in
628           let unif_from_stack t1 t2 b metasenv subst =
629               try
630                 let t1 = NCicReduction.from_stack ~delta:max_int t1 in
631                 let t2 = NCicReduction.from_stack ~delta:max_int t2 in
632                 unif_machines metasenv subst (put_in_whd t1 t2)
633               with UnificationFailure _ | Uncertain _ when not b ->
634                 metasenv, subst
635           in
636           let rec check_stack l1 l2 r todo =
637             match l1,l2,r with
638             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
639             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
640             | l1, l2, _ -> 
641                NCicReduction.unwind (k1,e1,t1,List.rev l1),
642                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
643                 todo
644           in
645         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
646         try
647          let metasenv,subst = fo_unif test_eq_only metasenv subst hh1 hh2 in
648          List.fold_left
649           (fun (metasenv,subst) (x1,x2,r) ->
650             unif_from_stack x1 x2 r metasenv subst
651           ) (metasenv,subst) todo
652         with UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
653             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
654       (*D*)  in outside(); rc with exn -> outside (); raise exn 
655      in
656      try fo_unif test_eq_only metasenv subst t1 t2
657      with 
658      | UnificationFailure msg as exn ->
659           (try 
660             unif_machines metasenv subst 
661              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
662           with 
663           | UnificationFailure _ -> raise (UnificationFailure msg)
664           | Uncertain _ -> raise exn)
665      | Uncertain msg as exn -> 
666        match try_hints metasenv subst t1 t2 with
667        | Some x -> x
668        | None -> 
669           try 
670             unif_machines metasenv subst 
671              (put_in_whd (0,[],t1,[]) (0,[],t2,[]))
672           with 
673           | UnificationFailure _ -> raise (UnificationFailure msg)
674           | Uncertain _ -> raise exn
675  (*D*)  in outside(); rc with exn -> outside (); raise exn 
676
677 and delift_type_wrt_terms rdb metasenv subst context t args =
678   let (metasenv, subst), t =
679    try
680     NCicMetaSubst.delift 
681       ~unify:(fun m s c t1 t2 -> 
682          let ind = !indent in
683          let res = 
684            try Some (unify rdb false m s c t1 t2 )
685            with UnificationFailure _ | Uncertain _ -> None
686          in
687          indent := ind; res)
688       metasenv subst context 0 (0,NCic.Ctx (args @ 
689         List.rev (mk_irl (List.length context)))) t
690    with NCicMetaSubst.MetaSubstFailure _ -> (metasenv, subst), t
691   in
692    metasenv, subst, t
693 ;;
694
695
696 let unify rdb ?(test_eq_only=false) = 
697   indent := "";      
698   unify rdb test_eq_only;;
699
700 let fix_sorts = fix_sorts true (UnificationFailure (lazy "no sup"));;