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