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