src/Pure/envir.ML
author wenzelm
Tue Dec 12 20:49:22 2006 +0100 (2006-12-12)
changeset 21795 d7dcc3dfa7e9
parent 21695 6c07cc87fe2b
child 22174 f2bf6bcd4a98
permissions -rw-r--r--
added expand_term_frees;
wenzelm@247
     1
(*  Title:      Pure/envir.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@247
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
clasohm@0
     4
    Copyright   1988  University of Cambridge
wenzelm@10485
     5
berghofe@15797
     6
Environments.  The type of a term variable / sort of a type variable is
berghofe@15797
     7
part of its name. The lookup function must apply type substitutions,
berghofe@15797
     8
since they may change the identity of a variable.
clasohm@0
     9
*)
clasohm@0
    10
wenzelm@247
    11
signature ENVIR =
clasohm@0
    12
sig
berghofe@15797
    13
  type tenv
berghofe@15797
    14
  datatype env = Envir of {asol: tenv, iTs: Type.tyenv, maxidx: int}
berghofe@15797
    15
  val type_env: env -> Type.tyenv
berghofe@11513
    16
  exception SAME
wenzelm@10485
    17
  val genvars: string -> env * typ list -> env * term list
wenzelm@10485
    18
  val genvar: string -> env * typ -> env * term
berghofe@15797
    19
  val lookup: env * (indexname * typ) -> term option
berghofe@16652
    20
  val lookup': tenv * (indexname * typ) -> term option
berghofe@15797
    21
  val update: ((indexname * typ) * term) * env -> env
wenzelm@10485
    22
  val empty: int -> env
wenzelm@10485
    23
  val is_empty: env -> bool
wenzelm@19861
    24
  val above: env -> int -> bool
berghofe@15797
    25
  val vupdate: ((indexname * typ) * term) * env -> env
berghofe@15797
    26
  val alist_of: env -> (indexname * (typ * term)) list
wenzelm@10485
    27
  val norm_term: env -> term -> term
berghofe@11513
    28
  val norm_term_same: env -> term -> term
berghofe@15797
    29
  val norm_type: Type.tyenv -> typ -> typ
berghofe@15797
    30
  val norm_type_same: Type.tyenv -> typ -> typ
berghofe@15797
    31
  val norm_types_same: Type.tyenv -> typ list -> typ list
wenzelm@10485
    32
  val beta_norm: term -> term
berghofe@12231
    33
  val head_norm: env -> term -> term
wenzelm@18937
    34
  val eta_contract: term -> term
wenzelm@18937
    35
  val beta_eta_contract: term -> term
berghofe@12231
    36
  val fastype: env -> typ list -> term -> typ
berghofe@15797
    37
  val typ_subst_TVars: Type.tyenv -> typ -> typ
berghofe@15797
    38
  val subst_TVars: Type.tyenv -> term -> term
berghofe@15797
    39
  val subst_Vars: tenv -> term -> term
berghofe@15797
    40
  val subst_vars: Type.tyenv * tenv -> term -> term
wenzelm@19422
    41
  val expand_atom: typ -> typ * term -> term
wenzelm@21695
    42
  val expand_term: (term -> (typ * term) option) -> term -> term
wenzelm@21795
    43
  val expand_term_frees: ((string * typ) * term) list -> term -> term
clasohm@0
    44
end;
clasohm@0
    45
paulson@1500
    46
structure Envir : ENVIR =
clasohm@0
    47
struct
clasohm@0
    48
clasohm@0
    49
(*updating can destroy environment in 2 ways!!
clasohm@0
    50
   (1) variables out of range   (2) circular assignments
clasohm@0
    51
*)
berghofe@15797
    52
type tenv = (typ * term) Vartab.table
berghofe@15797
    53
clasohm@0
    54
