src/Tools/nbe.ML
author wenzelm
Fri Mar 21 20:33:56 2014 +0100 (2014-03-21)
changeset 56245 84fc7dfa3cd4
parent 55757 9fc71814b8c1
child 56920 d651b944c67e
permissions -rw-r--r--
more qualified names;
haftmann@24590
     1
(*  Title:      Tools/nbe.ML
haftmann@24155
     2
    Authors:    Klaus Aehlig, LMU Muenchen; Tobias Nipkow, Florian Haftmann, TU Muenchen
haftmann@24155
     3
haftmann@24839
     4
Normalization by evaluation, based on generic code generator.
haftmann@24155
     5
*)
haftmann@24155
     6
haftmann@24155
     7
signature NBE =
haftmann@24155
     8
sig
haftmann@55757
     9
  val dynamic_conv: Proof.context -> conv
haftmann@55757
    10
  val dynamic_value: Proof.context -> term -> term
haftmann@55757
    11
  val static_conv: Proof.context -> string list -> Proof.context -> conv
haftmann@55757
    12
  val static_value: Proof.context -> string list -> Proof.context -> term -> term
haftmann@25101
    13
wenzelm@25204
    14
  datatype Univ =
haftmann@26064
    15
      Const of int * Univ list               (*named (uninterpreted) constants*)
haftmann@25924
    16
    | DFree of string * int                  (*free (uninterpreted) dictionary parameters*)
haftmann@24155
    17
    | BVar of int * Univ list
haftmann@28350
    18
    | Abs of (int * (Univ list -> Univ)) * Univ list
haftmann@25924
    19
  val apps: Univ -> Univ list -> Univ        (*explicit applications*)
haftmann@25944
    20
  val abss: int -> (Univ list -> Univ) -> Univ
haftmann@28337
    21
                                             (*abstractions as closures*)
haftmann@41037
    22
  val same: Univ * Univ -> bool
haftmann@24155
    23
haftmann@39388
    24
  val put_result: (unit -> Univ list -> Univ list) -> Proof.context -> Proof.context
wenzelm@32740
    25
  val trace: bool Unsynchronized.ref
haftmann@25924
    26
haftmann@26747
    27
  val setup: theory -> theory
haftmann@32544
    28
  val add_const_alias: thm -> theory -> theory
haftmann@24155
    29
end;
haftmann@24155
    30
haftmann@24155
    31
structure Nbe: NBE =
haftmann@24155
    32
struct
haftmann@24155
    33
haftmann@24155
    34
(* generic non-sense *)
haftmann@24155
    35
wenzelm@32740
    36
val trace = Unsynchronized.ref false;
haftmann@32544
    37
fun traced f x = if !trace then (tracing (f x); x) else x;
haftmann@24155
    38
haftmann@24155
    39
haftmann@32544
    40
(** certificates and oracle for "trivial type classes" **)
haftmann@32544
    41
wenzelm@33522
    42
structure Triv_Class_Data = Theory_Data
haftmann@32544
    43
(
haftmann@32544
    44
  type T = (class * thm) list;
haftmann@32544
    45
  val empty = [];
haftmann@32544
    46
  val extend = I;
wenzelm@33522
    47
  fun merge data : T = AList.merge (op =) (K true) data;
haftmann@32544
    48
);
haftmann@32544
    49
haftmann@32544
    50
fun add_const_alias thm thy =
haftmann@32544
    51
  let
haftmann@32544
    52
    val (ofclass, eqn) = case try Logic.dest_equals (Thm.prop_of thm)
haftmann@32544
    53
     of SOME ofclass_eq => ofclass_eq
haftmann@32544
    54
      | _ => error ("Bad certificate: " ^ Display.string_of_thm_global thy thm);
haftmann@32544
    55
    val (T, class) = case try Logic.dest_of_class ofclass
haftmann@32544
    56
     of SOME T_class => T_class
haftmann@32544
    57
      | _ => error ("Bad certificate: " ^ Display.string_of_thm_global thy thm);
haftmann@32544
    58
    val tvar = case try Term.dest_TVar T
wenzelm@51685
    59
     of SOME (tvar as (_, sort)) => if null (filter (can (Axclass.get_info thy)) sort)
haftmann@32544
    60
          then tvar
haftmann@32544
    61
          else error ("Bad sort: " ^ Display.string_of_thm_global thy thm)
haftmann@32544
    62
      | _ => error ("Bad type: " ^ Display.string_of_thm_global thy thm);
haftmann@32544
    63
    val _ = if Term.add_tvars eqn [] = [tvar] then ()
haftmann@32544
    64
      else error ("Inconsistent type: " ^ Display.string_of_thm_global thy thm);
haftmann@32544
    65
    val lhs_rhs = case try Logic.dest_equals eqn
haftmann@32544
    66
     of SOME lhs_rhs => lhs_rhs
haftmann@32544
    67
      | _ => error ("Not an equation: " ^ Syntax.string_of_term_global thy eqn);
wenzelm@51685
    68
    val c_c' = case try (pairself (Axclass.unoverload_const thy o dest_Const)) lhs_rhs
haftmann@32544
    69
     of SOME c_c' => c_c'
haftmann@32544
    70
      | _ => error ("Not an equation with two constants: "
haftmann@32544
    71
          ^ Syntax.string_of_term_global thy eqn);
