src/Pure/pattern.ML
author wenzelm
Tue Sep 26 20:54:40 2017 +0200 (22 months ago)
changeset 66695 91500c024c7f
parent 64556 851ae0e7b09c
child 69575 f77cc54f6d47
permissions -rw-r--r--
tuned;
     1 (*  Title:      Pure/pattern.ML
     2     Author:     Tobias Nipkow, Christine Heinzelmann, and Stefan Berghofer, TU Muenchen
     3 
     4 Unification of Higher-Order Patterns.
     5 
     6 See also:
     7 Tobias Nipkow. Functional Unification of Higher-Order Patterns.
     8 In Proceedings of the 8th IEEE Symposium Logic in Computer Science, 1993.
     9 
    10 TODO: optimize red by special-casing it
    11 *)
    12 
    13 signature PATTERN =
    14 sig
    15   exception Unif
    16   exception Pattern
    17   val unify_trace_failure_raw: Config.raw
    18   val unify_trace_failure: bool Config.T
    19   val unify_types: Context.generic -> typ * typ -> Envir.env -> Envir.env
    20   val unify: Context.generic -> term * term -> Envir.env -> Envir.env
    21   exception MATCH
    22   val match: theory -> term * term -> Type.tyenv * Envir.tenv -> Type.tyenv * Envir.tenv
    23   val first_order_match: theory -> term * term
    24     -> Type.tyenv * Envir.tenv -> Type.tyenv * Envir.tenv
    25 end;
    26 
    27 structure Pattern: PATTERN =
    28 struct
    29 
    30 exception Unif;
    31 exception Pattern;
    32 
    33 val unify_trace_failure_raw =
    34   Config.declare ("unify_trace_failure", \<^here>) (fn _ => Config.Bool false);
    35 val unify_trace_failure = Config.bool unify_trace_failure_raw;
    36 
    37 fun string_of_term ctxt env binders t =
    38   Syntax.string_of_term ctxt (Envir.norm_term env (subst_bounds (map Free binders, t)));
    39 
    40 fun bname binders i = fst (nth binders i);
    41 fun bnames binders is = space_implode " " (map (bname binders) is);
    42 
    43 fun typ_clash context (tye,T,U) =
    44   if Config.get_generic context unify_trace_failure then
    45     let
    46       val ctxt = Context.proof_of context;
    47       val t = Syntax.string_of_typ ctxt (Envir.norm_type tye T);
    48       val u = Syntax.string_of_typ ctxt (Envir.norm_type tye U);
    49     in tracing ("The following types do not unify:\n" ^ t ^ "\n" ^ u) end
    50   else ();
    51 
    52 fun clash context a b =
    53   if Config.get_generic context unify_trace_failure
    54   then tracing ("Clash: " ^ a ^ " =/= " ^ b) else ();
    55 
    56 fun boundVar binders i =
    57   "bound variable " ^ bname binders i ^ " (depth " ^ string_of_int i ^ ")";
    58 
    59 fun clashBB context binders i j =
    60   if Config.get_generic context unify_trace_failure
    61   then clash context (boundVar binders i) (boundVar binders j) else ();
    62 
    63 fun clashB context binders i s =
    64   if Config.get_generic context unify_trace_failure
    65   then clash context (boundVar binders i) s else ();
    66 
    67 fun proj_fail context (env,binders,F,_,is,t) =
    68   if Config.get_generic context unify_trace_failure then
    69     let
    70       val ctxt = Context.proof_of context
    71       val f = Term.string_of_vname F
    72       val xs = bnames binders is
    73       val u = string_of_term ctxt env binders t
    74       val ys = bnames binders (subtract (op =) is (loose_bnos t))
    75     in
    76       tracing ("Cannot unify variable " ^ f ^
    77         " (depending on bound variables " ^ xs ^ ")\nwith term " ^ u ^
    78         "\nTerm contains additional bound variable(s) " ^ ys)
    79     end
    80   else ();
    81 
    82 fun ocheck_fail context (F,t,binders,env) =
    83   if Config.get_generic context unify_trace_failure then
    84     let
    85       val ctxt = Context.proof_of context
    86       val f = Term.string_of_vname F
    87       val u = string_of_term ctxt env binders t
    88     in tracing ("Variable " ^ f ^ " occurs in term\n" ^ u ^ "\nCannot unify!\n") end
    89   else ();
    90 
    91 fun occurs(F,t,env) =
    92     let fun occ(Var (G, T))   = (case Envir.lookup env (G, T) of
    93                                  SOME(t) => occ t
    94                                | NONE    => F=G)
    95           | occ(t1$t2)      = occ t1 orelse occ t2
    96           | occ(Abs(_,_,t)) = occ t
    97           | occ _           = false
    98     in occ t end;
    99 
   100 
   101 fun mapbnd f =
   102     let fun mpb d (Bound(i))     = if i < d then Bound(i) else Bound(f(i-d)+d)
   103           | mpb d (Abs(s,T,t))   = Abs(s,T,mpb(d+1) t)
   104           | mpb d ((u1 $ u2))    = (mpb d u1)$(mpb d u2)
   105           | mpb _ atom           = atom
   106     in mpb 0 end;
   107 
   108 fun idx [] j     = raise Unif
   109   | idx(i::is) j = if (i:int) =j then length is else idx is j;
   110 
   111 fun mkabs (binders,is,t)  =
   112     let fun mk(i::is) = let val (x,T) = nth binders i
   113                         in Abs(x,T,mk is) end
   114           | mk []     = t
   115     in mk is end;
   116 
   117 val incr = mapbnd (fn i => i+1);
   118 
   119 fun ints_of []             = []
   120   | ints_of (Bound i ::bs) =
   121       let val is = ints_of bs
   122       in if member (op =) is i then raise Pattern else i::is end
   123   | ints_of _              = raise Pattern;
   124 
   125 fun ints_of' env ts = ints_of (map (Envir.head_norm env) ts);
   126 
   127 
   128 fun app (s,(i::is)) = app (s$Bound(i),is)
   129   | app (s,[])      = s;
   130 
   131 fun red (Abs(_,_,s)) (i::is) js = red s is (i::js)
   132   | red t            []      [] = t
   133   | red t            is      jn = app (mapbnd (nth jn) t,is);
   134 
   135 
   136 (* split_type ([T1,....,Tn]---> T,n,[]) = ([Tn,...,T1],T) *)
   137 fun split_type (T,0,Ts)                    = (Ts,T)
   138   | split_type (Type ("fun",[T1,T2]),n,Ts) = split_type (T2,n-1,T1::Ts)
   139   | split_type _                           = raise Fail "split_type";
   140 
   141 fun type_of_G env (T, n, is) =
   142   let
   143     val tyenv = Envir.type_env env;
   144     val (Ts, U) = split_type (Envir.norm_type tyenv T, n, []);
   145   in map (nth Ts) is ---> U end;
   146 
   147 fun mk_hnf (binders,is,G,js) = mkabs (binders, is, app(G,js));
   148 
   149 fun mk_new_hnf(env,binders,is,F as (a,_),T,js) =
   150   let val (env',G) = Envir.genvar a (env,type_of_G env (T,length is,js))
   151   in Envir.update ((F, T), mk_hnf (binders, is, G, js)) env' end;
   152 
   153 
   154 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   155 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   156   | downto0 ([], n) = n = ~1;
   157 
   158 (*mk_proj_list(is) = [ |is| - k | 1 <= k <= |is| and is[k] >= 0 ]*)
   159 fun mk_proj_list is =
   160     let fun mk(i::is,j) = if is_some i then j :: mk(is,j-1) else mk(is,j-1)
   161           | mk([],_)    = []
   162     in mk(is,length is - 1) end;
   163 
   164 fun proj(s,env,binders,is) =
   165     let fun trans d i = if i<d then i else (idx is (i-d))+d;
   166         fun pr(s,env,d,binders) = (case Envir.head_norm env s of
   167               Abs(a,T,t) => let val (t',env') = pr(t,env,d+1,((a,T)::binders))
   168                             in (Abs(a,T,t'),env') end
   169             | t => (case strip_comb t of
   170                 (c as Const _,ts) =>
   171                          let val (ts',env') = prs(ts,env,d,binders)
   172                          in (list_comb(c,ts'),env') end
   173                  | (f as Free _,ts) =>
   174                          let val (ts',env') = prs(ts,env,d,binders)
   175                          in (list_comb(f,ts'),env') end
   176                  | (Bound(i),ts) =>
   177                          let val j = trans d i
   178                              val (ts',env') = prs(ts,env,d,binders)
   179                          in (list_comb(Bound j,ts'),env') end
   180                  | (Var(F as (a,_),Fty),ts) =>
   181                       let val js = ints_of' env ts;
   182                           val js' = map (try (trans d)) js;
   183                           val ks = mk_proj_list js';
   184                           val ls = map_filter I js'
   185                           val Hty = type_of_G env (Fty,length js,ks)
   186                           val (env',H) = Envir.genvar a (env,Hty)
   187                           val env'' =
   188                             Envir.update ((F, Fty), mk_hnf (binders, js, H, ks)) env'
   189                       in (app(H,ls),env'') end
   190                  | _  => raise Pattern))
   191         and prs(s::ss,env,d,binders) =
   192               let val (s',env1) = pr(s,env,d,binders)
   193                   val (ss',env2) = prs(ss,env1,d,binders)
   194               in (s'::ss',env2) end
   195           | prs([],env,_,_) = ([],env)
   196    in if downto0(is,length binders - 1) then (s,env)
   197       else pr(s,env,0,binders)
   198    end;
   199 
   200 
   201 (* mk_ff_list(is,js) = [ length(is) - k | 1 <= k <= |is| and is[k] = js[k] ] *)
   202 fun mk_ff_list(is,js) =
   203     let fun mk([],[],_)        = []
   204           | mk(i::is,j::js, k) = if (i:int) = j then k :: mk(is,js,k-1)
   205                                         else mk(is,js,k-1)
   206           | mk _               = raise Fail "mk_ff_list"
   207     in mk(is,js,length is-1) end;
   208 
   209 fun flexflex1(env,binders,F,Fty,is,js) =
   210   if is=js then env
   211   else let val ks = mk_ff_list(is,js)
   212        in mk_new_hnf(env,binders,is,F,Fty,ks) end;
   213 
   214 fun flexflex2(env,binders,F,Fty,is,G,Gty,js) =
   215   let fun ff(F,Fty,is,G as (a,_),Gty,js) =
   216             if subset (op =) (js, is)
   217             then let val t= mkabs(binders,is,app(Var(G,Gty),map (idx is) js))
   218                  in Envir.update ((F, Fty), t) env end
   219             else let val ks = inter (op =) js is
   220                      val Hty = type_of_G env (Fty,length is,map (idx is) ks)
   221                      val (env',H) = Envir.genvar a (env,Hty)
   222                      fun lam(is) = mkabs(binders,is,app(H,map (idx is) ks));
   223                  in Envir.update ((G, Gty), lam js) (Envir.update ((F, Fty), lam is) env')
   224                  end;
   225   in if Term_Ord.indexname_ord (G,F) = LESS then ff(F,Fty,is,G,Gty,js) else ff(G,Gty,js,F,Fty,is) end
   226 
   227 fun unify_types context (T, U) (env as Envir.Envir {maxidx, tenv, tyenv}) =
   228   if T = U then env
   229   else
   230     let
   231       val thy = Context.theory_of context
   232       val (tyenv', maxidx') = Sign.typ_unify thy (U, T) (tyenv, maxidx)
   233     in Envir.Envir {maxidx = maxidx', tenv = tenv, tyenv = tyenv'} end
   234     handle Type.TUNIFY => (typ_clash context (tyenv, T, U); raise Unif);
   235 
   236 fun unif context binders (s,t) env = case (Envir.head_norm env s, Envir.head_norm env t) of
   237       (Abs(ns,Ts,ts),Abs(nt,Tt,tt)) =>
   238          let val name = if ns = "" then nt else ns
   239          in unif context ((name,Ts)::binders) (ts,tt) (unify_types context (Ts, Tt) env) end
   240     | (Abs(ns,Ts,ts),t) => unif context ((ns,Ts)::binders) (ts,(incr t)$Bound(0)) env
   241     | (t,Abs(nt,Tt,tt)) => unif context ((nt,Tt)::binders) ((incr t)$Bound(0),tt) env
   242     | p => cases context (binders,env,p)
   243 
   244 and cases context (binders,env,(s,t)) = case (strip_comb s,strip_comb t) of
   245        ((Var(F,Fty),ss),(Var(G,Gty),ts)) =>
   246          if F = G then flexflex1(env,binders,F,Fty,ints_of' env ss,ints_of' env ts)
   247                   else flexflex2(env,binders,F,Fty,ints_of' env ss,G,Gty,ints_of' env ts)
   248       | ((Var(F,Fty),ss),_)           => flexrigid context (env,binders,F,Fty,ints_of' env ss,t)
   249       | (_,(Var(F,Fty),ts))           => flexrigid context (env,binders,F,Fty,ints_of' env ts,s)
   250       | ((Const c,ss),(Const d,ts))   => rigidrigid context (env,binders,c,d,ss,ts)
   251       | ((Free(f),ss),(Free(g),ts))   => rigidrigid context (env,binders,f,g,ss,ts)
   252       | ((Bound(i),ss),(Bound(j),ts)) => rigidrigidB context (env,binders,i,j,ss,ts)
   253       | ((Abs(_),_),_)                => raise Pattern
   254       | (_,(Abs(_),_))                => raise Pattern
   255       | ((Const(c,_),_),(Free(f,_),_)) => (clash context c f; raise Unif)
   256       | ((Const(c,_),_),(Bound i,_))   => (clashB context binders i c; raise Unif)
   257       | ((Free(f,_),_),(Const(c,_),_)) => (clash context f c; raise Unif)
   258       | ((Free(f,_),_),(Bound i,_))    => (clashB context binders i f; raise Unif)
   259       | ((Bound i,_),(Const(c,_),_))   => (clashB context binders i c; raise Unif)
   260       | ((Bound i,_),(Free(f,_),_))    => (clashB context binders i f; raise Unif)
   261 
   262 
   263 and rigidrigid context (env,binders,(a,Ta),(b,Tb),ss,ts) =
   264       if a<>b then (clash context a b; raise Unif)
   265       else env |> unify_types context (Ta,Tb) |> fold (unif context binders) (ss~~ts)
   266 
   267 and rigidrigidB context (env,binders,i,j,ss,ts) =
   268      if i <> j then (clashBB context binders i j; raise Unif)
   269      else fold (unif context binders) (ss~~ts) env
   270 
   271 and flexrigid context (params as (env,binders,F,Fty,is,t)) =
   272       if occurs(F,t,env) then (ocheck_fail context (F,t,binders,env); raise Unif)
   273       else (let val (u,env') = proj(t,env,binders,is)
   274             in Envir.update ((F, Fty), mkabs (binders, is, u)) env' end
   275             handle Unif => (proj_fail context params; raise Unif));
   276 
   277 fun unify context = unif context [];
   278 
   279 
   280 
   281 (*** Matching ***)
   282 
   283 exception MATCH;
   284 
   285 fun typ_match thy TU tyenv = Sign.typ_match thy TU tyenv
   286   handle Type.TYPE_MATCH => raise MATCH;
   287 
   288 (*First-order matching;
   289   The pattern and object may have variables in common.
   290   Instantiation does not affect the object, so matching ?a with ?a+1 works.
   291   Object is eta-contracted on the fly (by eta-expanding the pattern).
   292   Precondition: the pattern is already eta-contracted!
   293   Types are matched on the fly.
   294   The parameter inAbs is an optimization to avoid calling is_open;
   295   it has the funny consequence that outside abstractions
   296   ?x matches terms containing loose Bounds.
   297 *)
   298 fun first_order_match thy =
   299   let
   300     fun mtch inAbs (instsp as (tyinsts,insts)) = fn
   301         (Var(ixn,T), t)  =>
   302           if inAbs andalso Term.is_open t then raise MATCH
   303           else (case Envir.lookup1 insts (ixn, T) of
   304                   NONE => (typ_match thy (T, fastype_of t) tyinsts,
   305                            Vartab.update_new (ixn, (T, t)) insts)
   306                 | SOME u => if Envir.aeconv (t, u) then instsp else raise MATCH)
   307       | (Free (a,T), Free (b,U)) =>
   308           if a=b then (typ_match thy (T,U) tyinsts, insts) else raise MATCH
   309       | (Const (a,T), Const (b,U))  =>
   310           if a=b then (typ_match thy (T,U) tyinsts, insts) else raise MATCH
   311       | (Bound i, Bound j)  =>  if  i=j  then  instsp  else raise MATCH
   312       | (Abs(_,T,t), Abs(_,U,u))  =>
   313           mtch true (typ_match thy (T,U) tyinsts, insts) (t,u)
   314       | (f$t, g$u) => mtch inAbs (mtch inAbs instsp (f,g)) (t, u)
   315       | (t, Abs(_,U,u))  =>  mtch true instsp ((incr t)$(Bound 0), u)
   316       | _ => raise MATCH
   317   in fn tu => fn env => mtch false env tu end;
   318 
   319 
   320 (* Matching of higher-order patterns *)
   321 
   322 fun match_bind(itms,binders,ixn,T,is,t) =
   323   let val js = loose_bnos t
   324   in if null is
   325      then if null js then Vartab.update_new (ixn, (T, t)) itms else raise MATCH
   326      else if subset (op =) (js, is)
   327           then let val t' = if downto0(is,length binders - 1) then t
   328                             else mapbnd (idx is) t
   329                in Vartab.update_new (ixn, (T, mkabs (binders, is, t'))) itms end
   330           else raise MATCH
   331   end;
   332 
   333 fun match thy (po as (pat,obj)) envir =
   334 let
   335   (* Pre: pat and obj have same type *)
   336   fun mtch binders (pat,obj) (env as (iTs,itms)) =
   337     case pat of
   338       Abs(ns,Ts,ts) =>
   339         (case obj of
   340            Abs(nt,Tt,tt) => mtch ((nt,Tt)::binders) (ts,tt) env
   341          | _ => let val Tt = Envir.subst_type iTs Ts
   342                 in mtch((ns,Tt)::binders) (ts,(incr obj)$Bound(0)) env end)
   343     | _ => (case obj of
   344               Abs(nt,Tt,tt) =>
   345                 mtch((nt,Tt)::binders) ((incr pat)$Bound(0),tt) env
   346             | _ => cases(binders,env,pat,obj))
   347 
   348   and cases(binders,env as (iTs,itms),pat,obj) =
   349     let val (ph,pargs) = strip_comb pat
   350         fun rigrig1(iTs,oargs) = fold (mtch binders) (pargs~~oargs) (iTs,itms)
   351           handle ListPair.UnequalLengths => raise MATCH
   352         fun rigrig2((a:string,Ta),(b,Tb),oargs) =
   353               if a <> b then raise MATCH
   354               else rigrig1(typ_match thy (Ta,Tb) iTs, oargs)
   355     in case ph of
   356          Var(ixn,T) =>
   357            let val is = ints_of pargs
   358            in case Envir.lookup1 itms (ixn, T) of
   359                 NONE => (iTs,match_bind(itms,binders,ixn,T,is,obj))
   360               | SOME u => if Envir.aeconv (obj, red u is []) then env
   361                           else raise MATCH
   362            end
   363        | _ =>
   364            let val (oh,oargs) = strip_comb obj
   365            in case (ph,oh) of
   366                 (Const c,Const d) => rigrig2(c,d,oargs)
   367               | (Free f,Free g)   => rigrig2(f,g,oargs)
   368               | (Bound i,Bound j) => if i<>j then raise MATCH
   369                                      else rigrig1(iTs,oargs)
   370               | (Abs _, _)        => raise Pattern
   371               | (_, Abs _)        => raise Pattern
   372               | _                 => raise MATCH
   373            end
   374     end;
   375 
   376   val pT = fastype_of pat
   377   and oT = fastype_of obj
   378   val envir' = apfst (typ_match thy (pT, oT)) envir;
   379 in mtch [] po envir' handle Pattern => first_order_match thy po envir' end;
   380 
   381 end;
   382