datatype env = Envir of
berghofe@15797
    55
    {maxidx: int,      (*maximum index of vars*)
berghofe@15797
    56
     asol: tenv,       (*table of assignments to Vars*)
berghofe@15797
    57
     iTs: Type.tyenv}  (*table of assignments to TVars*)
clasohm@0
    58
wenzelm@12496
    59
fun type_env (Envir {iTs, ...}) = iTs;
clasohm@0
    60
clasohm@0
    61
(*Generate a list of distinct variables.
clasohm@0
    62
  Increments index to make them distinct from ALL present variables. *)
clasohm@0
    63
fun genvars name (Envir{maxidx, asol, iTs}, Ts) : env * term list =
clasohm@0
    64
  let fun genvs (_, [] : typ list) : term list = []
clasohm@0
    65
        | genvs (n, [T]) = [ Var((name, maxidx+1), T) ]
clasohm@0
    66
        | genvs (n, T::Ts) =
wenzelm@247
    67
            Var((name ^ radixstring(26,"a",n), maxidx+1), T)
wenzelm@247
    68
            :: genvs(n+1,Ts)
clasohm@0
    69
  in  (Envir{maxidx=maxidx+1, asol=asol, iTs=iTs}, genvs (0,Ts))  end;
clasohm@0
    70
clasohm@0
    71
(*Generate a variable.*)
clasohm@0
    72