wenzelm@51685
    72
    val _ = if the_list (Axclass.class_of_param thy (snd c_c')) = [class] then ()
haftmann@32544
    73
      else error ("Inconsistent class: " ^ Display.string_of_thm_global thy thm);
haftmann@32544
    74
  in Triv_Class_Data.map (AList.update (op =) (class, thm)) thy end;
haftmann@32544
    75
haftmann@32544
    76
local
haftmann@32544
    77
haftmann@32544
    78
val get_triv_classes = map fst o Triv_Class_Data.get;
haftmann@32544
    79
haftmann@32544
    80
val (_, triv_of_class) = Context.>>> (Context.map_theory_result
wenzelm@43619
    81
  (Thm.add_oracle (@{binding triv_of_class}, fn (thy, T, class) =>
haftmann@32544
    82
    Thm.cterm_of thy (Logic.mk_of_class (T, class)))));
haftmann@32544
    83
haftmann@32544
    84
in
haftmann@32544
    85
haftmann@55757
    86
fun lift_triv_classes_conv ctxt conv ct =
haftmann@32544
    87
  let
haftmann@55757
    88
    val thy = Proof_Context.theory_of ctxt;
haftmann@32544
    89
    val algebra = Sign.classes_of thy;
haftmann@36982
    90
    val certT = Thm.ctyp_of thy;
haftmann@32544
    91
    val triv_classes = get_triv_classes thy;
haftmann@36982
    92
    fun additional_classes sort = filter_out (fn class => Sorts.sort_le algebra (sort, [class])) triv_classes;
haftmann@36982
    93
    fun mk_entry (v, sort) =
haftmann@36982
    94
      let
haftmann@36982
    95
        val T = TFree (v, sort);
haftmann@36982
    96
        val cT = certT T;
haftmann@36982
    97
        val triv_sort = additional_classes sort;
haftmann@36982
    98
      in
haftmann@36982
    99
        (v, (Sorts.inter_sort algebra (sort, triv_sort),
haftmann@36982
   100
          (cT, AList.make (fn class => Thm.of_class (cT, class)) sort
haftmann@36982
   101
            @ AList.make (fn class => triv_of_class (thy, T, class)) triv_sort)))
haftmann@36982
   102
      end;
haftmann@36982
   103
    val vs_tab = map mk_entry (Term.add_tfrees (Thm.term_of ct) []);
haftmann@36982
   104
    fun instantiate thm =
haftmann@36982
   105
      let
haftmann@36982
   106
        val cert_tvars = map (certT o TVar) (Term.add_tvars
haftmann@36982
   107
          ((fst o Logic.dest_equals o Logic.strip_imp_concl o Thm.prop_of) thm) []);
haftmann@36982
   108
        val instantiation =
haftmann@36982
   109
          map2 (fn cert_tvar => fn (_, (_, (cT, _))) => (cert_tvar, cT)) cert_tvars vs_tab;
haftmann@36982
   110
      in Thm.instantiate (instantiation, []) thm end;
haftmann@36982
   111
    fun of_class (TFree (v, _), class) =
haftmann@36982
   112
          the (AList.lookup (op =) ((snd o snd o the o AList.lookup (op =) vs_tab) v) class)
haftmann@36982
   113
      | of_class (T, _) = error ("Bad type " ^ Syntax.string_of_typ_global thy T);
haftmann@32544
   114
    fun strip_of_class thm =
haftmann@32544
   115
      let
haftmann@36982
   116
        val prems_of_class = Thm.prop_of thm
haftmann@36982
   117
          |> Logic.strip_imp_prems
haftmann@36982
   118
          |> map (Logic.dest_of_class #> of_class);
haftmann@36982
   119
      in fold Thm.elim_implies prems_of_class thm end;
wenzelm@36770
   120
  in
wenzelm@36770
   121
    ct
haftmann@36982
   122
    |> (Drule.cterm_fun o map_types o map_type_tfree)
haftmann@47609
   123
        (fn (v, _) => TFree (v, (fst o the o AList.lookup (op =) vs_tab) v))
haftmann@32544
   124
    |> conv
haftmann@36982
   125
    |> Thm.strip_shyps
wenzelm@35845
   126
    |> Thm.varifyT_global
haftmann@36982
   127
    |> Thm.unconstrainT
haftmann@36982
   128
    |> instantiate
haftmann@32544
   129
    |> strip_of_class
haftmann@32544
   130
  end;
haftmann@32544
   131
haftmann@55757
   132
fun lift_triv_classes_rew ctxt rew t =
haftmann@32544
   133
  let
haftmann@55757
   134
    val thy = Proof_Context.theory_of ctxt;
haftmann@32544
   135
    val algebra = Sign.classes_of thy;
haftmann@32544
   136
    val triv_classes = get_triv_classes thy;
haftmann@32544
   137
    val vs = Term.add_tfrees t [];
haftmann@52473
   138
  in
haftmann@52473
   139
    t
haftmann@32544
   140
    |> (map_types o map_type_tfree)
haftmann@32544
   141
        (fn (v, sort) => TFree (v, Sorts.inter_sort algebra (sort, triv_classes)))
haftmann@32544
   142
    |> rew
haftmann@32544
   143
    |> (map_types o map_type_tfree)
haftmann@52473
   144
        (fn (v, sort) => TFree (v, the_default sort (AList.lookup (op =) vs v)))
haftmann@32544
   145
  end;
haftmann@32544
   146
haftmann@32544
   147
end;
haftmann@32544
   148
haftmann@32544
   149
haftmann@32544
   150
(** the semantic universe **)
haftmann@24155
   151
haftmann@24155
   152
(*
haftmann@24155
   153
   Functions are given by their semantical function value. To avoid
haftmann@24155
   154
   trouble with the ML-type system, these functions have the most
haftmann@24155
   155
   generic type, that is "Univ list -> Univ". The calling convention is
haftmann@24155
   156
   that the arguments come as a list, the last argument first. In
haftmann@24155
   157
   other words, a function call that usually would look like
haftmann@24155
   158
haftmann@24155
   159
   f x_1 x_2 ... x_n   or   f(x_1,x_2, ..., x_n)
haftmann@24155
   160
haftmann@24155
   161
   would be in our convention called as
haftmann@24155
   162
haftmann@24155
   163
              f [x_n,..,x_2,x_1]
haftmann@24155
   164
haftmann@24155
   165
   Moreover, to handle functions that are still waiting for some
haftmann@24155
   166
   arguments we have additionally a list of arguments collected to far
haftmann@24155
   167
   and the number of arguments we're still waiting for.
haftmann@24155
   168
*)
haftmann@24155
   169
wenzelm@25204
   170
datatype Univ =
haftmann@26064
   171
    Const of int * Univ list           (*named (uninterpreted) constants*)
haftmann@25924
   172
  | DFree of string * int              (*free (uninterpreted) dictionary parameters*)
haftmann@27499
   173
  | BVar of int * Univ list            (*bound variables, named*)
haftmann@24155
   174
  | Abs of (int * (Univ list -> Univ)) * Univ list
haftmann@27499
   175
                                       (*abstractions as closures*);
haftmann@24155
   176
haftmann@35371
   177
haftmann@24155
   178
(* constructor functions *)
haftmann@24155
   179
haftmann@25944
   180
fun abss n f = Abs ((n, f), []);
haftmann@25924
   181
fun apps (Abs ((n, f), xs)) ys = let val k = n - length ys in
haftmann@27499
   182
      case int_ord (k, 0)
haftmann@27499
   183
       of EQUAL => f (ys @ xs)
haftmann@27499
   184
        | LESS => let val (zs, ws) = chop (~ k) ys in apps (f (ws @ xs)) zs end
haftmann@27499
   185
        | GREATER => Abs ((k, f), ys @ xs) (*note: reverse convention also for apps!*)
haftmann@27499
   186
      end
haftmann@25924
   187
  | apps (Const (name, xs)) ys = Const (name, ys @ xs)
haftmann@27499
   188
  | apps (BVar (n, xs)) ys = BVar (n, ys @ xs);
haftmann@24155
   189
haftmann@41037
   190
fun same (Const (k, xs), Const (l, ys)) = k = l andalso eq_list same (xs, ys)
haftmann@41037
   191
  | same (DFree (s, k), DFree (t, l)) = s = t andalso k = l
haftmann@41037
   192
  | same (BVar (k, xs), BVar (l, ys)) = k = l andalso eq_list same (xs, ys)
haftmann@41037
   193
  | same _ = false;
haftmann@40730
   194
haftmann@24155
   195
haftmann@24155
   196
(** assembling and compiling ML code from terms **)
haftmann@24155
   197
haftmann@24155
   198
(* abstract ML syntax *)
haftmann@24155
   199
haftmann@24155
   200
infix 9 `$` `$$`;
haftmann@24155
   201
fun e1 `$` e2 = "(" ^ e1 ^ " " ^ e2 ^ ")";
haftmann@25101
   202
fun e `$$` [] = e
haftmann@25101
   203
  | e `$$` es = "(" ^ e ^ " " ^ space_implode " " es ^ ")";
haftmann@24590
   204
fun ml_abs v e = "(fn " ^ v ^ " => " ^ e ^ ")";
haftmann@24155
   205
haftmann@24155
   206
fun ml_cases t cs =
haftmann@24155
   207
  "(case " ^ t ^ " of " ^ space_implode " | " (map (fn (p, t) => p ^ " => " ^ t) cs) ^ ")";
haftmann@25944
   208
fun ml_Let d e = "let\n" ^ d ^ " in " ^ e ^ " end";
haftmann@28337
   209
fun ml_as v t = "(" ^ v ^ " as " ^ t ^ ")";
haftmann@24155
   210
haftmann@28350
   211
fun ml_and [] = "true"
haftmann@28350
   212
  | ml_and [x] = x
haftmann@28350
   213
  | ml_and xs = "(" ^ space_implode " andalso " xs ^ ")";
haftmann@28350
   214
fun ml_if b x y = "(if " ^ b ^ " then " ^ x ^ " else " ^ y ^ ")";
haftmann@28350
   215
haftmann@24155
   216
fun ml_list es = "[" ^ commas es ^ "]";
haftmann@24155
   217
haftmann@24155
   218
fun ml_fundefs ([(name, [([], e)])]) =
haftmann@24155
   219
      "val " ^ name ^ " = " ^ e ^ "\n"
haftmann@24155
   220
  | ml_fundefs (eqs :: eqss) =
haftmann@24155
   221
      let
haftmann@24155
   222
        fun fundef (name, eqs) =
haftmann@24155
   223
          let
haftmann@24155
   224
            fun eqn (es, e) = name ^ " " ^ space_implode " " es ^ " = " ^ e
haftmann@24155
   225
          in space_implode "\n  | " (map eqn eqs) end;
haftmann@24155
   226
      in
haftmann@24155
   227
        (prefix "fun " o fundef) eqs :: map (prefix "and " o fundef) eqss
wenzelm@26931
   228
        |> cat_lines
haftmann@24155
   229
        |> suffix "\n"
haftmann@24155
   230
      end;
haftmann@24155
   231
haftmann@35371
   232
haftmann@25944
   233
(* nbe specific syntax and sandbox communication *)
haftmann@25944
   234
wenzelm@41472
   235
structure Univs = Proof_Data
wenzelm@41472
   236
(
haftmann@39388
   237
  type T = unit -> Univ list -> Univ list
wenzelm@41472
   238
  (* FIXME avoid user error with non-user text *)
haftmann@39399
   239
  fun init _ () = error "Univs"
haftmann@39388
   240
);
haftmann@39388
   241
val put_result = Univs.put;
haftmann@24155
   242
haftmann@24155
   243
local
haftmann@41068
   244
  val prefix =     "Nbe.";
haftmann@41068
   245
  val name_put =   prefix ^ "put_result";
haftmann@41068
   246
  val name_const = prefix ^ "Const";
haftmann@41068
   247
  val name_abss =  prefix ^ "abss";
haftmann@41068
   248
  val name_apps =  prefix ^ "apps";
haftmann@41068
   249
  val name_same =  prefix ^ "same";
haftmann@24155
   250
in
haftmann@24155
   251
haftmann@39388
   252
val univs_cookie = (Univs.get, put_result, name_put);
haftmann@25944
   253
haftmann@55147
   254
fun nbe_fun idx_of 0 (Code_Symbol.Constant "") = "nbe_value"
haftmann@55147
   255
  | nbe_fun idx_of i sym = "c_" ^ string_of_int (idx_of sym)
haftmann@55150
   256
      ^ "_" ^ Code_Symbol.default_base sym ^ "_" ^ string_of_int i;
haftmann@25101
   257
fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
haftmann@24155
   258
fun nbe_bound v = "v_" ^ v;
haftmann@31888
   259
fun nbe_bound_optional NONE = "_"
haftmann@35500
   260
  | nbe_bound_optional (SOME v) = nbe_bound v;
haftmann@28337
   261
fun nbe_default v = "w_" ^ v;
haftmann@24155
   262
haftmann@25924
   263
(*note: these three are the "turning spots" where proper argument order is established!*)
haftmann@25924
   264
fun nbe_apps t [] = t
haftmann@25924
   265
  | nbe_apps t ts = name_apps `$$` [t, ml_list (rev ts)];
haftmann@55043
   266
fun nbe_apps_local idx_of i c ts = nbe_fun idx_of i c `$` ml_list (rev ts);
haftmann@28337
   267
fun nbe_apps_constr idx_of c ts =
haftmann@28337
   268
  let
haftmann@55150
   269
    val c' = if !trace then string_of_int (idx_of c) ^ " (*" ^ Code_Symbol.default_base c ^ "*)"
haftmann@28337
   270
      else string_of_int (idx_of c);
haftmann@28337
   271
  in name_const `$` ("(" ^ c' ^ ", " ^ ml_list (rev ts) ^ ")") end;
haftmann@25924
   272
haftmann@24155
   273
fun nbe_abss 0 f = f `$` ml_list []
haftmann@25944
   274
  | nbe_abss n f = name_abss `$$` [string_of_int n, f];
haftmann@24155
   275
haftmann@41037
   276
fun nbe_same (v1, v2) = "(" ^ name_same ^ " (" ^ nbe_bound v1 ^ ", " ^ nbe_bound v2 ^ "))";
haftmann@28350
   277
haftmann@24155
   278
end;
haftmann@24155
   279
haftmann@55150
   280
open Basic_Code_Symbol;
haftmann@28054
   281
open Basic_Code_Thingol;
haftmann@24155
   282
haftmann@35371
   283
haftmann@25865
   284
(* code generation *)
haftmann@24155
   285
haftmann@26064
   286
fun assemble_eqnss idx_of deps eqnss =
haftmann@25944
   287
  let
haftmann@25944
   288
    fun prep_eqns (c, (vs, eqns)) =
haftmann@25924
   289
      let
haftmann@25944
   290
        val dicts = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs;
haftmann@28337
   291
        val num_args = length dicts + ((length o fst o hd) eqns);
haftmann@25944
   292
      in (c, (num_args, (dicts, eqns))) end;
haftmann@25944
   293
    val eqnss' = map prep_eqns eqnss;
haftmann@25944
   294
haftmann@55147
   295
    fun assemble_constapp sym dss ts = 
haftmann@25944
   296
      let
haftmann@41118
   297
        val ts' = (maps o map) assemble_dict dss @ ts;
haftmann@55147
   298
      in case AList.lookup (op =) eqnss' sym
haftmann@28337
   299
       of SOME (num_args, _) => if num_args <= length ts'
haftmann@28337
   300
            then let val (ts1, ts2) = chop num_args ts'
haftmann@55147
   301
            in nbe_apps (nbe_apps_local idx_of 0 sym ts1) ts2
haftmann@55147
   302
            end else nbe_apps (nbe_abss num_args (nbe_fun idx_of 0 sym)) ts'
haftmann@55147
   303
        | NONE => if member (op =) deps sym
haftmann@55147
   304
            then nbe_apps (nbe_fun idx_of 0 sym) ts'
haftmann@55147
   305
            else nbe_apps_constr idx_of sym ts'
haftmann@25924
   306
      end
haftmann@41100
   307
    and assemble_classrels classrels =
haftmann@55150
   308
      fold_rev (fn classrel => assemble_constapp (Class_Relation classrel) [] o single) classrels
haftmann@41118
   309
    and assemble_dict (Dict (classrels, x)) =
haftmann@41118
   310
          assemble_classrels classrels (assemble_plain_dict x)
haftmann@41118
   311
    and assemble_plain_dict (Dict_Const (inst, dss)) =
haftmann@55150
   312
          assemble_constapp (Class_Instance inst) dss []
haftmann@41118
   313
      | assemble_plain_dict (Dict_Var (v, (n, _))) =
haftmann@41118
   314
          nbe_dict v n
haftmann@25924
   315
haftmann@28350
   316
    fun assemble_iterm constapp =
haftmann@24155
   317
      let
haftmann@28350
   318
        fun of_iterm match_cont t =
haftmann@25944
   319
          let
haftmann@28054
   320
            val (t', ts) = Code_Thingol.unfold_app t
haftmann@28350
   321
          in of_iapp match_cont t' (fold_rev (cons o of_iterm NONE) ts []) end
haftmann@55147
   322
        and of_iapp match_cont (IConst { sym, dicts = dss, ... }) ts = constapp sym dss ts
haftmann@31889
   323
          | of_iapp match_cont (IVar v) ts = nbe_apps (nbe_bound_optional v) ts
haftmann@31724
   324
          | of_iapp match_cont ((v, _) `|=> t) ts =
haftmann@31888
   325
              nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound_optional v]) (of_iterm NONE t))) ts
haftmann@48072
   326
          | of_iapp match_cont (ICase { term = t, clauses = clauses, primitive = t0, ... }) ts =
haftmann@28350
   327
              nbe_apps (ml_cases (of_iterm NONE t)
haftmann@48072
   328
                (map (fn (p, t) => (of_iterm NONE p, of_iterm match_cont t)) clauses
haftmann@28350
   329
                  @ [("_", case match_cont of SOME s => s | NONE => of_iterm NONE t0)])) ts
haftmann@25944
   330
      in of_iterm end;
haftmann@24155
   331
haftmann@28350
   332
    fun subst_nonlin_vars args =
haftmann@28350
   333
      let
haftmann@28350
   334
        val vs = (fold o Code_Thingol.fold_varnames)
wenzelm@33002
   335
          (fn v => AList.map_default (op =) (v, 0) (Integer.add 1)) args [];
haftmann@28350
   336
        val names = Name.make_context (map fst vs);
wenzelm@43329
   337
        fun declare v k ctxt =
wenzelm@43329
   338
          let val vs = Name.invent ctxt v k
haftmann@28350
   339
          in (vs, fold Name.declare vs ctxt) end;
haftmann@28350
   340
        val (vs_renames, _) = fold_map (fn (v, k) => if k > 1
haftmann@28350
   341
          then declare v (k - 1) #>> (fn vs => (v, vs))
haftmann@28350
   342
          else pair (v, [])) vs names;
haftmann@28350
   343
        val samepairs = maps (fn (v, vs) => map (pair v) vs) vs_renames;
haftmann@28350
   344
        fun subst_vars (t as IConst _) samepairs = (t, samepairs)
haftmann@31889
   345
          | subst_vars (t as IVar NONE) samepairs = (t, samepairs)
haftmann@31889
   346
          | subst_vars (t as IVar (SOME v)) samepairs = (case AList.lookup (op =) samepairs v
haftmann@31889
   347
             of SOME v' => (IVar (SOME v'), AList.delete (op =) v samepairs)
haftmann@28350
   348
              | NONE => (t, samepairs))
haftmann@28350
   349
          | subst_vars (t1 `$ t2) samepairs = samepairs
haftmann@28350
   350
              |> subst_vars t1
haftmann@28350
   351
              ||>> subst_vars t2
haftmann@28350
   352
              |>> (op `$)
haftmann@48072
   353
          | subst_vars (ICase { primitive = t, ... }) samepairs = subst_vars t samepairs;
haftmann@28350
   354
        val (args', _) = fold_map subst_vars args samepairs;
haftmann@28350
   355
      in (samepairs, args') end;
haftmann@28350
   356
haftmann@55147
   357
    fun assemble_eqn sym dicts default_args (i, (args, rhs)) =
haftmann@28337
   358
      let
haftmann@55147
   359
        val match_cont = if Code_Symbol.is_value sym then NONE
haftmann@55147
   360
          else SOME (nbe_apps_local idx_of (i + 1) sym (dicts @ default_args));
haftmann@28350
   361
        val assemble_arg = assemble_iterm
haftmann@55147
   362
          (fn sym' => fn dss => fn ts => nbe_apps_constr idx_of sym' ((maps o map) (K "_") dss @ ts)) NONE;
haftmann@35371
   363
        val assemble_rhs = assemble_iterm assemble_constapp match_cont;
haftmann@28350
   364
        val (samepairs, args') = subst_nonlin_vars args;
haftmann@28350
   365
        val s_args = map assemble_arg args';
haftmann@28350
   366
        val s_rhs = if null samepairs then assemble_rhs rhs
haftmann@41037
   367
          else ml_if (ml_and (map nbe_same samepairs))
haftmann@55043
   368
            (assemble_rhs rhs) (the match_cont);
haftmann@55043
   369
        val eqns = case match_cont
haftmann@55043
   370
         of NONE => [([ml_list (rev (dicts @ s_args))], s_rhs)]
haftmann@55043
   371
          | SOME default_rhs =>
haftmann@55043
   372
              [([ml_list (rev (dicts @ map2 ml_as default_args s_args))], s_rhs),
haftmann@55043
   373
                ([ml_list (rev (dicts @ default_args))], default_rhs)]
haftmann@55147
   374
      in (nbe_fun idx_of i sym, eqns) end;
haftmann@28337
   375
haftmann@55147
   376
    fun assemble_eqns (sym, (num_args, (dicts, eqns))) =
haftmann@25944
   377
      let
haftmann@28337
   378
        val default_args = map nbe_default
wenzelm@43329
   379
          (Name.invent Name.context "a" (num_args - length dicts));
haftmann@55147
   380
        val eqns' = map_index (assemble_eqn sym dicts default_args) eqns
haftmann@55147
   381
          @ (if Code_Symbol.is_value sym then [] else [(nbe_fun idx_of (length eqns) sym,
haftmann@28337
   382
            [([ml_list (rev (dicts @ default_args))],
haftmann@55147
   383
              nbe_apps_constr idx_of sym (dicts @ default_args))])]);
haftmann@55147
   384
      in (eqns', nbe_abss num_args (nbe_fun idx_of 0 sym)) end;
haftmann@24155
   385
haftmann@25944
   386
    val (fun_vars, fun_vals) = map_split assemble_eqns eqnss';
haftmann@55043
   387
    val deps_vars = ml_list (map (nbe_fun idx_of 0) deps);
haftmann@28337
   388
  in ml_abs deps_vars (ml_Let (ml_fundefs (flat fun_vars)) (ml_list fun_vals)) end;
haftmann@25944
   389
haftmann@35371
   390
haftmann@39392
   391
(* compile equations *)
haftmann@25944
   392
haftmann@55757
   393
fun compile_eqnss ctxt nbe_program raw_deps [] = []
haftmann@55757
   394
  | compile_eqnss ctxt nbe_program raw_deps eqnss =
haftmann@24155
   395
      let
haftmann@26064
   396
        val (deps, deps_vals) = split_list (map_filter
haftmann@55147
   397
          (fn dep => Option.map (fn univ => (dep, univ)) (fst ((Code_Symbol.Graph.get_node nbe_program dep)))) raw_deps);
haftmann@26064
   398
        val idx_of = raw_deps
haftmann@55147
   399
          |> map (fn dep => (dep, snd (Code_Symbol.Graph.get_node nbe_program dep)))
haftmann@26064
   400
          |> AList.lookup (op =)
haftmann@26064
   401
          |> (fn f => the o f);
haftmann@26064
   402
        val s = assemble_eqnss idx_of deps eqnss;
haftmann@24155
   403
        val cs = map fst eqnss;
haftmann@25944
   404
      in
haftmann@25944
   405
        s
haftmann@32544
   406
        |> traced (fn s => "\n--- code to be evaluated:\n" ^ s)
haftmann@38931
   407
        |> pair ""
haftmann@39911
   408
        |> Code_Runtime.value ctxt univs_cookie
haftmann@25944
   409
        |> (fn f => f deps_vals)
haftmann@25944
   410
        |> (fn univs => cs ~~ univs)
haftmann@25944
   411
      end;
haftmann@25190
   412
wenzelm@30672
   413
haftmann@39392
   414
(* extract equations from statements *)
haftmann@24155
   415
haftmann@55147
   416
fun dummy_const sym dss =
haftmann@55147
   417
  IConst { sym = sym, typargs = [], dicts = dss,
haftmann@48072
   418
    dom = [], range = ITyVar "", annotate = false };
haftmann@48072
   419
haftmann@55147
   420
fun eqns_of_stmt (_, Code_Thingol.NoStmt) =
haftmann@54889
   421
      []
haftmann@55147
   422
  | eqns_of_stmt (_, Code_Thingol.Fun ((_, []), _)) =
haftmann@25101
   423
      []
haftmann@55147
   424
  | eqns_of_stmt (sym_const, Code_Thingol.Fun (((vs, _), eqns), _)) =
haftmann@55147
   425
      [(sym_const, (vs, map fst eqns))]
haftmann@28054
   426
  | eqns_of_stmt (_, Code_Thingol.Datatypecons _) =
haftmann@25101
   427
      []
haftmann@28054
   428
  | eqns_of_stmt (_, Code_Thingol.Datatype _) =
haftmann@25101
   429
      []
haftmann@55147
   430
  | eqns_of_stmt (sym_class, Code_Thingol.Class (v, (classrels, classparams))) =
haftmann@25101
   431
      let
haftmann@55150
   432
        val syms = map Class_Relation classrels @ map (Constant o fst) classparams;
haftmann@55147
   433
        val params = Name.invent Name.context "d" (length syms);
haftmann@55147
   434
        fun mk (k, sym) =
haftmann@55147
   435
          (sym, ([(v, [])],
haftmann@55147
   436
            [([dummy_const sym_class [] `$$ map (IVar o SOME) params],
haftmann@31889
   437
              IVar (SOME (nth params k)))]));
haftmann@55147
   438
      in map_index mk syms end
haftmann@28054
   439
  | eqns_of_stmt (_, Code_Thingol.Classrel _) =
haftmann@25101
   440
      []
haftmann@28054
   441
  | eqns_of_stmt (_, Code_Thingol.Classparam _) =
haftmann@25101
   442
      []
haftmann@55147
   443
  | eqns_of_stmt (sym_inst, Code_Thingol.Classinst { class, tyco, vs, superinsts, inst_params, ... }) =
haftmann@55150
   444
      [(sym_inst, (vs, [([], dummy_const (Type_Class class) [] `$$
haftmann@55150
   445
        map (fn (class, dss) => dummy_const (Class_Instance (tyco, class)) dss) superinsts
haftmann@52519
   446
        @ map (IConst o fst o snd o fst) inst_params)]))];
haftmann@24155
   447
haftmann@39392
   448
haftmann@39392
   449
(* compile whole programs *)
haftmann@39392
   450
haftmann@39399
   451
fun ensure_const_idx name (nbe_program, (maxidx, idx_tab)) =
haftmann@55147
   452
  if can (Code_Symbol.Graph.get_node nbe_program) name
haftmann@39399
   453
  then (nbe_program, (maxidx, idx_tab))
haftmann@55147
   454
  else (Code_Symbol.Graph.new_node (name, (NONE, maxidx)) nbe_program,
haftmann@39399
   455
    (maxidx + 1, Inttab.update_new (maxidx, name) idx_tab));
haftmann@39399
   456
haftmann@55757
   457
fun compile_stmts ctxt stmts_deps =
haftmann@25101
   458
  let
haftmann@25101
   459
    val names = map (fst o fst) stmts_deps;
haftmann@25101
   460
    val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
haftmann@25101
   461
    val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
haftmann@26064
   462
    val refl_deps = names_deps
haftmann@25190
   463
      |> maps snd
haftmann@25190
   464
      |> distinct (op =)
haftmann@26064
   465
      |> fold (insert (op =)) names;
haftmann@39392
   466
    fun compile nbe_program = eqnss
haftmann@55757
   467
      |> compile_eqnss ctxt nbe_program refl_deps
haftmann@39392
   468
      |> rpair nbe_program;
haftmann@25101
   469
  in
haftmann@39399
   470
    fold ensure_const_idx refl_deps
haftmann@55147
   471
    #> apfst (fold (fn (name, deps) => fold (curry Code_Symbol.Graph.add_edge name) deps) names_deps
haftmann@26064
   472
      #> compile
haftmann@55147
   473
      #-> fold (fn (name, univ) => (Code_Symbol.Graph.map_node name o apfst) (K (SOME univ))))
haftmann@25101
   474
  end;
haftmann@24155
   475
haftmann@55757
   476
fun compile_program ctxt program =
haftmann@25101
   477
  let
haftmann@55147
   478
    fun add_stmts names (nbe_program, (maxidx, idx_tab)) = if exists ((can o Code_Symbol.Graph.get_node) nbe_program) names
haftmann@39392
   479
      then (nbe_program, (maxidx, idx_tab))
haftmann@39392
   480
      else (nbe_program, (maxidx, idx_tab))
haftmann@55757
   481
        |> compile_stmts ctxt (map (fn name => ((name, Code_Symbol.Graph.get_node program name),
haftmann@55147
   482
          Code_Symbol.Graph.immediate_succs program name)) names);
haftmann@28706
   483
  in
haftmann@55147
   484
    fold_rev add_stmts (Code_Symbol.Graph.strong_conn program)
haftmann@28706
   485
  end;
haftmann@24155
   486
haftmann@25944
   487
haftmann@25944
   488
(** evaluation **)
haftmann@25944
   489
haftmann@39392
   490
(* term evaluation by compilation *)
haftmann@25944
   491
haftmann@55757
   492
fun compile_term ctxt nbe_program deps (vs : (string * sort) list, t) =
haftmann@25924
   493
  let 
haftmann@25924
   494
    val dict_frees = maps (fn (v, sort) => map_index (curry DFree v o fst) sort) vs;
haftmann@25924
   495
  in
haftmann@55147
   496
    (Code_Symbol.value, (vs, [([], t)]))
haftmann@55757
   497
    |> singleton (compile_eqnss ctxt nbe_program deps)
haftmann@25924
   498
    |> snd
haftmann@31064
   499
    |> (fn t => apps t (rev dict_frees))
haftmann@25924
   500
  end;
haftmann@24155
   501
haftmann@35371
   502
haftmann@39392
   503
(* reconstruction *)
haftmann@24155
   504
haftmann@55147
   505
fun typ_of_itype vs (tyco `%% itys) =
haftmann@55147
   506
      Type (tyco, map (typ_of_itype vs) itys)
haftmann@55147
   507
  | typ_of_itype vs (ITyVar v) =
haftmann@55147
   508
      TFree ("'" ^ v, (the o AList.lookup (op =) vs) v);
haftmann@30947
   509
haftmann@55757
   510
fun term_of_univ ctxt (idx_tab : Code_Symbol.T Inttab.table) t =
haftmann@24155
   511
  let
haftmann@25101
   512
    fun take_until f [] = []
haftmann@55147
   513
      | take_until f (x :: xs) = if f x then [] else x :: take_until f xs;
haftmann@55147
   514
    fun is_dict (Const (idx, _)) =
haftmann@55147
   515
          (case Inttab.lookup idx_tab idx of
haftmann@55150
   516
            SOME (Constant _) => false
haftmann@55147
   517
          | _ => true)
haftmann@25101
   518
      | is_dict (DFree _) = true
haftmann@25101
   519
      | is_dict _ = false;
haftmann@55147
   520
    fun const_of_idx idx =
haftmann@55150
   521
      case Inttab.lookup idx_tab idx of SOME (Constant const) => const;
haftmann@24155
   522
    fun of_apps bounds (t, ts) =
haftmann@24155
   523
      fold_map (of_univ bounds) ts
haftmann@24155
   524
      #>> (fn ts' => list_comb (t, rev ts'))
haftmann@26064
   525
    and of_univ bounds (Const (idx, ts)) typidx =
haftmann@24155
   526
          let
haftmann@25101
   527
            val ts' = take_until is_dict ts;
haftmann@55147
   528
            val const = const_of_idx idx;
haftmann@31957
   529
            val T = map_type_tvar (fn ((v, i), _) =>
wenzelm@37145
   530
              Type_Infer.param typidx (v ^ string_of_int i, []))
haftmann@55757
   531
                (Sign.the_const_type (Proof_Context.theory_of ctxt) const);
haftmann@30022
   532
            val typidx' = typidx + 1;
haftmann@55147
   533
          in of_apps bounds (Term.Const (const, T), ts') typidx' end
haftmann@27499
   534
      | of_univ bounds (BVar (n, ts)) typidx =
haftmann@27499
   535
          of_apps bounds (Bound (bounds - n - 1), ts) typidx
haftmann@24155
   536
      | of_univ bounds (t as Abs _) typidx =
haftmann@24155
   537
          typidx
haftmann@25924
   538
          |> of_univ (bounds + 1) (apps t [BVar (bounds, [])])
haftmann@24155
   539
          |-> (fn t' => pair (Term.Abs ("u", dummyT, t')))
haftmann@24155
   540
  in of_univ 0 t 0 |> fst end;
haftmann@24155
   541
haftmann@35371
   542
haftmann@39392
   543
(* evaluation with type reconstruction *)
haftmann@39392
   544
haftmann@55757
   545
fun eval_term raw_ctxt (nbe_program, idx_tab) ((vs0, (vs, ty)), t) deps =
haftmann@39392
   546
  let
haftmann@55757
   547
    val ctxt = Syntax.init_pretty_global (Proof_Context.theory_of raw_ctxt);
haftmann@39392
   548
    val string_of_term = Syntax.string_of_term (Config.put show_types true ctxt);
haftmann@55147
   549
    val ty' = typ_of_itype vs0 ty;
wenzelm@42405
   550
    fun type_infer t =
wenzelm@42405
   551
      Syntax.check_term (Config.put Type_Infer_Context.const_sorts false ctxt)
wenzelm@42405
   552
        (Type.constraint ty' t);
haftmann@39392
   553
    fun check_tvars t =
haftmann@39392
   554
      if null (Term.add_tvars t []) then t
haftmann@39392
   555
      else error ("Illegal schematic type variables in normalized term: " ^ string_of_term t);
haftmann@39392
   556
  in
haftmann@55757
   557
    compile_term ctxt nbe_program deps (vs, t)
haftmann@55757
   558
    |> term_of_univ ctxt idx_tab
haftmann@39392
   559
    |> traced (fn t => "Normalized:\n" ^ string_of_term t)
haftmann@39392
   560
    |> type_infer
haftmann@39392
   561
    |> traced (fn t => "Types inferred:\n" ^ string_of_term t)
haftmann@39392
   562
    |> check_tvars
haftmann@39392
   563
    |> traced (fn _ => "---\n")
haftmann@39392
   564
  end;
haftmann@39392
   565
haftmann@39436
   566
haftmann@25101
   567
(* function store *)
haftmann@25101
   568
haftmann@34173
   569
structure Nbe_Functions = Code_Data
haftmann@25101
   570
(
haftmann@55150
   571
  type T = (Univ option * int) Code_Symbol.Graph.T * (int * Code_Symbol.T Inttab.table);
haftmann@55147
   572
  val empty = (Code_Symbol.Graph.empty, (0, Inttab.empty));
haftmann@25101
   573
);
haftmann@25101
   574
haftmann@55757
   575
fun compile ignore_cache ctxt program =
haftmann@24155
   576
  let
haftmann@39392
   577
    val (nbe_program, (_, idx_tab)) =
haftmann@55757
   578
      Nbe_Functions.change (if ignore_cache then NONE else SOME (Proof_Context.theory_of ctxt))
haftmann@55757
   579
        (compile_program ctxt program);
haftmann@39392
   580
  in (nbe_program, idx_tab) end;
haftmann@24155
   581
haftmann@32544
   582
haftmann@47572
   583
(* evaluation oracle *)
haftmann@24155
   584
haftmann@55757
   585
fun mk_equals ctxt lhs raw_rhs =
haftmann@26747
   586
  let
haftmann@55757
   587
    val thy = Proof_Context.theory_of ctxt;
haftmann@30947
   588
    val ty = Thm.typ_of (Thm.ctyp_of_term lhs);
wenzelm@56245
   589
    val eq = Thm.cterm_of thy (Term.Const (@{const_name Pure.eq}, ty --> ty --> propT));
haftmann@30947
   590
    val rhs = Thm.cterm_of thy raw_rhs;
haftmann@30947
   591
  in Thm.mk_binop eq lhs rhs end;
haftmann@26747
   592
haftmann@38669
   593
val (_, raw_oracle) = Context.>>> (Context.map_theory_result
wenzelm@43619
   594
  (Thm.add_oracle (@{binding normalization_by_evaluation},
haftmann@55757
   595
    fn (ctxt, nbe_program_idx_tab, vsp_ty_t, deps, ct) =>
haftmann@55757
   596
      mk_equals ctxt ct (eval_term ctxt nbe_program_idx_tab vsp_ty_t deps))));
haftmann@55757
   597
haftmann@55757
   598
fun oracle ctxt nbe_program_idx_tab vsp_ty_t deps ct =
haftmann@55757
   599
  raw_oracle (ctxt, nbe_program_idx_tab, vsp_ty_t, deps, ct);
haftmann@31064
   600
haftmann@55757
   601
fun dynamic_conv ctxt = lift_triv_classes_conv ctxt
haftmann@55757
   602
  (Code_Thingol.dynamic_conv ctxt (oracle ctxt o compile false ctxt));
haftmann@30942
   603
haftmann@55757
   604
fun dynamic_value ctxt = lift_triv_classes_rew ctxt
haftmann@55757
   605
  (Code_Thingol.dynamic_value ctxt I (eval_term ctxt o compile false ctxt));
haftmann@24155
   606
haftmann@55757
   607
fun static_conv ctxt consts =
haftmann@55757
   608
  let
haftmann@55757
   609
    val evaluator = Code_Thingol.static_conv ctxt consts
haftmann@55757
   610
      (fn program => fn _ => K (oracle ctxt (compile true ctxt program)));
haftmann@55757
   611
  in fn ctxt' => lift_triv_classes_conv ctxt' (evaluator ctxt') end;
haftmann@39399
   612
haftmann@55757
   613
fun static_value ctxt consts =
haftmann@55757
   614
  let
haftmann@55757
   615
    val evaluator = Code_Thingol.static_value ctxt I consts
haftmann@55757
   616
      (fn program => fn _ => K (eval_term ctxt (compile true ctxt program)));
haftmann@55757
   617
  in fn ctxt' => lift_triv_classes_rew ctxt' (evaluator ctxt') end;
haftmann@41184
   618
haftmann@35371
   619
haftmann@39396
   620
(** setup **)
haftmann@24155
   621
haftmann@55757
   622
val setup = Value.add_evaluator ("nbe", dynamic_value);
haftmann@24155
   623
haftmann@24155
   624
end;