src/Tools/nbe.ML
author haftmann
Thu May 15 16:38:31 2014 +0200 (2014-05-15)
changeset 56973 62da80041afd
parent 56972 f64730f667b9
child 56974 4ab498f41eee
permissions -rw-r--r--
syntactic means to prevent accidental mixup of static and dynamic context
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
wenzelm@32740
    25
  val trace: bool Unsynchronized.ref
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
wenzelm@32740
    35
val trace = Unsynchronized.ref false;
haftmann@32544
    36
fun traced f x = if !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@51685
    67
    val c_c' = case try (pairself (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
(
haftmann@39388
   236
  type T = unit -> Univ list -> Univ list
wenzelm@41472
   237
  (* FIXME avoid user error with non-user text *)
haftmann@39399
   238
  fun init _ () = error "Univs"
haftmann@39388
   239
);
haftmann@39388
   240
val put_result = Univs.put;
haftmann@24155
   241
haftmann@24155
   242
local
haftmann@41068
   243
  val prefix =     "Nbe.";
haftmann@41068
   244
  val name_put =   prefix ^ "put_result";
haftmann@41068
   245
  val name_const = prefix ^ "Const";
haftmann@41068
   246
  val name_abss =  prefix ^ "abss";
haftmann@41068
   247
  val name_apps =  prefix ^ "apps";
haftmann@41068
   248
  val name_same =  prefix ^ "same";
haftmann@24155
   249
in
haftmann@24155
   250
haftmann@39388
   251
val univs_cookie = (Univs.get, put_result, name_put);
haftmann@25944
   252
haftmann@55147
   253
fun nbe_fun idx_of 0 (Code_Symbol.Constant "") = "nbe_value"
haftmann@55147
   254
  | nbe_fun idx_of i sym = "c_" ^ string_of_int (idx_of sym)
haftmann@55150
   255
      ^ "_" ^ Code_Symbol.default_base sym ^ "_" ^ string_of_int i;
haftmann@25101
   256
fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
haftmann@24155
   257
fun nbe_bound v = "v_" ^ v;
haftmann@31888
   258
fun nbe_bound_optional NONE = "_"
haftmann@35500
   259
  | nbe_bound_optional (SOME v) = nbe_bound v;
haftmann@28337
   260
fun nbe_default v = "w_" ^ v;
haftmann@24155
   261
haftmann@25924
   262
(*note: these three are the "turning spots" where proper argument order is established!*)
haftmann@25924
   263
fun nbe_apps t [] = t
haftmann@25924
   264
  | nbe_apps t ts = name_apps `$$` [t, ml_list (rev ts)];
haftmann@55043
   265
fun nbe_apps_local idx_of i c ts = nbe_fun idx_of i c `$` ml_list (rev ts);
haftmann@28337
   266
fun nbe_apps_constr idx_of c ts =
haftmann@28337
   267
  let
haftmann@55150
   268
    val c' = if !trace then string_of_int (idx_of c) ^ " (*" ^ Code_Symbol.default_base c ^ "*)"
haftmann@28337
   269
      else string_of_int (idx_of c);