fun genvar name (env,T) : env * term =
wenzelm@247
    73
  let val (env',[v]) = genvars name (env,[T])
clasohm@0
    74
  in  (env',v)  end;
clasohm@0
    75
berghofe@15797
    76
fun var_clash ixn T T' = raise TYPE ("Variable " ^
berghofe@15797
    77
  quote (Syntax.string_of_vname ixn) ^ " has two distinct types",
berghofe@15797
    78
  [T', T], []);
clasohm@0
    79
berghofe@15797
    80
fun gen_lookup f asol (xname, T) =
wenzelm@17412
    81
  (case Vartab.lookup asol xname of
berghofe@15797
    82
     NONE => NONE
berghofe@15797
    83
   | SOME (U, t) => if f (T, U) then SOME t
berghofe@15797
    84
       else var_clash xname T U);
berghofe@15797
    85
berghofe@16652
    86
(* When dealing with environments produced by matching instead *)
berghofe@16652
    87
(* of unification, there is no need to chase assigned TVars.   *)
berghofe@16652
    88
(* In this case, we can simply ignore the type substitution    *)
berghofe@16652
    89
(* and use = instead of eq_type.                               *)
berghofe@15797
    90
berghofe@16652
    91
fun lookup' (asol, p) = gen_lookup op = asol p;
berghofe@15797
    92
berghofe@16652
    93
fun lookup2 (iTs, asol) p =
berghofe@16652
    94
  if Vartab.is_empty iTs then lookup' (asol, p)
berghofe@16652
    95
  else gen_lookup (Type.eq_type iTs) asol p;
berghofe@15797
    96
berghofe@15797
    97
fun lookup (Envir {asol, iTs, ...}, p) = lookup2 (iTs, asol) p;
berghofe@15797
    98
berghofe@15797
    99
fun update (((xname, T), t), Envir {maxidx, asol, iTs}) =
wenzelm@17412
   100
  Envir{maxidx=maxidx, asol=Vartab.update_new (xname, (T, t)) asol, iTs=iTs};
clasohm@0
   101
wenzelm@5289
   102
(*The empty environment.  New variables will start with the given index+1.*)
berghofe@8407
   103
fun empty m = Envir{maxidx=m, asol=Vartab.empty, iTs=Vartab.empty};
clasohm@0
   104
paulson@2142
   105
(*Test for empty environment*)
berghofe@8407
   106
fun is_empty (Envir {asol, iTs, ...}) = Vartab.is_empty asol andalso Vartab.is_empty iTs;
wenzelm@247
   107
paulson@2142
   108
(*Determine if the least index updated exceeds lim*)
wenzelm@19861
   109
fun above (Envir {asol, iTs, ...}) lim =
wenzelm@19861
   110
  (case Vartab.min_key asol of SOME (_, i) => i > lim | NONE => true) andalso
wenzelm@19861
   111
  (case Vartab.min_key iTs of SOME (_, i) => i > lim | NONE => true);
wenzelm@247
   112
clasohm@0
   113
(*Update, checking Var-Var assignments: try to suppress higher indexes*)
berghofe@15797
   114
fun vupdate ((aU as (a, U), t), env as Envir {iTs, ...}) = case t of
berghofe@15797
   115
      Var (nT as (name', T)) =>
berghofe@15797
   116
        if a = name' then env     (*cycle!*)
wenzelm@20098
   117
        else if Term.indexname_ord (a, name') = LESS then
berghofe@15797
   118
           (case lookup (env, nT) of  (*if already assigned, chase*)
berghofe@15797
   119
                NONE => update ((nT, Var (a, T)), env)
berghofe@15797
   120
              | SOME u => vupdate ((aU, u), env))
berghofe@15797
   121
        else update ((aU, t), env)
berghofe@15797
   122
    | _ => update ((aU, t), env);
clasohm@0
   123
clasohm@0
   124
clasohm@0
   125
(*Convert environment to alist*)
berghofe@8407
   126
fun alist_of (Envir{asol,...}) = Vartab.dest asol;
clasohm@0
   127
clasohm@0
   128
paulson@1500
   129
(*** Beta normal form for terms (not eta normal form).
paulson@1500
   130
     Chases variables in env;  Does not exploit sharing of variable bindings
paulson@1500
   131
     Does not check types, so could loop. ***)
paulson@1500
   132
paulson@1500
   133
(*raised when norm has no effect on a term, to do sharing instead of copying*)
paulson@1500
   134
exception SAME;
clasohm@0
   135
berghofe@11513
   136
fun norm_term1 same (asol,t) : term =
berghofe@15797
   137
  let fun norm (Var wT) =
berghofe@16652
   138
            (case lookup' (asol, wT) of
skalberg@15531
   139
                SOME u => (norm u handle SAME => u)
skalberg@15531
   140
              | NONE   => raise SAME)
wenzelm@10485
   141
        | norm (Abs(a,T,body)) =  Abs(a, T, norm body)
wenzelm@10485
   142
        | norm (Abs(_,_,body) $ t) = normh(subst_bound (t, body))
wenzelm@10485
   143
        | norm (f $ t) =
wenzelm@10485
   144
            ((case norm f of
wenzelm@10485
   145
               Abs(_,_,body) => normh(subst_bound (t, body))
wenzelm@10485
   146
             | nf => nf $ (norm t handle SAME => t))
wenzelm@10485
   147
            handle SAME => f $ norm t)
wenzelm@10485
   148
        | norm _ =  raise SAME
paulson@2191
   149
      and normh t = norm t handle SAME => t
berghofe@11513
   150
  in (if same then norm else normh) t end
clasohm@0
   151
berghofe@11513
   152
fun normT iTs (Type (a, Ts)) = Type (a, normTs iTs Ts)
berghofe@11513
   153
  | normT iTs (TFree _) = raise SAME
berghofe@15797
   154
  | normT iTs (TVar vS) = (case Type.lookup (iTs, vS) of
skalberg@15531
   155
          SOME U => normTh iTs U
skalberg@15531
   156
        | NONE => raise SAME)
berghofe@11513
   157
and normTh iTs T = ((normT iTs T) handle SAME => T)
berghofe@11513
   158
and normTs iTs [] = raise SAME
berghofe@11513
   159
  | normTs iTs (T :: Ts) =
berghofe@11513
   160
      ((normT iTs T :: (normTs iTs Ts handle SAME => Ts))
berghofe@11513
   161
       handle SAME => T :: normTs iTs Ts);
berghofe@11513
   162
berghofe@11513
   163
fun norm_term2 same (asol, iTs, t) : term =
berghofe@11513
   164
  let fun norm (Const (a, T)) = Const(a, normT iTs T)
berghofe@11513
   165
        | norm (Free (a, T)) = Free(a, normT iTs T)
berghofe@11513
   166
        | norm (Var (w, T)) =
berghofe@15797
   167
            (case lookup2 (iTs, asol) (w, T) of
skalberg@15531
   168
                SOME u => normh u
skalberg@15531
   169
              | NONE   => Var(w, normT iTs T))
berghofe@11513
   170
        | norm (Abs (a, T, body)) =
berghofe@11513
   171
               (Abs (a, normT iTs T, normh body) handle SAME => Abs (a, T, norm body))
berghofe@11513
   172
        | norm (Abs(_, _, body) $ t) = normh (subst_bound (t, body))
berghofe@11513
   173
        | norm (f $ t) =
wenzelm@10485
   174
            ((case norm f of
berghofe@11513
   175
               Abs(_, _, body) => normh (subst_bound (t, body))
wenzelm@10485
   176
             | nf => nf $ normh t)
wenzelm@10485
   177
            handle SAME => f $ norm t)
wenzelm@10485
   178
        | norm _ =  raise SAME
paulson@1500
   179
      and normh t = (norm t) handle SAME => t
berghofe@11513
   180
  in (if same then norm else normh) t end;
clasohm@0
   181
berghofe@11513
   182
fun gen_norm_term same (env as Envir{asol,iTs,...}) t : term =
berghofe@11513
   183
  if Vartab.is_empty iTs then norm_term1 same (asol, t)
berghofe@11513
   184
  else norm_term2 same (asol, iTs, t);
berghofe@11513
   185
berghofe@11513
   186
val norm_term = gen_norm_term false;
berghofe@11513
   187
val norm_term_same = gen_norm_term true;
wenzelm@10485
   188
wenzelm@10485
   189
val beta_norm = norm_term (empty 0);
lcp@719
   190
wenzelm@12496
   191
fun norm_type iTs = normTh iTs;
wenzelm@12496
   192
fun norm_type_same iTs =
berghofe@11513
   193
  if Vartab.is_empty iTs then raise SAME else normT iTs;
berghofe@11513
   194
wenzelm@12496
   195
fun norm_types_same iTs =
berghofe@11513
   196
  if Vartab.is_empty iTs then raise SAME else normTs iTs;
berghofe@11513
   197
berghofe@11513
   198
berghofe@12231
   199
(*Put a term into head normal form for unification.*)
berghofe@12231
   200
berghofe@12231
   201
fun head_norm env t =
berghofe@12231
   202
  let
berghofe@15797
   203
    fun hnorm (Var vT) = (case lookup (env, vT) of
skalberg@15531
   204
          SOME u => head_norm env u
skalberg@15531
   205
        | NONE => raise SAME)
berghofe@12231
   206
      | hnorm (Abs (a, T, body)) =  Abs (a, T, hnorm body)
berghofe@12231
   207
      | hnorm (Abs (_, _, body) $ t) =
berghofe@12231
   208
          head_norm env (subst_bound (t, body))
berghofe@12231
   209
      | hnorm (f $ t) = (case hnorm f of
berghofe@12231
   210
          Abs (_, _, body) => head_norm env (subst_bound (t, body))
berghofe@12231
   211
        | nf => nf $ t)
wenzelm@20670
   212
          | hnorm _ =  raise SAME
berghofe@12231
   213
  in hnorm t handle SAME => t end;
berghofe@12231
   214
berghofe@12231
   215
wenzelm@18937
   216
(*Eta-contract a term (fully)*)
wenzelm@18937
   217
wenzelm@18937
   218
fun eta_contract t =
wenzelm@18937
   219
  let
wenzelm@20670
   220
    fun decr lev (Bound i) = if i >= lev then Bound (i - 1) else raise SAME
wenzelm@20670
   221
      | decr lev (Abs (a, T, body)) = Abs (a, T, decr (lev + 1) body)
wenzelm@20670
   222
      | decr lev (t $ u) = (decr lev t $ decrh lev u handle SAME => t $ decr lev u)
wenzelm@20670
   223
      | decr _ _ = raise SAME
wenzelm@20670
   224
    and decrh lev t = (decr lev t handle SAME => t);
wenzelm@20670
   225
wenzelm@18937
   226
    fun eta (Abs (a, T, body)) =
wenzelm@20670
   227
        ((case eta body of
wenzelm@20670
   228
            body' as (f $ Bound 0) =>
wenzelm@20670
   229
              if loose_bvar1 (f, 0) then Abs (a, T, body')
wenzelm@20670
   230
              else decrh 0 f
wenzelm@20670
   231
         | body' => Abs (a, T, body')) handle SAME =>
wenzelm@20670
   232
            (case body of
wenzelm@20670
   233
              f $ Bound 0 =>
wenzelm@20670
   234
                if loose_bvar1 (f, 0) then raise SAME
wenzelm@20670
   235
                else decrh 0 f
wenzelm@20670
   236
            | _ => raise SAME))
wenzelm@20670
   237
      | eta (t $ u) = (eta t $ etah u handle SAME => t $ eta u)
wenzelm@18937
   238
      | eta _ = raise SAME
wenzelm@20670
   239
    and etah t = (eta t handle SAME => t);
wenzelm@18937
   240
  in etah t end;
wenzelm@18937
   241
wenzelm@18937
   242
val beta_eta_contract = eta_contract o beta_norm;
wenzelm@18937
   243
wenzelm@18937
   244
berghofe@12231
   245
(*finds type of term without checking that combinations are consistent
berghofe@12231
   246
  Ts holds types of bound variables*)
berghofe@12231
   247
fun fastype (Envir {iTs, ...}) =
berghofe@12231
   248
let val funerr = "fastype: expected function type";
berghofe@12231
   249
    fun fast Ts (f $ u) =
wenzelm@20670
   250
        (case fast Ts f of
wenzelm@20670
   251
           Type ("fun", [_, T]) => T
wenzelm@20670
   252
         | TVar ixnS =>
wenzelm@20670
   253
                (case Type.lookup (iTs, ixnS) of
wenzelm@20670
   254
                   SOME (Type ("fun", [_, T])) => T
wenzelm@20670
   255
                 | _ => raise TERM (funerr, [f $ u]))
wenzelm@20670
   256
         | _ => raise TERM (funerr, [f $ u]))
berghofe@12231
   257
      | fast Ts (Const (_, T)) = T
berghofe@12231
   258
      | fast Ts (Free (_, T)) = T
berghofe@12231
   259
      | fast Ts (Bound i) =
wenzelm@20670
   260
        (List.nth (Ts, i)
wenzelm@20670
   261
         handle Subscript => raise TERM ("fastype: Bound", [Bound i]))
wenzelm@20670
   262
      | fast Ts (Var (_, T)) = T
berghofe@12231
   263
      | fast Ts (Abs (_, T, u)) = T --> fast (T :: Ts) u
berghofe@12231
   264
in fast end;
berghofe@12231
   265
berghofe@15797
   266
berghofe@15797
   267
(*Substitute for type Vars in a type*)
berghofe@15797
   268
fun typ_subst_TVars iTs T = if Vartab.is_empty iTs then T else
berghofe@15797
   269
  let fun subst(Type(a, Ts)) = Type(a, map subst Ts)
berghofe@15797
   270
        | subst(T as TFree _) = T
berghofe@15797
   271
        | subst(T as TVar ixnS) =
berghofe@15797
   272
            (case Type.lookup (iTs, ixnS) of NONE => T | SOME(U) => U)
berghofe@15797
   273
  in subst T end;
berghofe@15797
   274
berghofe@15797
   275
(*Substitute for type Vars in a term*)
wenzelm@20548
   276
val subst_TVars = map_types o typ_subst_TVars;
berghofe@15797
   277
berghofe@15797
   278
(*Substitute for Vars in a term *)
berghofe@15797
   279
fun subst_Vars itms t = if Vartab.is_empty itms then t else
wenzelm@18937
   280
  let fun subst (v as Var ixnT) = the_default v (lookup' (itms, ixnT))
berghofe@15797
   281
        | subst (Abs (a, T, t)) = Abs (a, T, subst t)
berghofe@15797
   282
        | subst (f $ t) = subst f $ subst t
berghofe@15797
   283
        | subst t = t
berghofe@15797
   284
  in subst t end;
berghofe@15797
   285
berghofe@15797
   286
(*Substitute for type/term Vars in a term *)
berghofe@16652
   287
fun subst_vars (iTs, itms) =
berghofe@15797
   288
  if Vartab.is_empty iTs then subst_Vars itms else
berghofe@15797
   289
  let fun subst (Const (a, T)) = Const(a, typ_subst_TVars iTs T)
berghofe@15797
   290
        | subst (Free (a, T)) = Free (a, typ_subst_TVars iTs T)
berghofe@16652
   291
        | subst (Var (ixn, T)) = (case lookup' (itms, (ixn, T)) of
berghofe@15797
   292
            NONE   => Var (ixn, typ_subst_TVars iTs T)
berghofe@15797
   293
          | SOME t => t)
berghofe@15797
   294
        | subst (b as Bound _) = b
berghofe@15797
   295
        | subst (Abs (a, T, t)) = Abs(a, typ_subst_TVars iTs T, subst t)
berghofe@15797
   296
        | subst (f $ t) = subst f $ subst t
berghofe@15797
   297
  in subst end;
berghofe@15797
   298
wenzelm@18937
   299
wenzelm@21795
   300
(* expand defined atoms -- with local beta reduction *)
wenzelm@18937
   301
wenzelm@19422
   302
fun expand_atom T (U, u) =
wenzelm@19422
   303
  subst_TVars (Type.raw_match (U, T) Vartab.empty) u
wenzelm@18937
   304
  handle Type.TYPE_MATCH => raise TYPE ("expand_atom: ill-typed replacement", [T, U], [u]);
wenzelm@18937
   305
wenzelm@21795
   306
fun expand_term get =
wenzelm@21695
   307
  let
wenzelm@21695
   308
    fun expand tm =
wenzelm@21695
   309
      let
wenzelm@21695
   310
        val (head, args) = Term.strip_comb tm;
wenzelm@21695
   311
        val args' = map expand args;
wenzelm@21695
   312
        fun comb head' = Term.list_comb (head', args');
wenzelm@21695
   313
      in
wenzelm@21695
   314
        (case head of
wenzelm@21695
   315
          Abs (x, T, t) => comb (Abs (x, T, expand t))
wenzelm@21695
   316
        | _ =>
wenzelm@21795
   317
            (case get head of
wenzelm@21695
   318
              SOME def => Term.betapplys (expand_atom (Term.fastype_of head) def, args')
wenzelm@21695
   319
            | NONE => comb head)
wenzelm@21695
   320
        | _ => comb head)
wenzelm@21695
   321
      end;
wenzelm@21695
   322
  in expand end;
wenzelm@21695
   323
wenzelm@21795
   324
fun expand_term_frees defs =
wenzelm@21795
   325
  let
wenzelm@21795
   326
    val eqs = map (fn ((x, U), u) => (x, (U, u))) defs;
wenzelm@21795
   327
    val get = fn Free (x, _) => AList.lookup (op =) eqs x | _ => NONE;
wenzelm@21795
   328
  in expand_term get end;
wenzelm@21795
   329
clasohm@0
   330
end;