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