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