haftmann@28337
   270
  in name_const `$` ("(" ^ c' ^ ", " ^ ml_list (rev ts) ^ ")") end;
haftmann@25924
   271
haftmann@24155
   272
fun nbe_abss 0 f = f `$` ml_list []
haftmann@25944
   273
  | nbe_abss n f = name_abss `$$` [string_of_int n, f];
haftmann@24155
   274
haftmann@41037
   275
fun nbe_same (v1, v2) = "(" ^ name_same ^ " (" ^ nbe_bound v1 ^ ", " ^ nbe_bound v2 ^ "))";
haftmann@28350
   276
haftmann@24155
   277
end;
haftmann@24155
   278
haftmann@55150
   279
open Basic_Code_Symbol;
haftmann@28054
   280
open Basic_Code_Thingol;
haftmann@24155
   281
haftmann@35371
   282
haftmann@25865
   283
(* code generation *)
haftmann@24155
   284
haftmann@26064
   285
fun assemble_eqnss idx_of deps eqnss =
haftmann@25944
   286
  let
haftmann@25944
   287
    fun prep_eqns (c, (vs, eqns)) =
haftmann@25924
   288
      let
haftmann@25944
   289
        val dicts = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs;
haftmann@28337
   290
        val num_args = length dicts + ((length o fst o hd) eqns);
haftmann@25944
   291
      in (c, (num_args, (dicts, eqns))) end;
haftmann@25944
   292
    val eqnss' = map prep_eqns eqnss;
haftmann@25944
   293
haftmann@55147
   294
    fun assemble_constapp sym dss ts = 
haftmann@25944
   295
      let
haftmann@41118
   296
        val ts' = (maps o map) assemble_dict dss @ ts;
haftmann@55147
   297
      in case AList.lookup (op =) eqnss' sym
haftmann@28337
   298
       of SOME (num_args, _) => if num_args <= length ts'
haftmann@28337
   299
            then let val (ts1, ts2) = chop num_args ts'
haftmann@55147
   300
            in nbe_apps (nbe_apps_local idx_of 0 sym ts1) ts2
haftmann@55147
   301
            end else nbe_apps (nbe_abss num_args (nbe_fun idx_of 0 sym)) ts'
haftmann@55147
   302
        | NONE => if member (op =) deps sym
haftmann@55147
   303
            then nbe_apps (nbe_fun idx_of 0 sym) ts'
haftmann@55147
   304
            else nbe_apps_constr idx_of sym ts'
haftmann@25924
   305
      end
haftmann@41100
   306
    and assemble_classrels classrels =
haftmann@55150
   307
      fold_rev (fn classrel => assemble_constapp (Class_Relation classrel) [] o single) classrels
haftmann@41118
   308
    and assemble_dict (Dict (classrels, x)) =
haftmann@41118
   309
          assemble_classrels classrels (assemble_plain_dict x)
haftmann@41118
   310
    and assemble_plain_dict (Dict_Const (inst, dss)) =
haftmann@55150
   311
          assemble_constapp (Class_Instance inst) dss []
haftmann@41118
   312
      | assemble_plain_dict (Dict_Var (v, (n, _))) =
haftmann@41118
   313
          nbe_dict v n
haftmann@25924
   314
haftmann@28350
   315
    fun assemble_iterm constapp =
haftmann@24155
   316
      let
haftmann@28350
   317
        fun of_iterm match_cont t =
haftmann@25944
   318
          let
haftmann@28054
   319
            val (t', ts) = Code_Thingol.unfold_app t
haftmann@28350
   320
          in of_iapp match_cont t' (fold_rev (cons o of_iterm NONE) ts []) end
haftmann@55147
   321
        and of_iapp match_cont (IConst { sym, dicts = dss, ... }) ts = constapp sym dss ts
haftmann@31889
   322
          | of_iapp match_cont (IVar v) ts = nbe_apps (nbe_bound_optional v) ts
haftmann@31724
   323
          | of_iapp match_cont ((v, _) `|=> t) ts =
haftmann@31888
   324
              nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound_optional v]) (of_iterm NONE t))) ts
haftmann@48072
   325
          | of_iapp match_cont (ICase { term = t, clauses = clauses, primitive = t0, ... }) ts =
haftmann@28350
   326
              nbe_apps (ml_cases (of_iterm NONE t)
haftmann@48072
   327
                (map (fn (p, t) => (of_iterm NONE p, of_iterm match_cont t)) clauses
haftmann@28350
   328
                  @ [("_", case match_cont of SOME s => s | NONE => of_iterm NONE t0)])) ts
haftmann@25944
   329
      in of_iterm end;
haftmann@24155
   330
haftmann@28350
   331
    fun subst_nonlin_vars args =
haftmann@28350
   332
      let
haftmann@28350
   333
        val vs = (fold o Code_Thingol.fold_varnames)
wenzelm@33002
   334
          (fn v => AList.map_default (op =) (v, 0) (Integer.add 1)) args [];
haftmann@28350
   335
        val names = Name.make_context (map fst vs);
wenzelm@43329
   336
        fun declare v k ctxt =
wenzelm@43329
   337
          let val vs = Name.invent ctxt v k
haftmann@28350
   338
          in (vs, fold Name.declare vs ctxt) end;
haftmann@28350
   339
        val (vs_renames, _) = fold_map (fn (v, k) => if k > 1
haftmann@28350
   340
          then declare v (k - 1) #>> (fn vs => (v, vs))
haftmann@28350
   341
          else pair (v, [])) vs names;
haftmann@28350
   342
        val samepairs = maps (fn (v, vs) => map (pair v) vs) vs_renames;
haftmann@28350
   343
        fun subst_vars (t as IConst _) samepairs = (t, samepairs)
haftmann@31889
   344
          | subst_vars (t as IVar NONE) samepairs = (t, samepairs)
haftmann@31889
   345
          | subst_vars (t as IVar (SOME v)) samepairs = (case AList.lookup (op =) samepairs v
haftmann@31889
   346
             of SOME v' => (IVar (SOME v'), AList.delete (op =) v samepairs)
haftmann@28350
   347
              | NONE => (t, samepairs))
haftmann@28350
   348
          | subst_vars (t1 `$ t2) samepairs = samepairs
haftmann@28350
   349
              |> subst_vars t1
haftmann@28350
   350
              ||>> subst_vars t2
haftmann@28350
   351
              |>> (op `$)
haftmann@48072
   352
          | subst_vars (ICase { primitive = t, ... }) samepairs = subst_vars t samepairs;
haftmann@28350
   353
        val (args', _) = fold_map subst_vars args samepairs;
haftmann@28350
   354
      in (samepairs, args') end;
haftmann@28350
   355
haftmann@55147
   356
    fun assemble_eqn sym dicts default_args (i, (args, rhs)) =
haftmann@28337
   357
      let
haftmann@55147
   358
        val match_cont = if Code_Symbol.is_value sym then NONE
haftmann@55147
   359
          else SOME (nbe_apps_local idx_of (i + 1) sym (dicts @ default_args));
haftmann@28350
   360
        val assemble_arg = assemble_iterm
haftmann@55147
   361
          (fn sym' => fn dss => fn ts => nbe_apps_constr idx_of sym' ((maps o map) (K "_") dss @ ts)) NONE;
haftmann@35371
   362
        val assemble_rhs = assemble_iterm assemble_constapp match_cont;
haftmann@28350
   363
        val (samepairs, args') = subst_nonlin_vars args;
haftmann@28350
   364
        val s_args = map assemble_arg args';
haftmann@28350
   365
        val s_rhs = if null samepairs then assemble_rhs rhs
haftmann@41037
   366
          else ml_if (ml_and (map nbe_same samepairs))
haftmann@55043
   367
            (assemble_rhs rhs) (the match_cont);
haftmann@55043
   368
        val eqns = case match_cont
haftmann@55043
   369
         of NONE => [([ml_list (rev (dicts @ s_args))], s_rhs)]
haftmann@55043
   370
          | SOME default_rhs =>
haftmann@55043
   371
              [([ml_list (rev (dicts @ map2 ml_as default_args s_args))], s_rhs),
haftmann@55043
   372
                ([ml_list (rev (dicts @ default_args))], default_rhs)]
haftmann@55147
   373
      in (nbe_fun idx_of i sym, eqns) end;
haftmann@28337
   374
haftmann@55147
   375
    fun assemble_eqns (sym, (num_args, (dicts, eqns))) =
haftmann@25944
   376
      let
haftmann@28337
   377
        val default_args = map nbe_default
wenzelm@43329
   378
          (Name.invent Name.context "a" (num_args - length dicts));
haftmann@55147
   379
        val eqns' = map_index (assemble_eqn sym dicts default_args) eqns
haftmann@55147
   380
          @ (if Code_Symbol.is_value sym then [] else [(nbe_fun idx_of (length eqns) sym,
haftmann@28337
   381
            [([ml_list (rev (dicts @ default_args))],
haftmann@55147
   382
              nbe_apps_constr idx_of sym (dicts @ default_args))])]);
haftmann@55147
   383
      in (eqns', nbe_abss num_args (nbe_fun idx_of 0 sym)) end;
haftmann@24155
   384
haftmann@25944
   385
    val (fun_vars, fun_vals) = map_split assemble_eqns eqnss';
haftmann@55043
   386
    val deps_vars = ml_list (map (nbe_fun idx_of 0) deps);
haftmann@28337
   387
  in ml_abs deps_vars (ml_Let (ml_fundefs (flat fun_vars)) (ml_list fun_vals)) end;
haftmann@25944
   388
haftmann@35371
   389
haftmann@39392
   390
(* compile equations *)
haftmann@25944
   391
haftmann@55757
   392
fun compile_eqnss ctxt nbe_program raw_deps [] = []
haftmann@55757
   393
  | compile_eqnss ctxt nbe_program raw_deps eqnss =
haftmann@24155
   394
      let
haftmann@26064
   395
        val (deps, deps_vals) = split_list (map_filter
haftmann@55147
   396
          (fn dep => Option.map (fn univ => (dep, univ)) (fst ((Code_Symbol.Graph.get_node nbe_program dep)))) raw_deps);
haftmann@26064
   397
        val idx_of = raw_deps
haftmann@55147
   398
          |> map (fn dep => (dep, snd (Code_Symbol.Graph.get_node nbe_program dep)))
haftmann@26064
   399
          |> AList.lookup (op =)
haftmann@26064
   400
          |> (fn f => the o f);
haftmann@26064
   401
        val s = assemble_eqnss idx_of deps eqnss;
haftmann@24155
   402
        val cs = map fst eqnss;
haftmann@25944
   403
      in
haftmann@25944
   404
        s
haftmann@32544
   405
        |> traced (fn s => "\n--- code to be evaluated:\n" ^ s)
haftmann@38931
   406
        |> pair ""
haftmann@39911
   407
        |> Code_Runtime.value ctxt univs_cookie
haftmann@25944
   408
        |> (fn f => f deps_vals)
haftmann@25944
   409
        |> (fn univs => cs ~~ univs)
haftmann@25944
   410
      end;
haftmann@25190
   411
wenzelm@30672
   412
haftmann@39392
   413
(* extract equations from statements *)
haftmann@24155
   414
haftmann@55147
   415
fun dummy_const sym dss =
haftmann@55147
   416
  IConst { sym = sym, typargs = [], dicts = dss,
haftmann@48072
   417
    dom = [], range = ITyVar "", annotate = false };
haftmann@48072
   418
haftmann@55147
   419
fun eqns_of_stmt (_, Code_Thingol.NoStmt) =
haftmann@54889
   420
      []
haftmann@55147
   421
  | eqns_of_stmt (_, Code_Thingol.Fun ((_, []), _)) =
haftmann@25101
   422
      []
haftmann@55147
   423
  | eqns_of_stmt (sym_const, Code_Thingol.Fun (((vs, _), eqns), _)) =
haftmann@55147
   424
      [(sym_const, (vs, map fst eqns))]
haftmann@28054
   425
  | eqns_of_stmt (_, Code_Thingol.Datatypecons _) =
haftmann@25101
   426
      []
haftmann@28054
   427
  | eqns_of_stmt (_, Code_Thingol.Datatype _) =
haftmann@25101
   428
      []
haftmann@55147
   429
  | eqns_of_stmt (sym_class, Code_Thingol.Class (v, (classrels, classparams))) =
haftmann@25101
   430
      let
haftmann@55150
   431
        val syms = map Class_Relation classrels @ map (Constant o fst) classparams;
haftmann@55147
   432
        val params = Name.invent Name.context "d" (length syms);
haftmann@55147
   433
        fun mk (k, sym) =
haftmann@55147
   434
          (sym, ([(v, [])],
haftmann@55147
   435
            [([dummy_const sym_class [] `$$ map (IVar o SOME) params],
haftmann@31889
   436
              IVar (SOME (nth params k)))]));
