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