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