haftmann@55147
   437
      in map_index mk syms end
haftmann@28054
   438
  | eqns_of_stmt (_, Code_Thingol.Classrel _) =
haftmann@25101
   439
      []
haftmann@28054
   440
  | eqns_of_stmt (_, Code_Thingol.Classparam _) =
haftmann@25101
   441
      []
haftmann@55147
   442
  | eqns_of_stmt (sym_inst, Code_Thingol.Classinst { class, tyco, vs, superinsts, inst_params, ... }) =
haftmann@55150
   443
      [(sym_inst, (vs, [([], dummy_const (Type_Class class) [] `$$
haftmann@55150
   444
        map (fn (class, dss) => dummy_const (Class_Instance (tyco, class)) dss) superinsts
haftmann@52519
   445
        @ map (IConst o fst o snd o fst) inst_params)]))];
haftmann@24155
   446
haftmann@39392
   447
haftmann@39392
   448
(* compile whole programs *)
haftmann@39392
   449
haftmann@39399
   450
fun ensure_const_idx name (nbe_program, (maxidx, idx_tab)) =
haftmann@55147
   451
  if can (Code_Symbol.Graph.get_node nbe_program) name
haftmann@39399
   452
  then (nbe_program, (maxidx, idx_tab))
haftmann@55147
   453
  else (Code_Symbol.Graph.new_node (name, (NONE, maxidx)) nbe_program,
haftmann@39399
   454
    (maxidx + 1, Inttab.update_new (maxidx, name) idx_tab));
haftmann@39399
   455
haftmann@55757
   456
fun compile_stmts ctxt stmts_deps =
haftmann@25101
   457
  let
haftmann@25101
   458
    val names = map (fst o fst) stmts_deps;
haftmann@25101
   459
    val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
haftmann@25101
   460
    val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
haftmann@26064
   461
    val refl_deps = names_deps
haftmann@25190
   462
      |> maps snd
haftmann@25190
   463
      |> distinct (op =)
haftmann@26064
   464
      |> fold (insert (op =)) names;
haftmann@39392
   465
    fun compile nbe_program = eqnss
haftmann@55757
   466
      |> compile_eqnss ctxt nbe_program refl_deps
haftmann@39392
   467
      |> rpair nbe_program;
haftmann@25101
   468
  in
haftmann@39399
   469
    fold ensure_const_idx refl_deps
haftmann@55147
   470
    #> apfst (fold (fn (name, deps) => fold (curry Code_Symbol.Graph.add_edge name) deps) names_deps
haftmann@26064
   471
      #> compile
haftmann@55147
   472
      #-> fold (fn (name, univ) => (Code_Symbol.Graph.map_node name o apfst) (K (SOME univ))))
haftmann@25101
   473
  end;
haftmann@24155
   474
haftmann@55757
   475
fun compile_program ctxt program =
haftmann@25101
   476
  let
haftmann@55147
   477
    fun add_stmts names (nbe_program, (maxidx, idx_tab)) = if exists ((can o Code_Symbol.Graph.get_node) nbe_program) names
haftmann@39392
   478
      then (nbe_program, (maxidx, idx_tab))
haftmann@39392
   479
      else (nbe_program, (maxidx, idx_tab))
haftmann@55757
   480
        |> compile_stmts ctxt (map (fn name => ((name, Code_Symbol.Graph.get_node program name),
haftmann@55147
   481
          Code_Symbol.Graph.immediate_succs program name)) names);
haftmann@28706
   482
  in
haftmann@55147
   483
    fold_rev add_stmts (Code_Symbol.Graph.strong_conn program)
haftmann@28706
   484
  end;
haftmann@24155
   485
haftmann@25944
   486
haftmann@25944
   487
(** evaluation **)
haftmann@25944
   488
haftmann@39392
   489
(* term evaluation by compilation *)
haftmann@25944
   490
haftmann@55757
   491
fun compile_term ctxt nbe_program deps (vs : (string * sort) list, t) =
haftmann@25924
   492
  let 
haftmann@25924
   493
    val dict_frees = maps (fn (v, sort) => map_index (curry DFree v o fst) sort) vs;
haftmann@25924
   494
  in
haftmann@55147
   495
    (Code_Symbol.value, (vs, [([], t)]))
haftmann@55757
   496
    |> singleton (compile_eqnss ctxt nbe_program deps)
haftmann@25924
   497
    |> snd
haftmann@31064
   498
    |> (fn t => apps t (rev dict_frees))
haftmann@25924
   499
  end;
haftmann@24155
   500
haftmann@35371
   501
haftmann@39392
   502
(* reconstruction *)
haftmann@24155
   503
haftmann@55757
   504
fun term_of_univ ctxt (idx_tab : Code_Symbol.T Inttab.table) t =
haftmann@24155
   505
  let
haftmann@25101
   506
    fun take_until f [] = []
haftmann@55147
   507
      | take_until f (x :: xs) = if f x then [] else x :: take_until f xs;
haftmann@55147
   508
    fun is_dict (Const (idx, _)) =
haftmann@55147
   509
          (case Inttab.lookup idx_tab idx of
haftmann@55150
   510
            SOME (Constant _) => false
haftmann@55147
   511
          | _ => true)
haftmann@25101
   512
      | is_dict (DFree _) = true
haftmann@25101
   513
      | is_dict _ = false;
haftmann@55147
   514
    fun const_of_idx idx =
haftmann@55150
   515
      case Inttab.lookup idx_tab idx of SOME (Constant const) => const;
haftmann@24155
   516
    fun of_apps bounds (t, ts) =
haftmann@24155
   517
      fold_map (of_univ bounds) ts
haftmann@24155
   518
      #>> (fn ts' => list_comb (t, rev ts'))
haftmann@26064
   519
    and of_univ bounds (Const (idx, ts)) typidx =
haftmann@24155
   520
          let
haftmann@25101
   521
            val ts' = take_until is_dict ts;
haftmann@55147
   522
            val const = const_of_idx idx;
haftmann@31957
   523
            val T = map_type_tvar (fn ((v, i), _) =>
wenzelm@37145
   524
              Type_Infer.param typidx (v ^ string_of_int i, []))
haftmann@55757
   525
                (Sign.the_const_type (Proof_Context.theory_of ctxt) const);
haftmann@30022
   526
            val typidx' = typidx + 1;
haftmann@55147
   527
          in of_apps bounds (Term.Const (const, T), ts') typidx' end
haftmann@27499
   528
      | of_univ bounds (BVar (n, ts)) typidx =
haftmann@27499
   529
          of_apps bounds (Bound (bounds - n - 1), ts) typidx
haftmann@24155
   530
      | of_univ bounds (t as Abs _) typidx =
haftmann@24155
   531
          typidx
haftmann@25924
   532
          |> of_univ (bounds + 1) (apps t [BVar (bounds, [])])
haftmann@24155
   533
          |-> (fn t' => pair (Term.Abs ("u", dummyT, t')))
haftmann@24155
   534
  in of_univ 0 t 0 |> fst end;
haftmann@24155
   535
haftmann@35371
   536
haftmann@39392
   537
(* evaluation with type reconstruction *)
haftmann@39392
   538
haftmann@56969
   539
fun eval_term raw_ctxt (nbe_program, idx_tab) t_original ((vs, ty), t) deps =
haftmann@39392
   540
  let
haftmann@55757
   541
    val ctxt = Syntax.init_pretty_global (Proof_Context.theory_of raw_ctxt);
haftmann@39392
   542
    val string_of_term = Syntax.string_of_term (Config.put show_types true ctxt);
haftmann@56969
   543
    fun type_infer t' =
wenzelm@42405
   544
      Syntax.check_term (Config.put Type_Infer_Context.const_sorts false ctxt)
haftmann@56969
   545
        (Type.constraint (fastype_of t_original) t');
haftmann@56969
   546
    fun check_tvars t' =
haftmann@56969
   547
      if null (Term.add_tvars t' []) then t'
haftmann@56969
   548
      else error ("Illegal schematic type variables in normalized term: " ^ string_of_term t');
haftmann@39392
   549
  in
haftmann@55757
   550
    compile_term ctxt nbe_program deps (vs, t)
haftmann@55757
   551
    |> term_of_univ ctxt idx_tab
haftmann@39392
   552
    |> traced (fn t => "Normalized:\n" ^ string_of_term t)
haftmann@39392
   553
    |> type_infer
haftmann@39392
   554
    |> traced (fn t => "Types inferred:\n" ^ string_of_term t)
haftmann@39392
   555
    |> check_tvars
haftmann@39392
   556
    |> traced (fn _ => "---\n")
haftmann@39392
   557
  end;
haftmann@39392
   558
haftmann@39436
   559
haftmann@25101
   560
(* function store *)
haftmann@25101
   561
haftmann@34173
   562
structure Nbe_Functions = Code_Data
haftmann@25101
   563
(
haftmann@55150
   564
  type T = (Univ option * int) Code_Symbol.Graph.T * (int * Code_Symbol.T Inttab.table);
haftmann@55147
   565
  val empty = (Code_Symbol.Graph.empty, (0, Inttab.empty));
haftmann@25101
   566
);
haftmann@25101
   567
haftmann@55757
   568
fun compile ignore_cache ctxt program =
haftmann@24155
   569
  let
haftmann@39392
   570
    val (nbe_program, (_, idx_tab)) =
haftmann@55757
   571
      Nbe_Functions.change (if ignore_cache then NONE else SOME (Proof_Context.theory_of ctxt))
haftmann@55757
   572
        (compile_program ctxt program);
haftmann@39392
   573
  in (nbe_program, idx_tab) end;
haftmann@24155
   574
haftmann@32544
   575
haftmann@47572
   576
(* evaluation oracle *)
haftmann@24155
   577
haftmann@55757
   578
fun mk_equals ctxt lhs raw_rhs =
haftmann@26747
   579
  let
haftmann@55757
   580
    val thy = Proof_Context.theory_of ctxt;
haftmann@30947
   581
    val ty = Thm.typ_of (Thm.ctyp_of_term lhs);
wenzelm@56245
   582
    val eq = Thm.cterm_of thy (Term.Const (@{const_name Pure.eq}, ty --> ty --> propT));
haftmann@30947
   583
    val rhs = Thm.cterm_of thy raw_rhs;
haftmann@30947
   584
  in Thm.mk_binop eq lhs rhs end;
haftmann@26747
   585
haftmann@38669
   586
val (_, raw_oracle) = Context.>>> (Context.map_theory_result
wenzelm@43619
   587
  (Thm.add_oracle (@{binding normalization_by_evaluation},
haftmann@56969
   588
    fn (ctxt, nbe_program_idx_tab, vs_ty_t, deps, ct) =>
haftmann@56969
   589
      mk_equals ctxt ct (eval_term ctxt nbe_program_idx_tab (term_of ct) vs_ty_t deps))));
haftmann@55757
   590
haftmann@56969
   591
fun oracle ctxt nbe_program_idx_tab vs_ty_t deps ct =
haftmann@56969
   592
  raw_oracle (ctxt, nbe_program_idx_tab, vs_ty_t, deps, ct);
haftmann@31064
   593
haftmann@55757
   594
fun dynamic_conv ctxt = lift_triv_classes_conv ctxt
haftmann@55757
   595
  (Code_Thingol.dynamic_conv ctxt (oracle ctxt o compile false ctxt));
haftmann@30942
   596
haftmann@55757
   597
fun dynamic_value ctxt = lift_triv_classes_rew ctxt
haftmann@55757
   598
  (Code_Thingol.dynamic_value ctxt I (eval_term ctxt o compile false ctxt));
haftmann@24155
   599
haftmann@56973
   600
fun static_conv (ctxt_consts as { ctxt, ... }) =
haftmann@55757
   601
  let
haftmann@56973
   602
    val evaluator = Code_Thingol.static_conv ctxt_consts
haftmann@56973
   603
      (fn { program, ... } => fn ctxt' => oracle ctxt' (compile true ctxt program));
haftmann@55757
   604
  in fn ctxt' => lift_triv_classes_conv ctxt' (evaluator ctxt') end;
haftmann@39399
   605
haftmann@56973
   606
fun static_value { ctxt, consts } =
haftmann@55757
   607
  let
haftmann@56973
   608
    val evaluator = Code_Thingol.static_value { ctxt = ctxt, lift_postproc = I, consts = consts }
haftmann@56973
   609
      (fn { program, ... } => fn ctxt' => eval_term ctxt' (compile false ctxt program));
haftmann@55757
   610
  in fn ctxt' => lift_triv_classes_rew ctxt' (evaluator ctxt') end;
haftmann@41184
   611
haftmann@24155
   612
end;