]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_refiner/nCicUnification.ml
Better error message.
[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 exception KeepReducing of string Lazy.t;;
18 exception KeepReducingThis of 
19   string Lazy.t * (NCicReduction.machine * bool) * 
20                   (NCicReduction.machine * bool) ;;
21
22 let (===) x y = Pervasives.compare x y = 0 ;;
23
24 let mk_msg metasenv subst context t1 t2 =
25  (lazy (
26   "Can't unify " ^ NCicPp.ppterm ~metasenv ~subst ~context t1 ^
27   " with " ^ NCicPp.ppterm ~metasenv ~subst ~context t2))
28
29 let mk_appl ~upto hd tl =
30   NCicReduction.head_beta_reduce ~upto
31     (match hd with
32     | NCic.Appl l -> NCic.Appl (l@tl)
33     | _ -> NCic.Appl (hd :: tl))
34 ;;
35
36 exception WrongShape;;
37
38 let eta_reduce subst t = 
39   let delift_if_not_occur body =
40     try 
41         Some (NCicSubstitution.psubst ~avoid_beta_redexes:true
42           (fun () -> raise WrongShape) [()] body)
43     with WrongShape -> None
44   in 
45   let rec eat_lambdas ctx = function
46     | NCic.Lambda (name, src, tgt) -> 
47         eat_lambdas ((name, src) :: ctx) tgt
48     | NCic.Meta (i,lc) as t->
49         (try 
50           let _,_,t,_ = NCicUtils.lookup_subst i subst in
51           let t = NCicSubstitution.subst_meta lc t in
52           eat_lambdas ctx t
53         with Not_found -> ctx, t)
54     | t -> ctx, t
55   in
56   let context_body = eat_lambdas [] t in
57   let rec aux = function
58     | [],body -> body
59     | (name, src)::ctx, (NCic.Appl (hd::[NCic.Rel 1]) as bo) -> 
60         (match delift_if_not_occur hd with
61         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
62         | Some bo -> aux (ctx,bo))
63     | (name, src)::ctx, (NCic.Appl args as bo) 
64       when HExtlib.list_last args = NCic.Rel 1 -> 
65         let args, _ = HExtlib.split_nth (List.length args - 1) args in
66         (match delift_if_not_occur (NCic.Appl args) with
67         | None -> aux (ctx,NCic.Lambda(name,src, bo)) 
68         | Some bo -> aux (ctx,bo))
69     | (name, src) :: ctx, t ->
70         aux (ctx,NCic.Lambda(name,src, t)) 
71   in
72     aux context_body
73 ;;
74
75 module C = NCic;;
76 module Ref = NReference;;
77
78 let debug = ref false;;
79 let indent = ref "";;
80 let times = ref [];;
81 let pp s =
82  if !debug then
83   prerr_endline (Printf.sprintf "%-20s" !indent ^ " " ^ Lazy.force s)
84 ;;
85 let inside c =
86  if !debug then
87   begin
88    let time1 = Unix.gettimeofday () in
89    indent := !indent ^ String.make 1 c;
90    times := time1 :: !times;
91    prerr_endline ("{{{" ^ !indent ^ " ")
92   end
93 ;;
94 let outside exc_opt =
95  if !debug then
96   begin
97    let time2 = Unix.gettimeofday () in
98    let time1 =
99     match !times with time1::tl -> times := tl; time1 | [] -> assert false in
100    prerr_endline ("}}} " ^ string_of_float (time2 -. time1));
101    (match exc_opt with
102    | Some e ->  prerr_endline ("exception raised: " ^ Printexc.to_string e)
103    | None -> ());
104    try
105     indent := String.sub !indent 0 (String.length !indent -1)
106    with
107     Invalid_argument _ -> indent := "??"; ()
108   end
109 ;;
110
111 let ppcontext ~metasenv ~subst c = 
112       "\nctx:\n"^ NCicPp.ppcontext ~metasenv ~subst c
113 ;;
114 let ppmetasenv ~subst m = "\nmenv:\n" ^ NCicPp.ppmetasenv ~subst m;;
115
116 let ppcontext ~metasenv:_metasenv ~subst:_subst _context = "";;
117 let ppmetasenv ~subst:_subst _metasenv = "";;
118 let ppterm ~metasenv ~subst ~context = NCicPp.ppterm ~metasenv ~subst ~context;;
119 (* let ppterm ~metasenv:_ ~subst:_ ~context:_ _ = "";; *)
120
121 let is_locked n subst =
122    try
123      match NCicUtils.lookup_subst n subst with
124      | tag, _,_,_ when NCicMetaSubst.is_out_scope_tag tag -> true
125      | _ -> false
126    with NCicUtils.Subst_not_found _ -> false
127 ;;
128
129 let rec mk_irl stop base =
130   if base > stop then []
131   else (NCic.Rel base) :: mk_irl stop (base+1) 
132 ;;
133
134 (* the argument must be a term in whd *)
135 let rec could_reduce =
136  function
137   | C.Meta _ -> true
138   | C.Appl (C.Const (Ref.Ref (_,Ref.Fix (_,recno,_)))::args)
139      when List.length args > recno -> could_reduce (List.nth args recno)
140   | C.Match (_,_,arg,_) -> could_reduce arg
141   | C.Appl (he::_) -> could_reduce he
142   | C.Sort _ | C.Rel _ | C.Prod _ | C.Lambda _ | C.Const _ -> false
143   | C.Appl [] | C.LetIn _ | C.Implicit _ -> assert false
144 ;;
145
146 let rec lambda_intros rdb metasenv subst context argsno ty =
147  pp (lazy ("LAMBDA INTROS: " ^ ppterm ~metasenv ~subst ~context ty));
148  match argsno with
149     0 -> 
150        let metasenv, _, bo, _ = 
151          NCicMetaSubst.mk_meta metasenv context ~with_type:ty `IsTerm
152        in
153        metasenv, bo
154   | _ ->
155      (match NCicReduction.whd ~subst context ty with
156          C.Prod (n,so,ta) ->
157           let metasenv,bo =
158            lambda_intros rdb metasenv subst
159             ((n,C.Decl so)::context) (argsno - 1) ta
160           in
161            metasenv,C.Lambda (n,so,bo)
162        | _ -> assert false)
163 ;;
164   
165 let unopt exc = function None -> raise exc | Some x -> x ;;
166
167 let fix metasenv subst is_sup test_eq_only exc t =
168   (*D*)  inside 'f'; try let rc =  
169   pp (lazy (NCicPp.ppterm ~metasenv ~subst ~context:[] t));
170   let rec aux test_eq_only metasenv = function
171     | NCic.Prod (n,so,ta) ->
172        let metasenv,so = aux true metasenv so in
173        let metasenv,ta = aux test_eq_only metasenv ta in
174         metasenv,NCic.Prod (n,so,ta)
175     | NCic.Sort (NCic.Type [(`CProp|`Type),_]) as orig when test_eq_only ->
176        metasenv,orig
177     | NCic.Sort (NCic.Type _) when test_eq_only -> raise exc
178     | NCic.Sort (NCic.Type u) when is_sup ->
179        metasenv, NCic.Sort (NCic.Type (unopt exc (NCicEnvironment.sup u)))
180     | NCic.Sort (NCic.Type u) ->
181        metasenv, NCic.Sort (NCic.Type 
182          (unopt exc (NCicEnvironment.inf ~strict:false u)))
183     | NCic.Meta (n,_) as orig ->
184         (try 
185           let _,_,_,_ = NCicUtils.lookup_subst n subst in metasenv,orig
186          with NCicUtils.Subst_not_found _ -> 
187           let metasenv, _ = NCicMetaSubst.extend_meta metasenv n in
188            metasenv, orig)
189     | t ->
190       NCicUntrusted.map_term_fold_a (fun _ x -> x) test_eq_only aux metasenv t
191   in
192    aux test_eq_only metasenv t
193  (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
194 ;;
195
196 let metasenv_to_subst n (kind,context,ty) metasenv subst =
197  let infos,metasenv = List.partition (fun (n',_) -> n = n') metasenv in
198  let attrs,octx,oty = match infos with [_,infos] -> infos | _ -> assert false in
199  if octx=context && oty=ty then
200   (n,(NCicUntrusted.set_kind kind attrs, octx, oty))::metasenv,subst
201  else 
202   let metasenv, _, bo, _ = 
203    NCicMetaSubst.mk_meta metasenv context ~attrs ~with_type:ty kind in
204   let subst = (n,(NCicUntrusted.set_kind kind attrs,octx,bo,oty))::subst in
205    metasenv,subst
206 ;;
207
208 let rec sortfy exc metasenv subst context t =
209  let t = NCicReduction.whd ~subst context t in
210  let metasenv,subst =
211   match t with
212    | NCic.Sort _ -> metasenv, subst
213    | NCic.Meta (n,_) -> 
214       let attrs, context, ty = NCicUtils.lookup_meta n metasenv in
215       let kind = NCicUntrusted.kind_of_meta attrs in
216        if kind = `IsSort then
217         metasenv,subst
218        else
219         (match ty with
220           | NCic.Implicit (`Typeof _) ->
221               metasenv_to_subst n (`IsSort,[],ty) metasenv subst
222           | ty ->
223              let metasenv,subst,ty = sortfy exc metasenv subst context ty in
224               metasenv_to_subst n (`IsSort,[],ty) metasenv subst)
225    | NCic.Implicit _ -> assert false
226    | _ -> raise exc
227  in
228   metasenv,subst,t
229
230 let tipify exc metasenv subst context t ty =
231  let is_type attrs =
232   match NCicUntrusted.kind_of_meta attrs with
233      `IsType | `IsSort -> true
234    | `IsTerm -> false
235  in
236  let rec optimize_meta metasenv subst =
237   function 
238      NCic.Meta (n,lc) ->
239       (try
240         let attrs,_,_ = NCicUtils.lookup_meta n metasenv in
241         if is_type attrs then
242          metasenv,subst,true
243         else
244          let metasenv = 
245            NCicUntrusted.replace_in_metasenv n
246             (fun attrs,cc,ty -> NCicUntrusted.set_kind `IsType attrs, cc, ty)
247             metasenv 
248          in
249           metasenv,subst,false
250        with
251         NCicUtils.Meta_not_found _ ->
252          let attrs, _,bo,_ = NCicUtils.lookup_subst n subst in
253          if is_type attrs then
254           metasenv,subst,true
255          else
256           let subst = 
257             NCicUntrusted.replace_in_subst n
258              (fun attrs,cc,bo,ty->NCicUntrusted.set_kind `IsType attrs,cc,bo,ty)
259              subst 
260           in
261            optimize_meta metasenv subst (NCicSubstitution.subst_meta lc bo))
262    | _ -> metasenv,subst,false
263  in
264   let metasenv,subst,b = optimize_meta metasenv subst t in
265    if b then
266     metasenv,subst,t
267    else
268     let metasenv,subst,_ = sortfy exc metasenv subst context ty in
269      metasenv,subst,t
270 ;;
271
272 let rec instantiate rdb test_eq_only metasenv subst context n lc t swap =
273  (*D*)  inside 'I'; try let rc =  
274   pp (lazy(string_of_int n^" :=?= "^ppterm ~metasenv ~subst ~context t));
275   let exc = 
276     UnificationFailure (mk_msg metasenv subst context (NCic.Meta (n,lc)) t) in
277   let move_to_subst i ((_,cc,t,_) as infos) metasenv subst =
278     let metasenv = List.remove_assoc i metasenv in
279     pp(lazy(string_of_int n ^ " :==> "^ ppterm ~metasenv ~subst ~context:cc t));
280     metasenv, (i,infos) :: subst
281   in
282   let delift_to_subst test_eq_only n lc (attrs,cc,ty) t context metasenv subst =
283     pp (lazy(string_of_int n ^ " := 111 = "^ 
284       ppterm ~metasenv ~subst ~context t));
285     let (metasenv, subst), t = 
286       try 
287         NCicMetaSubst.delift 
288          ~unify:(fun m s c t1 t2 -> 
289            let ind = !indent in
290            let res = 
291                    try Some (unify rdb test_eq_only m s c t1 t2 )
292              with UnificationFailure _ | Uncertain _ -> None
293            in
294            indent := ind; res) 
295          metasenv subst context n lc t
296       with NCicMetaSubst.Uncertain msg -> 
297            pp (lazy ("delift is uncertain: " ^ Lazy.force msg));
298            raise (Uncertain msg)
299       | NCicMetaSubst.MetaSubstFailure msg -> 
300            pp (lazy ("delift fails: " ^ Lazy.force msg));
301            raise (UnificationFailure msg)
302     in
303     pp (lazy(string_of_int n ^ " := 222 = "^
304       ppterm ~metasenv ~subst ~context:cc t^ppmetasenv ~subst metasenv));
305     (* Unifying the types may have already instantiated n. *)
306     try
307       let _, _,oldt,_ = NCicUtils.lookup_subst n subst in
308       let oldt = NCicSubstitution.subst_meta lc oldt in
309       let t = NCicSubstitution.subst_meta lc t in
310       (* conjecture: always fail --> occur check *)
311       unify rdb test_eq_only metasenv subst context t oldt
312     with NCicUtils.Subst_not_found _ -> 
313       move_to_subst n (attrs,cc,t,ty) metasenv subst
314   in
315   let attrs,cc,ty = NCicUtils.lookup_meta n metasenv in
316   let kind = NCicUntrusted.kind_of_meta attrs in
317   let metasenv,t = fix metasenv subst swap test_eq_only exc t in
318   let ty_t = NCicTypeChecker.typeof ~metasenv ~subst context t in
319   let metasenv,subst,t =
320    match kind with
321       `IsSort -> sortfy exc metasenv subst context t
322     | `IsType -> tipify exc metasenv subst context t ty_t
323     | `IsTerm -> metasenv,subst,t in
324   match kind with
325   | `IsSort ->
326      (match ty,t with
327          NCic.Implicit (`Typeof _), NCic.Sort _ ->
328            move_to_subst n (attrs,cc,t,ty_t) metasenv subst  
329        | NCic.Sort (NCic.Type u1), NCic.Sort s ->
330           let s =
331            match s,swap with
332               NCic.Type u2, false ->
333                NCic.Sort (NCic.Type
334                 (unopt exc (NCicEnvironment.inf ~strict:false
335                  (unopt exc (NCicEnvironment.inf ~strict:true u1) @ u2))))
336             | NCic.Type u2, true ->
337                if NCicEnvironment.universe_lt u2 u1 then
338                 NCic.Sort (NCic.Type u2)
339                else (raise exc)
340             | NCic.Prop,_ -> NCic.Sort NCic.Prop
341           in
342            move_to_subst n (attrs,cc,s,ty) metasenv subst  
343        | NCic.Implicit (`Typeof _), NCic.Meta _ ->
344           move_to_subst n (attrs,cc,t,ty_t) metasenv subst  
345        | _, NCic.Meta _
346        | NCic.Meta _, NCic.Sort _ ->
347           pp (lazy ("On the types: " ^
348             ppterm ~metasenv ~subst ~context ty ^ "=<=" ^
349             ppterm ~metasenv ~subst ~context ty_t)); 
350           let metasenv, subst = 
351             unify rdb false metasenv subst context ty_t ty in
352           delift_to_subst test_eq_only n lc (attrs,cc,ty) t
353            context metasenv subst
354        | _ -> assert false)
355   | `IsType
356   | `IsTerm ->
357      (match ty,t with
358          NCic.Implicit (`Typeof _), _ ->
359           let (metasenv, subst), ty_t = 
360             try 
361               NCicMetaSubst.delift 
362                ~unify:(fun m s c t1 t2 -> 
363                  let ind = !indent in
364                  let res = try Some (unify rdb test_eq_only m s c t1 t2 )
365                    with UnificationFailure _ | Uncertain _ -> None
366                  in
367                  indent := ind; res)
368                metasenv subst context n lc ty_t
369             with NCicMetaSubst.Uncertain msg -> 
370                  pp (lazy ("delift is uncertain: " ^ Lazy.force msg));
371                  raise (Uncertain msg)
372             | NCicMetaSubst.MetaSubstFailure msg -> 
373                  pp (lazy ("delift fails: " ^ Lazy.force msg));
374                  raise (UnificationFailure msg)
375           in
376            delift_to_subst test_eq_only n lc (attrs,cc,ty_t) t context metasenv
377             subst 
378        | _, _ ->
379         let lty = NCicSubstitution.subst_meta lc ty in
380         pp (lazy ("On the types: " ^
381           ppterm ~metasenv ~subst ~context lty ^ "=<=" ^
382           ppterm ~metasenv ~subst ~context ty_t)); 
383         let metasenv, subst = 
384           unify rdb false metasenv subst context ty_t lty
385         in
386         delift_to_subst test_eq_only n lc (attrs,cc,ty) t context metasenv
387          subst)
388 (*
389   | kind, ty, NCic.Meta(m,lcm), _ when List.mem_assoc m subst ->
390       let at,ccm,bo,tym = NCicUtils.lookup_subst m subst in
391        if NCicMetaSubst.is_out_scope_tag at then
392         begin
393          (* Case meta vs out-scope *)
394          pp(lazy("4.1"));
395          let ty_t, ccm, kindm = 
396            NCicSubstitution.subst_meta lcm tym, ccm,
397             NCicUntrusted.kind_of_meta at in
398          let lty = NCicSubstitution.subst_meta lc ty in
399          pp (lazy ("On the types: " ^
400            ppterm ~metasenv ~subst ~context lty ^ "=<=" ^
401            ppterm ~metasenv ~subst ~context ty_t)); 
402          let metasenv, subst = 
403            unify rdb false metasenv subst context ty_t lty in
404          (*CSC: here I should call kindfy, but it fails since the second
405            meta in in the susbt, not the metasenv! *)
406       (*  let metasenv,subst,t = kindfy exc metasenv subst ccm m lcm ty_t kindm kind in *)
407          delift_to_subst test_eq_only n lc attrs cc t ty context metasenv subst 
408         end
409        else
410         let bo = NCicSubstitution.subst_meta lcm bo in
411         instantiate rdb test_eq_only metasenv subst context n lc bo swap
412 *)
413  (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
414
415 and unify rdb test_eq_only metasenv subst context t1 t2 =
416  (*D*) inside 'U'; try let rc =
417    let fo_unif test_eq_only metasenv subst (norm1,t1) (norm2,t2) =
418     (*D*) inside 'F'; try let rc =  
419      pp (lazy("  " ^ ppterm ~metasenv ~subst ~context t1 ^ " ==?== " ^ 
420          ppterm ~metasenv ~subst ~context t2 ^ ppmetasenv
421          ~subst metasenv));
422      pp (lazy("  " ^ ppterm ~metasenv ~subst:[] ~context t1 ^ " ==??== " ^ 
423          ppterm ~metasenv ~subst:[] ~context t2 ^ ppmetasenv
424          ~subst metasenv));
425      if t1 === t2 then
426        metasenv, subst
427 (* CSC: To speed up Oliboni's stuff. Why is it necessary, anyway?
428      else if
429       NCicUntrusted.metas_of_term subst context t1 = [] &&
430       NCicUntrusted.metas_of_term subst context t2 = []
431      then
432       if NCicReduction.are_convertible ~metasenv ~subst context t1 t2 then
433        metasenv,subst
434       else
435        raise (UnificationFailure (lazy "Closed terms not convertible"))
436 *)
437      else
438        match (t1,t2) with
439        | C.Appl [_], _ | _, C.Appl [_] | C.Appl [], _ | _, C.Appl [] 
440        | C.Appl (C.Appl _::_), _ | _, C.Appl (C.Appl _::_) -> 
441            prerr_endline "Appl [Appl _;_] or Appl [] or Appl [_] invariant";
442            assert false 
443        | (C.Sort (C.Type a), C.Sort (C.Type b)) when not test_eq_only -> 
444            if NCicEnvironment.universe_leq a b then metasenv, subst
445            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
446        | (C.Sort (C.Type a), C.Sort (C.Type b)) -> 
447            if NCicEnvironment.universe_eq a b then metasenv, subst
448            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
449        | (C.Sort C.Prop,C.Sort (C.Type _)) -> 
450            if (not test_eq_only) then metasenv, subst
451            else raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
452
453        | (C.Lambda (name1,s1,t1), C.Lambda(_,s2,t2)) 
454        | (C.Prod (name1,s1,t1), C.Prod(_,s2,t2)) ->
455            let metasenv, subst = unify rdb true metasenv subst context s1 s2 in
456            unify rdb test_eq_only metasenv subst ((name1, C.Decl s1)::context) t1 t2
457        | (C.LetIn (name1,ty1,s1,t1), C.LetIn(_,ty2,s2,t2)) ->
458            let metasenv,subst=unify rdb test_eq_only metasenv subst context ty1 ty2 in
459            let metasenv,subst=unify rdb test_eq_only metasenv subst context s1 s2 in
460            let context = (name1, C.Def (s1,ty1))::context in
461            unify rdb test_eq_only metasenv subst context t1 t2
462
463        | (C.Meta (n1,(s1,l1 as lc1)),C.Meta (n2,(s2,l2 as lc2))) when n1 = n2 ->
464           (try 
465            let l1 = NCicUtils.expand_local_context l1 in
466            let l2 = NCicUtils.expand_local_context l2 in
467            let metasenv, subst, to_restrict, _ =
468             List.fold_right2 
469              (fun t1 t2 (metasenv, subst, to_restrict, i) -> 
470                 try 
471                   let metasenv, subst = 
472                    unify rdb test_eq_only metasenv subst context 
473                     (NCicSubstitution.lift s1 t1) (NCicSubstitution.lift s2 t2)
474                   in
475                   metasenv, subst, to_restrict, i-1  
476                 with UnificationFailure _ | Uncertain _ ->
477                   metasenv, subst, i::to_restrict, i-1)
478              l1 l2 (metasenv, subst, [], List.length l1)
479            in
480            if to_restrict <> [] then
481              let metasenv, subst, _ = 
482                NCicMetaSubst.restrict metasenv subst n1 to_restrict
483              in
484                metasenv, subst
485            else metasenv, subst
486           with 
487            | Invalid_argument _ -> assert false
488            | NCicMetaSubst.MetaSubstFailure msg ->
489               try 
490                 let _,_,term,_ = NCicUtils.lookup_subst n1 subst in
491                 let term1 = NCicSubstitution.subst_meta lc1 term in
492                 let term2 = NCicSubstitution.subst_meta lc2 term in
493                   unify rdb test_eq_only metasenv subst context term1 term2
494               with NCicUtils.Subst_not_found _-> raise (UnificationFailure msg))
495
496        |  NCic.Appl (NCic.Meta (i,_)::_ as l1),
497           NCic.Appl (NCic.Meta (j,_)::_ as l2) when i=j ->
498             (try
499               List.fold_left2 
500                 (fun (metasenv, subst) t1 t2 ->
501                   unify rdb test_eq_only metasenv subst context t1 t2)
502                 (metasenv,subst) l1 l2
503             with Invalid_argument _ -> 
504               raise (UnificationFailure (mk_msg metasenv subst context t1 t2)))
505        
506        | _, NCic.Meta (n, _) when is_locked n subst ->
507            (let (metasenv, subst), i = 
508               match NCicReduction.whd ~subst context t1 with
509               | NCic.Appl (NCic.Meta (i,l) as meta :: args) ->
510                  let metasenv, lambda_Mj =
511                    lambda_intros rdb metasenv subst context (List.length args)
512                     (NCicTypeChecker.typeof ~metasenv ~subst context meta)
513                  in
514                    unify rdb test_eq_only metasenv subst context 
515                     (C.Meta (i,l)) lambda_Mj,
516                    i
517               | NCic.Meta (i,_) -> (metasenv, subst), i
518               | _ ->
519                  raise (UnificationFailure (lazy "Locked term vs non
520                   flexible term; probably not saturated enough yet!"))
521              in
522               let t1 = NCicReduction.whd ~subst context t1 in
523               let j, lj = 
524                 match t1 with NCic.Meta (j,l) -> j, l | _ -> assert false
525               in
526               let metasenv, subst = 
527                 instantiate rdb test_eq_only metasenv subst context j lj t2 true
528               in
529               (* We need to remove the out_scope_tags to avoid propagation of
530                  them that triggers again the ad-hoc case *)
531               let subst =
532                List.map (fun (i,(tag,ctx,bo,ty)) ->
533                 let tag =
534                  List.filter
535                   (function `InScope | `OutScope _ -> false | _ -> true) tag
536                 in
537                   i,(tag,ctx,bo,ty)
538                 ) subst
539               in
540               (try
541                 let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
542                 let term = eta_reduce subst term in
543                 let subst = List.filter (fun (j,_) -> j <> i) subst in
544                 metasenv, ((i, (name, ctx, term, ty)) :: subst)
545               with Not_found -> assert false))
546
547        | C.Meta (n,lc), t when List.mem_assoc n subst -> 
548           let _,_,term,_ = NCicUtils.lookup_subst n subst in
549           let term = NCicSubstitution.subst_meta lc term in
550             unify rdb test_eq_only metasenv subst context term t
551
552        | t, C.Meta (n,lc) when List.mem_assoc n subst -> 
553           let _,_,term,_ = NCicUtils.lookup_subst n subst in
554           let term = NCicSubstitution.subst_meta lc term in
555             unify rdb test_eq_only metasenv subst context t term
556
557        | NCic.Appl (NCic.Meta (i,l)::args), _ when List.mem_assoc i subst ->
558             let _,_,term,_ = NCicUtils.lookup_subst i subst in
559             let term = NCicSubstitution.subst_meta l term in
560               unify rdb test_eq_only metasenv subst context 
561                 (mk_appl ~upto:(List.length args) term args) t2
562
563        | _, NCic.Appl (NCic.Meta (i,l)::args) when List.mem_assoc i subst ->
564             let _,_,term,_ = NCicUtils.lookup_subst i subst in
565             let term = NCicSubstitution.subst_meta l term in
566               unify rdb test_eq_only metasenv subst context t1 
567                 (mk_appl ~upto:(List.length args) term args)
568
569        | C.Meta (n,lc), t -> 
570           instantiate rdb test_eq_only metasenv subst context n lc 
571             (NCicReduction.head_beta_reduce ~subst t) false
572
573        | t, C.Meta (n,lc) -> 
574           instantiate rdb test_eq_only metasenv subst context n lc 
575            (NCicReduction.head_beta_reduce ~subst t) true
576
577        | NCic.Appl (NCic.Meta (i,l) as meta :: args), _ ->
578           let metasenv, lambda_Mj =
579             lambda_intros rdb metasenv subst context (List.length args)
580              (NCicTypeChecker.typeof ~metasenv ~subst context meta)
581           in
582           let metasenv, subst = 
583            try
584             unify rdb test_eq_only metasenv subst context 
585               (C.Meta (i,l)) lambda_Mj
586            with UnificationFailure msg | Uncertain msg when not norm2->
587             (* failure: let's try again argument vs argument *)
588             raise (KeepReducing msg)
589           in
590           let metasenv, subst = 
591             unify rdb test_eq_only metasenv subst context t1 t2 
592           in
593           (try
594             let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
595             let term = eta_reduce subst term in
596             let subst = List.filter (fun (j,_) -> j <> i) subst in
597             metasenv, ((i, (name, ctx, term, ty)) :: subst)
598           with Not_found -> assert false)
599
600        | _, NCic.Appl (NCic.Meta (i,l) as meta :: args) ->
601          let metasenv, lambda_Mj =
602            lambda_intros rdb metasenv subst context (List.length args)
603              (NCicTypeChecker.typeof ~metasenv ~subst context meta)
604          in
605          let metasenv, subst =
606           try
607            unify rdb test_eq_only metasenv subst context 
608             lambda_Mj (C.Meta (i,l))
609           with UnificationFailure msg | Uncertain msg when not norm1 ->
610            (* failure: let's try again argument vs argument *)
611            raise (KeepReducing msg)
612          in
613          let metasenv, subst = 
614            unify rdb test_eq_only metasenv subst context t1 t2 
615          in
616          (try
617            let name, ctx, term, ty = NCicUtils.lookup_subst i subst in
618            let term = eta_reduce subst term in
619            let subst = List.filter (fun (j,_) -> j <> i) subst in
620            metasenv, ((i, (name, ctx, term, ty)) :: subst)
621          with Not_found -> assert false)
622
623        (* processing this case here we avoid a useless small delta step *)
624        | (C.Appl ((C.Const r1) as _hd1::tl1), C.Appl (C.Const r2::tl2)) 
625          when Ref.eq r1 r2 ->
626            let relevance = NCicEnvironment.get_relevance r1 in
627            let metasenv, subst, _ = 
628              try
629                List.fold_left2 
630                  (fun (metasenv, subst, relevance) t1 t2 ->
631                     let b, relevance = 
632                       match relevance with b::tl -> b,tl | _ -> true, [] in
633                     let metasenv, subst = 
634                       try unify rdb test_eq_only metasenv subst context t1 t2
635                       with UnificationFailure _ | Uncertain _ when not b ->
636                         metasenv, subst
637                     in
638                       metasenv, subst, relevance)
639                  (metasenv, subst, relevance) tl1 tl2
640              with
641                 Invalid_argument _ -> 
642                  raise (Uncertain (mk_msg metasenv subst context t1 t2))
643               | UnificationFailure _ | Uncertain _ when not (norm1 && norm2) ->
644                  raise (KeepReducing (mk_msg metasenv subst context t1 t2))
645               | KeepReducing _ | KeepReducingThis _ -> assert false
646            in 
647              metasenv, subst
648
649        | (C.Match (Ref.Ref (_,Ref.Ind (_,tyno,_)) as ref1,outtype1,term1,pl1),
650           C.Match (ref2,outtype2,term2,pl2)) ->
651            let _,_,itl,_,_ = NCicEnvironment.get_checked_indtys ref1 in
652            let _,_,ty,_ = List.nth itl tyno in
653            let rec remove_prods ~subst context ty = 
654              let ty = NCicReduction.whd ~subst context ty in
655              match ty with
656              | C.Sort _ -> ty
657              | C.Prod (name,so,ta) -> 
658                    remove_prods ~subst ((name,(C.Decl so))::context) ta
659              | _ -> assert false
660            in
661            let is_prop = 
662              match remove_prods ~subst [] ty with
663              | C.Sort C.Prop -> true
664              | _ -> false 
665            in
666            if not (Ref.eq ref1 ref2) then 
667              raise (Uncertain (mk_msg metasenv subst context t1 t2))
668            else
669              let metasenv, subst = 
670               unify rdb test_eq_only metasenv subst context outtype1 outtype2 in
671              let metasenv, subst = 
672                try unify rdb test_eq_only metasenv subst context term1 term2 
673                with UnificationFailure _ | Uncertain _ when is_prop -> 
674                  metasenv, subst
675              in
676              (try
677               List.fold_left2 
678                (fun (metasenv,subst) -> 
679                   unify rdb test_eq_only metasenv subst context)
680                (metasenv, subst) pl1 pl2
681              with Invalid_argument _ -> assert false)
682        | (C.Implicit _, _) | (_, C.Implicit _) -> assert false
683        | _ when norm1 && norm2 ->
684            if (could_reduce t1 || could_reduce t2) then
685             raise (Uncertain (mk_msg metasenv subst context t1 t2))
686            else
687             raise (UnificationFailure (mk_msg metasenv subst context t1 t2))
688        | _ -> raise (KeepReducing (mk_msg metasenv subst context t1 t2))
689      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
690     in
691     let try_hints metasenv subst (_,t1 as mt1) (_,t2 as mt2) (* exc*) =
692     (*D*) inside 'H'; try let rc =  
693      pp(lazy ("\nProblema:\n" ^
694         ppterm ~metasenv ~subst ~context t1 ^ " =?= " ^
695         ppterm ~metasenv ~subst ~context t2));
696       let candidates = 
697         NCicUnifHint.look_for_hint rdb metasenv subst context t1 t2
698       in
699       let rec cand_iter = function
700         | [] -> None (* raise exc *)
701         | (metasenv,(c1,c2),premises)::tl -> 
702             pp (lazy ("\nProvo il candidato:\n" ^ 
703               String.concat "\n"
704                 (List.map 
705                   (fun (a,b) ->
706                    ppterm ~metasenv ~subst ~context a ^  " =?= " ^
707                    ppterm ~metasenv ~subst ~context b) premises) ^
708               "\n-------------------------------------------\n"^
709               ppterm ~metasenv ~subst ~context c1 ^  " = " ^
710               ppterm ~metasenv ~subst ~context c2));
711             try 
712     (*D*) inside 'K'; try let rc =  
713               let metasenv,subst = 
714                 fo_unif test_eq_only metasenv subst mt1 (false,c1) in
715               let metasenv,subst = 
716                 fo_unif test_eq_only metasenv subst (false,c2) mt2 in
717               let metasenv,subst = 
718                 List.fold_left 
719                   (fun (metasenv, subst) (x,y) ->
720                      unify rdb test_eq_only metasenv subst context x y)
721                   (metasenv, subst) premises
722               in
723               pp(lazy("FUNZIONA!"));
724               Some (metasenv, subst)
725      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
726             with
727              KeepReducing _ | UnificationFailure _ | Uncertain _ -> cand_iter tl
728            | KeepReducingThis _ -> assert false
729       in
730         cand_iter candidates
731      (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
732     in
733     let put_in_whd m1 m2 =
734       NCicReduction.reduce_machine ~delta:max_int ~subst context m1,
735       NCicReduction.reduce_machine ~delta:max_int ~subst context m2
736     in
737     let fo_unif_w_hints test_eq_only metasenv subst (_,t1 as m1) (_,t2 as m2) =
738       try fo_unif test_eq_only metasenv subst m1 m2
739       with 
740       | UnificationFailure _ as exn -> raise exn
741       | KeepReducing _ | Uncertain _ as exn ->
742         let (t1,norm1 as tm1),(t2,norm2 as tm2) =
743          put_in_whd (0,[],t1,[]) (0,[],t2,[])
744         in
745          match 
746            try_hints metasenv subst 
747             (norm1,NCicReduction.unwind t1) (norm2,NCicReduction.unwind t2)
748          with
749           | Some x -> x
750           | None -> 
751               match exn with 
752               | KeepReducing msg -> raise (KeepReducingThis (msg,tm1,tm2))
753               | Uncertain _ as exn -> raise exn
754               | _ -> assert false
755     in
756     let height_of = function
757      | NCic.Const (Ref.Ref (_,Ref.Def h)) 
758      | NCic.Const (Ref.Ref (_,Ref.Fix (_,_,h))) 
759      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Def h))::_) 
760      | NCic.Appl(NCic.Const(Ref.Ref(_,Ref.Fix (_,_,h)))::_) -> h
761      | _ -> 0
762     in
763     let small_delta_step ~subst  
764       ((_,_,t1,_ as m1, norm1) as x1) ((_,_,t2,_ as m2, norm2) as x2)
765     =
766      assert (not (norm1 && norm2));
767      if norm1 then
768       x1,NCicReduction.reduce_machine ~delta:0 ~subst context m2
769      else if norm2 then
770       NCicReduction.reduce_machine ~delta:0 ~subst context m1,x2
771      else 
772       let h1 = height_of t1 in 
773       let h2 = height_of t2 in
774       let delta = if h1 = h2 then max 0 (h1 -1) else min h1 h2 in
775       NCicReduction.reduce_machine ~delta ~subst context m1,
776       NCicReduction.reduce_machine ~delta ~subst context m2
777     in
778     let rec unif_machines metasenv subst = 
779       function
780       | ((k1,e1,t1,s1),norm1 as m1),((k2,e2,t2,s2),norm2 as m2) ->
781      (*D*) inside 'M'; try let rc = 
782          pp (lazy("UM: " ^
783            ppterm ~metasenv ~subst ~context 
784              (NCicReduction.unwind (k1,e1,t1,s1)) ^
785            " === " ^ 
786            ppterm ~metasenv ~subst ~context 
787              (NCicReduction.unwind (k2,e2,t2,s2))));
788          pp (lazy (string_of_bool norm1 ^ " ?? " ^ string_of_bool norm2));
789           let relevance = [] (* TO BE UNDERSTOOD 
790             match t1 with
791             | C.Const r -> NCicEnvironment.get_relevance r
792             | _ -> [] *) in
793           let unif_from_stack t1 t2 b metasenv subst =
794               try
795                 let t1 = NCicReduction.from_stack ~delta:max_int t1 in
796                 let t2 = NCicReduction.from_stack ~delta:max_int t2 in
797                 unif_machines metasenv subst (put_in_whd t1 t2)
798               with UnificationFailure _ | Uncertain _ when not b ->
799                 metasenv, subst
800           in
801           let rec check_stack l1 l2 r todo =
802             match l1,l2,r with
803             | x1::tl1, x2::tl2, r::tr-> check_stack tl1 tl2 tr ((x1,x2,r)::todo)
804             | x1::tl1, x2::tl2, []-> check_stack tl1 tl2 [] ((x1,x2,true)::todo)
805             | l1, l2, _ -> 
806                NCicReduction.unwind (k1,e1,t1,List.rev l1),
807                 NCicReduction.unwind (k2,e2,t2,List.rev l2),
808                 todo
809           in
810         let hh1,hh2,todo=check_stack (List.rev s1) (List.rev s2) relevance [] in
811         try
812          let metasenv,subst =
813           fo_unif_w_hints test_eq_only metasenv subst (norm1,hh1) (norm2,hh2) in
814          List.fold_left
815           (fun (metasenv,subst) (x1,x2,r) ->
816             unif_from_stack x1 x2 r metasenv subst
817           ) (metasenv,subst) todo
818         with
819          | KeepReducing _ -> assert false
820          | KeepReducingThis _ ->
821             assert (not (norm1 && norm2));
822             unif_machines metasenv subst (small_delta_step ~subst m1 m2)
823          | UnificationFailure _ | Uncertain _ when (not (norm1 && norm2))
824            -> unif_machines metasenv subst (small_delta_step ~subst m1 m2)
825          | UnificationFailure msg
826            when could_reduce (NCicReduction.unwind (fst m1))
827              || could_reduce (NCicReduction.unwind (fst m2))
828            -> raise (Uncertain msg)
829       (*D*)  in outside None; rc with exn -> outside (Some exn); raise exn 
830      in
831      try fo_unif_w_hints test_eq_only metasenv subst (false,t1) (false,t2)
832      with
833       | KeepReducingThis (msg,tm1,tm2) ->
834          (try 
835            unif_machines metasenv subst (tm1,tm2)
836           with 
837           | UnificationFailure _ -> raise (UnificationFailure msg)
838           | Uncertain _ -> raise (Uncertain msg)
839           | KeepReducing _ -> assert false)
840       | KeepReducing _ -> assert false
841
842  (*D*)  in outside None; rc with KeepReducing _ -> assert false | exn -> outside (Some exn); raise exn 
843
844 and delift_type_wrt_terms rdb metasenv subst context t args =
845   let lc = List.rev args @ mk_irl (List.length context) (List.length args+1) in
846   let (metasenv, subst), t =
847    try
848     NCicMetaSubst.delift 
849       ~unify:(fun m s c t1 t2 -> 
850          let ind = !indent in
851          let res = 
852            try Some (unify rdb false m s c t1 t2 )
853            with UnificationFailure _ | Uncertain _ -> None
854          in
855          indent := ind; res)
856       metasenv subst context 0 (0,NCic.Ctx lc) t
857    with
858       NCicMetaSubst.MetaSubstFailure _
859     | NCicMetaSubst.Uncertain _ -> (metasenv, subst), t
860   in
861    metasenv, subst, t
862 ;;
863
864
865 let unify rdb ?(test_eq_only=false) = 
866   indent := "";      
867   unify rdb test_eq_only;;
868
869 let fix_sorts m s =
870   fix m s true false (UnificationFailure (lazy "no sup"))
871 ;;