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