src/Tools/Code/code_preproc.ML
author haftmann
Thu May 26 15:27:50 2016 +0200 (2016-05-26)
changeset 63157 65a81a4ef7f8
parent 63073 413184c7a2a2
child 63160 80a91e0e236e
permissions -rw-r--r--
clarified naming conventions and code for code evaluation sandwiches
haftmann@37744
     1
(*  Title:      Tools/Code/code_preproc.ML
haftmann@30010
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@30010
     3
haftmann@31125
     4
Preprocessing code equations into a well-sorted system
haftmann@31125
     5
in a graph with explicit dependencies.
haftmann@30010
     6
*)
haftmann@30010
     7
haftmann@31125
     8
signature CODE_PREPROC =
haftmann@30010
     9
sig
wenzelm@51717
    10
  val map_pre: (Proof.context -> Proof.context) -> theory -> theory
wenzelm@51717
    11
  val map_post: (Proof.context -> Proof.context) -> theory -> theory
haftmann@55757
    12
  val add_functrans: string * (Proof.context -> (thm * bool) list -> (thm * bool) list option) -> theory -> theory
haftmann@31125
    13
  val del_functrans: string -> theory -> theory
haftmann@55757
    14
  val simple_functrans: (Proof.context -> thm list -> thm list option)
haftmann@55757
    15
    -> Proof.context -> (thm * bool) list -> (thm * bool) list option
haftmann@55757
    16
  val print_codeproc: Proof.context -> unit
haftmann@31125
    17
haftmann@30947
    18
  type code_algebra
haftmann@30947
    19
  type code_graph
haftmann@34891
    20
  val cert: code_graph -> string -> Code.cert
haftmann@32873
    21
  val sortargs: code_graph -> string -> sort list
haftmann@30947
    22
  val all: code_graph -> string list
haftmann@55757
    23
  val pretty: Proof.context -> code_graph -> Pretty.T
wenzelm@60697
    24
  val obtain: bool -> Proof.context -> string list -> term list -> code_algebra * code_graph
haftmann@55757
    25
  val dynamic_conv: Proof.context
haftmann@56920
    26
    -> (code_algebra -> code_graph -> term -> conv) -> conv
haftmann@56968
    27
  val dynamic_value: Proof.context -> ((term -> term) -> 'a -> 'b)
haftmann@56968
    28
    -> (code_algebra -> code_graph -> term -> 'a) -> term -> 'b
haftmann@56973
    29
  val static_conv: { ctxt: Proof.context, consts: string list }
haftmann@56973
    30
    -> ({ algebra: code_algebra, eqngr: code_graph } -> Proof.context -> term -> conv)
haftmann@55757
    31
    -> Proof.context -> conv
haftmann@56973
    32
  val static_value: { ctxt: Proof.context, lift_postproc: ((term -> term) -> 'a -> 'b), consts: string list }
haftmann@56973
    33
    -> ({ algebra: code_algebra, eqngr: code_graph } -> Proof.context -> term -> 'a)
haftmann@56968
    34
    -> Proof.context -> term -> 'b
haftmann@57430
    35
haftmann@57430
    36
  val trace_none: Context.generic -> Context.generic
haftmann@57430
    37
  val trace_all: Context.generic -> Context.generic
haftmann@57430
    38
  val trace_only: string list -> Context.generic -> Context.generic
haftmann@57430
    39
  val trace_only_ext: string list -> Context.generic -> Context.generic
haftmann@30010
    40
end
haftmann@30010
    41
haftmann@31125
    42
structure Code_Preproc : CODE_PREPROC =
haftmann@30010
    43
struct
haftmann@30010
    44
haftmann@31125
    45
(** preprocessor administration **)
haftmann@31125
    46
haftmann@31125
    47
(* theory data *)
haftmann@31125
    48
haftmann@31125
    49
datatype thmproc = Thmproc of {
haftmann@31125
    50
  pre: simpset,
haftmann@31125
    51
  post: simpset,
haftmann@55757
    52
  functrans: (string * (serial * (Proof.context -> (thm * bool) list -> (thm * bool) list option))) list
haftmann@31125
    53
};
haftmann@31125
    54
haftmann@31599
    55
fun make_thmproc ((pre, post), functrans) =
haftmann@31125
    56
  Thmproc { pre = pre, post = post, functrans = functrans };
haftmann@31125
    57
fun map_thmproc f (Thmproc { pre, post, functrans }) =
haftmann@31599
    58
  make_thmproc (f ((pre, post), functrans));
haftmann@31125
    59
fun merge_thmproc (Thmproc { pre = pre1, post = post1, functrans = functrans1 },
haftmann@31125
    60
  Thmproc { pre = pre2, post = post2, functrans = functrans2 }) =
haftmann@31125
    61
    let
haftmann@31125
    62
      val pre = Simplifier.merge_ss (pre1, pre2);
haftmann@31125
    63
      val post = Simplifier.merge_ss (post1, post2);
haftmann@34891
    64
      val functrans = AList.merge (op =) (eq_fst (op =)) (functrans1, functrans2)
haftmann@34891
    65
        handle AList.DUP => error ("Duplicate function transformer");
haftmann@31599
    66
    in make_thmproc ((pre, post), functrans) end;
haftmann@31125
    67
wenzelm@33522
    68
structure Code_Preproc_Data = Theory_Data
haftmann@31125
    69
(
haftmann@31125
    70
  type T = thmproc;
haftmann@31599
    71
  val empty = make_thmproc ((Simplifier.empty_ss, Simplifier.empty_ss), []);
wenzelm@33522
    72
  val extend = I;
wenzelm@33522
    73
  val merge = merge_thmproc;
haftmann@31125
    74
);
haftmann@31125
    75
haftmann@31125
    76
fun the_thmproc thy = case Code_Preproc_Data.get thy
haftmann@31125
    77
 of Thmproc x => x;
haftmann@31125
    78
haftmann@31125
    79
fun delete_force msg key xs =
haftmann@31125
    80
  if AList.defined (op =) xs key then AList.delete (op =) key xs
haftmann@31125
    81
  else error ("No such " ^ msg ^ ": " ^ quote key);
haftmann@31125
    82
haftmann@38669
    83
val map_data = Code_Preproc_Data.map o map_thmproc;
haftmann@31125
    84
haftmann@32072
    85
val map_pre_post = map_data o apfst;
wenzelm@51717
    86
wenzelm@51717
    87
fun map_simpset which f thy =
wenzelm@51717
    88
  map_pre_post (which (simpset_map (Proof_Context.init_global thy) f)) thy;
wenzelm@51717
    89
val map_pre = map_simpset apfst;
wenzelm@51717
    90
val map_post = map_simpset apsnd;
haftmann@31125
    91
haftmann@56929
    92
fun process_unfold add_del = map_pre o add_del;
haftmann@56929
    93
fun process_post add_del = map_post o add_del;
haftmann@32072
    94
haftmann@56929
    95
fun process_abbrev add_del raw_thm thy =
haftmann@32072
    96
  let
wenzelm@51717
    97
    val ctxt = Proof_Context.init_global thy;
wenzelm@51717
    98
    val thm = Local_Defs.meta_rewrite_rule ctxt raw_thm;
haftmann@32072
    99
    val thm_sym = Thm.symmetric thm;
haftmann@32072
   100
  in
haftmann@32072
   101
    thy |> map_pre_post (fn (pre, post) =>
haftmann@56929
   102
      (pre |> simpset_map ctxt (add_del thm_sym),
haftmann@56929
   103
       post |> simpset_map ctxt (add_del thm)))
haftmann@32072
   104
  end;
haftmann@32072
   105
haftmann@31125
   106
fun add_functrans (name, f) = (map_data o apsnd)
haftmann@31125
   107
  (AList.update (op =) (name, (serial (), f)));
haftmann@31125
   108
haftmann@31125
   109
fun del_functrans name = (map_data o apsnd)
haftmann@31125
   110
  (delete_force "function transformer" name);
haftmann@31125
   111
haftmann@31125
   112
haftmann@56968
   113
(* algebra of sandwiches: cterm transformations with pending postprocessors *)
haftmann@56968
   114
haftmann@56976
   115
fun matches_transitive eq1 eq2 = Thm.rhs_of eq1 aconvc Thm.lhs_of eq2;
haftmann@56976
   116
haftmann@56968
   117
fun trans_comb eq1 eq2 =
haftmann@56976
   118
  (*explicit assertions: evaluation conversion stacks are error-prone*)
haftmann@56976
   119
  if Thm.is_reflexive eq1 then (@{assert} (matches_transitive eq1 eq2); eq2)
haftmann@56976
   120
  else if Thm.is_reflexive eq2 then (@{assert} (matches_transitive eq1 eq2); eq1)
haftmann@56968
   121
  else Thm.transitive eq1 eq2;
haftmann@56968
   122
haftmann@56968
   123
fun trans_conv_rule conv eq = trans_comb eq (conv (Thm.rhs_of eq));
haftmann@56968
   124
haftmann@56976
   125
structure Sandwich : sig
haftmann@56976
   126
  type T = Proof.context -> cterm -> (thm -> thm) * cterm;
haftmann@56976
   127
  val chain: T -> T -> T
haftmann@56976
   128
  val lift: (Proof.context -> cterm -> (cterm -> thm) * thm) -> T
haftmann@56976
   129
  val conversion: T -> (Proof.context -> term -> conv) -> Proof.context -> conv;
haftmann@63157
   130
  val computation: T -> ((term -> term) -> 'a -> 'b) ->
haftmann@56976
   131
    (Proof.context -> term -> 'a) -> Proof.context -> term -> 'b;
haftmann@56976
   132
end = struct
haftmann@56976
   133
haftmann@56976
   134
type T = Proof.context -> cterm -> (thm -> thm) * cterm;
haftmann@56968
   135
haftmann@56968
   136
fun chain sandwich2 sandwich1 ctxt =
haftmann@56968
   137
  sandwich1 ctxt
haftmann@56968
   138
  ##>> sandwich2 ctxt
haftmann@56968
   139
  #>> (op o);
haftmann@56968
   140
haftmann@56976
   141
fun lift conv_sandwhich ctxt ct =
haftmann@56968
   142
  let
haftmann@56968
   143
    val (postproc_conv, eq) = conv_sandwhich ctxt ct;
haftmann@56976
   144
    fun potentail_trans_comb eq1 eq2 =
haftmann@56976
   145
      if matches_transitive eq1 eq2 then trans_comb eq1 eq2 else eq2;
haftmann@56976
   146
        (*weakened protocol for plain term evaluation*)
haftmann@56976
   147
  in (trans_conv_rule postproc_conv o potentail_trans_comb eq, Thm.rhs_of eq) end;
haftmann@56968
   148
haftmann@56976
   149
fun conversion sandwich conv ctxt ct =
haftmann@56968
   150
  let
haftmann@56968
   151
    val (postproc, ct') = sandwich ctxt ct;
wenzelm@59582
   152
  in postproc (conv ctxt (Thm.term_of ct') ct') end;
haftmann@56968
   153
haftmann@63157
   154
fun computation sandwich lift_postproc eval ctxt t =
haftmann@56968
   155
  let
wenzelm@59633
   156
    val (postproc, ct') = sandwich ctxt (Thm.cterm_of ctxt t);
haftmann@56968
   157
  in
wenzelm@59582
   158
    Thm.term_of ct'
haftmann@56968
   159
    |> eval ctxt
wenzelm@59633
   160
    |> lift_postproc (Thm.term_of o Thm.rhs_of o postproc o Thm.reflexive o Thm.cterm_of ctxt)
haftmann@56968
   161
  end;
haftmann@56968
   162
haftmann@56976
   163
end;
haftmann@56976
   164
haftmann@56968
   165
haftmann@31125
   166
(* post- and preprocessing *)
haftmann@31125
   167
haftmann@56968
   168
fun normalized_tfrees_sandwich ctxt ct =
haftmann@56967
   169
  let
wenzelm@59582
   170
    val t = Thm.term_of ct;
wenzelm@60805
   171
    val vs_original =
wenzelm@60805
   172
      fold_term_types (K (fold_atyps (insert (eq_fst op =) o dest_TFree))) t [];
haftmann@56967
   173
    val vs_normalized = Name.invent_names Name.context Name.aT (map snd vs_original);
wenzelm@60805
   174
    val normalize =
wenzelm@60805
   175
      map_type_tfree (TFree o the o AList.lookup (op =) (vs_original ~~ vs_normalized));
haftmann@56967
   176
    val normalization =
wenzelm@60805
   177
      map2 (fn (v, sort) => fn (v', _) => (((v', 0), sort), Thm.ctyp_of ctxt (TFree (v, sort))))
wenzelm@60805
   178
        vs_original vs_normalized;
haftmann@56967
   179
  in
haftmann@56971
   180
    if eq_list (eq_fst (op =)) (vs_normalized, vs_original)
haftmann@56971
   181
    then (I, ct)
wenzelm@59633
   182
    else
wenzelm@60805
   183
     (Thm.instantiate (normalization, []) o Thm.varifyT_global,
wenzelm@59633
   184
      Thm.cterm_of ctxt (map_types normalize t))
haftmann@56967
   185
  end;
haftmann@56967
   186
haftmann@56968
   187
fun no_variables_sandwich ctxt ct =
haftmann@56968
   188
  let
wenzelm@59633
   189
    val all_vars = fold_aterms (fn t as Free _ => insert (op aconvc) (Thm.cterm_of ctxt t)
wenzelm@59633
   190
      | t as Var _ => insert (op aconvc) (Thm.cterm_of ctxt t)
haftmann@56968
   191
      | _ => I) (Thm.term_of ct) [];
haftmann@56968
   192
    fun apply_beta var thm = Thm.combination thm (Thm.reflexive var)
haftmann@56968
   193
      |> Conv.fconv_rule (Conv.arg_conv (Conv.try_conv (Thm.beta_conversion false)))
haftmann@56968
   194
      |> Conv.fconv_rule (Conv.arg1_conv (Thm.beta_conversion false));
haftmann@56971
   195
  in
haftmann@56971
   196
    if null all_vars
haftmann@56971
   197
    then (I, ct)
haftmann@56971
   198
    else (fold apply_beta all_vars, fold_rev Thm.lambda all_vars ct)
haftmann@56971
   199
  end;
haftmann@31125
   200
haftmann@56968
   201
fun simplifier_conv_sandwich ctxt =
haftmann@31125
   202
  let
haftmann@55757
   203
    val thy = Proof_Context.theory_of ctxt;
haftmann@56968
   204
    val pre = (#pre o the_thmproc) thy;
haftmann@56968
   205
    val post = (#post o the_thmproc) thy;
haftmann@56968
   206
    fun pre_conv ctxt' =
haftmann@56968
   207
      Simplifier.rewrite (put_simpset pre ctxt')
wenzelm@63073
   208
      #> trans_conv_rule (Axclass.unoverload_conv ctxt')
haftmann@56968
   209
    fun post_conv ctxt' =
wenzelm@63073
   210
      Axclass.overload_conv ctxt'
haftmann@56968
   211
      #> trans_conv_rule (Simplifier.rewrite (put_simpset post ctxt'))
haftmann@56968
   212
  in fn ctxt' => pre_conv ctxt' #> pair (post_conv ctxt') end;
haftmann@55757
   213
haftmann@56976
   214
fun simplifier_sandwich ctxt = Sandwich.lift (simplifier_conv_sandwich ctxt);
haftmann@31125
   215
haftmann@56968
   216
fun value_sandwich ctxt =
haftmann@56968
   217
  normalized_tfrees_sandwich
haftmann@56976
   218
  |> Sandwich.chain no_variables_sandwich
haftmann@56976
   219
  |> Sandwich.chain (simplifier_sandwich ctxt);
haftmann@31125
   220
haftmann@55757
   221
fun print_codeproc ctxt =
haftmann@31125
   222
  let
haftmann@55757
   223
    val thy = Proof_Context.theory_of ctxt;
haftmann@31125
   224
    val pre = (#pre o the_thmproc) thy;
haftmann@31125
   225
    val post = (#post o the_thmproc) thy;
haftmann@31125
   226
    val functrans = (map fst o #functrans o the_thmproc) thy;
haftmann@31125
   227
  in
wenzelm@56334
   228
    Pretty.writeln_chunks [
haftmann@31125
   229
      Pretty.block [
haftmann@31125
   230
        Pretty.str "preprocessing simpset:",
haftmann@31125
   231
        Pretty.fbrk,
wenzelm@59917
   232
        Simplifier.pretty_simpset true (put_simpset pre ctxt)
haftmann@31125
   233
      ],
haftmann@31125
   234
      Pretty.block [
haftmann@31125
   235
        Pretty.str "postprocessing simpset:",
haftmann@31125
   236
        Pretty.fbrk,
wenzelm@59917
   237
        Simplifier.pretty_simpset true (put_simpset post ctxt)
haftmann@31125
   238
      ],
haftmann@31125
   239
      Pretty.block (
haftmann@31125
   240
        Pretty.str "function transformers:"
haftmann@31125
   241
        :: Pretty.fbrk
haftmann@31125
   242
        :: (Pretty.fbreaks o map Pretty.str) functrans
haftmann@31125
   243
      )
haftmann@31125
   244
    ]
haftmann@31125
   245
  end;
haftmann@31125
   246
haftmann@55757
   247
fun simple_functrans f ctxt eqns = case f ctxt (map fst eqns)
haftmann@31125
   248
 of SOME thms' => SOME (map (rpair (forall snd eqns)) thms')
haftmann@31125
   249
  | NONE => NONE;
haftmann@31125
   250
haftmann@31125
   251
haftmann@31125
   252
(** sort algebra and code equation graph types **)
haftmann@30010
   253
haftmann@30947
   254
type code_algebra = (sort -> sort) * Sorts.algebra;
haftmann@34891
   255
type code_graph = ((string * sort) list * Code.cert) Graph.T;
haftmann@30010
   256
haftmann@39604
   257
fun get_node eqngr const = Graph.get_node eqngr const
haftmann@39604
   258
  handle Graph.UNDEF _ => error ("No such constant in code equation graph: " ^ quote const);
haftmann@39604
   259
haftmann@39604
   260
fun cert eqngr = snd o get_node eqngr;
haftmann@39604
   261
fun sortargs eqngr = map snd o fst o get_node eqngr;
haftmann@30010
   262
fun all eqngr = Graph.keys eqngr;
haftmann@30010
   263
haftmann@55757
   264
fun pretty ctxt eqngr =
haftmann@55757
   265
  let
haftmann@55757
   266
    val thy = Proof_Context.theory_of ctxt;
haftmann@55757
   267
  in
haftmann@55757
   268
    AList.make (snd o Graph.get_node eqngr) (Graph.keys eqngr)
haftmann@55757
   269
    |> (map o apfst) (Code.string_of_const thy)
wenzelm@59058
   270
    |> sort (string_ord o apply2 fst)
haftmann@55757
   271
    |> map (fn (s, cert) => (Pretty.block o Pretty.fbreaks) (Pretty.str s :: Code.pretty_cert thy cert))
haftmann@55757
   272
    |> Pretty.chunks
haftmann@55757
   273
  end;
haftmann@30010
   274
haftmann@30010
   275
haftmann@57430
   276
(** simplifier tracing **)
haftmann@57430
   277
haftmann@57430
   278
structure Trace_Switch = Generic_Data
haftmann@57430
   279
(
haftmann@57430
   280
  type T = string list option;
haftmann@57430
   281
  val empty = SOME [];
haftmann@57430
   282
  val extend = I;
haftmann@59323
   283
  fun merge (NONE, _) = NONE
haftmann@59323
   284
    | merge (_, NONE) = NONE
haftmann@57430
   285
    | merge (SOME cs1, SOME cs2) = SOME (Library.merge (op =) (cs1, cs2));
haftmann@57430
   286
);
haftmann@57430
   287
haftmann@57430
   288
val trace_none = Trace_Switch.put (SOME []);
haftmann@57430
   289
haftmann@57430
   290
val trace_all = Trace_Switch.put NONE;
haftmann@57430
   291
haftmann@57430
   292
fun gen_trace_only prep_const raw_cs context =
haftmann@57430
   293
  let
haftmann@57430
   294
    val cs = map (prep_const (Context.theory_of context)) raw_cs;
haftmann@57430
   295
  in Trace_Switch.put (SOME cs) context end;
haftmann@57430
   296
haftmann@57430
   297
val trace_only = gen_trace_only (K I);
haftmann@57430
   298
val trace_only_ext = gen_trace_only Code.read_const;
haftmann@57430
   299
haftmann@57430
   300
fun switch_trace c ctxt =
haftmann@57430
   301
  let
haftmann@57430
   302
    val d = Trace_Switch.get (Context.Proof ctxt);
haftmann@57430
   303
    val switch = case d of NONE => true | SOME cs => member (op =) cs c;
haftmann@57430
   304
    val _ = if switch
haftmann@57430
   305
      then tracing ("Preprocessing function equations for "
haftmann@57430
   306
        ^ Code.string_of_const (Proof_Context.theory_of ctxt) c)
haftmann@57430
   307
      else ();
haftmann@57430
   308
  in Config.put simp_trace switch ctxt end;
haftmann@57430
   309
haftmann@57430
   310
haftmann@30010
   311
(** the Waisenhaus algorithm **)
haftmann@30010
   312
haftmann@30010
   313
(* auxiliary *)
haftmann@30010
   314
wenzelm@51685
   315
fun is_proper_class thy = can (Axclass.get_info thy);
haftmann@30942
   316
haftmann@30010
   317
fun complete_proper_sort thy =
haftmann@30942
   318
  Sign.complete_sort thy #> filter (is_proper_class thy);
haftmann@30010
   319
haftmann@30029
   320
fun inst_params thy tyco =
wenzelm@51685
   321
  map (fn (c, _) => Axclass.param_of_inst thy (c, tyco))
wenzelm@51685
   322
    o maps (#params o Axclass.get_info thy);
haftmann@30010
   323
haftmann@30010
   324
haftmann@30010
   325
(* data structures *)
haftmann@30010
   326
haftmann@30010
   327
datatype const = Fun of string | Inst of class * string;
haftmann@30010
   328
haftmann@30010
   329
fun const_ord (Fun c1, Fun c2) = fast_string_ord (c1, c2)
haftmann@30010
   330
  | const_ord (Inst class_tyco1, Inst class_tyco2) =
haftmann@30010
   331
      prod_ord fast_string_ord fast_string_ord (class_tyco1, class_tyco2)
haftmann@30010
   332
  | const_ord (Fun _, Inst _) = LESS
haftmann@30010
   333
  | const_ord (Inst _, Fun _) = GREATER;
haftmann@30010
   334
haftmann@30010
   335
type var = const * int;
haftmann@30010
   336
haftmann@30010
   337
structure Vargraph =
wenzelm@31971
   338
  Graph(type key = var val ord = prod_ord const_ord int_ord);
haftmann@30010
   339
haftmann@30054
   340
datatype styp = Tyco of string * styp list | Var of var | Free;
haftmann@30054
   341
haftmann@30054
   342
fun styp_of c_lhs (Type (tyco, tys)) = Tyco (tyco, map (styp_of c_lhs) tys)
haftmann@30054
   343
  | styp_of c_lhs (TFree (v, _)) = case c_lhs
haftmann@30054
   344
     of SOME (c, lhs) => Var (Fun c, find_index (fn (v', _) => v = v') lhs)
haftmann@30054
   345
      | NONE => Free;
haftmann@30010
   346
haftmann@30054
   347
type vardeps_data = ((string * styp list) list * class list) Vargraph.T
haftmann@34891
   348
  * (((string * sort) list * Code.cert) Symtab.table
haftmann@30054
   349
    * (class * string) list);
haftmann@30010
   350
haftmann@30054
   351
val empty_vardeps_data : vardeps_data =
haftmann@30054
   352
  (Vargraph.empty, (Symtab.empty, []));
haftmann@30054
   353
haftmann@30876
   354
haftmann@30054
   355
(* retrieving equations and instances from the background context *)
haftmann@30010
   356
haftmann@55364
   357
fun obtain_eqns ctxt eqngr c =
haftmann@30010
   358
  case try (Graph.get_node eqngr) c
haftmann@34891
   359
   of SOME (lhs, cert) => ((lhs, []), cert)
haftmann@30010
   360
    | NONE => let
haftmann@55364
   361
        val thy = Proof_Context.theory_of ctxt;
haftmann@55757
   362
        val functrans = (map (fn (_, (_, f)) => f ctxt)
haftmann@48075
   363
          o #functrans o the_thmproc) thy;
haftmann@57430
   364
        val cert = Code.get_cert (switch_trace c ctxt) functrans c;
haftmann@55364
   365
        val (lhs, rhss) =
haftmann@55364
   366
          Code.typargs_deps_of_cert thy cert;
haftmann@34891
   367
      in ((lhs, rhss), cert) end;
haftmann@30010
   368
haftmann@55757
   369
fun obtain_instance ctxt arities (inst as (class, tyco)) =
haftmann@30010
   370
  case AList.lookup (op =) arities inst
haftmann@30010
   371
   of SOME classess => (classess, ([], []))
haftmann@30010
   372
    | NONE => let
haftmann@55757
   373
        val thy = Proof_Context.theory_of ctxt;
haftmann@30029
   374
        val all_classes = complete_proper_sort thy [class];
haftmann@37384
   375
        val super_classes = remove (op =) class all_classes;
wenzelm@59840
   376
        val classess =
wenzelm@59840
   377
          map (complete_proper_sort thy)
wenzelm@59840
   378
            (Proof_Context.arity_sorts ctxt tyco [class]);
haftmann@30029
   379
        val inst_params = inst_params thy tyco all_classes;
haftmann@37384
   380
      in (classess, (super_classes, inst_params)) end;
haftmann@30010
   381
haftmann@30054
   382
haftmann@30054
   383
(* computing instantiations *)
haftmann@30054
   384
haftmann@55364
   385
fun add_classes ctxt arities eqngr c_k new_classes vardeps_data =
haftmann@30010
   386
  let
haftmann@30010
   387
    val (styps, old_classes) = Vargraph.get_node (fst vardeps_data) c_k;
haftmann@30010
   388
    val diff_classes = new_classes |> subtract (op =) old_classes;
haftmann@30010
   389
  in if null diff_classes then vardeps_data
haftmann@30010
   390
  else let
wenzelm@44338
   391
    val c_ks = Vargraph.immediate_succs (fst vardeps_data) c_k |> insert (op =) c_k;
haftmann@30010
   392
  in
haftmann@30010
   393
    vardeps_data
haftmann@30010
   394
    |> (apfst o Vargraph.map_node c_k o apsnd) (append diff_classes)
haftmann@55364
   395
    |> fold (fn styp => fold (ensure_typmatch_inst ctxt arities eqngr styp) new_classes) styps
haftmann@55364
   396
    |> fold (fn c_k => add_classes ctxt arities eqngr c_k diff_classes) c_ks
haftmann@30010
   397
  end end
haftmann@55364
   398
and add_styp ctxt arities eqngr c_k new_tyco_styps vardeps_data =
haftmann@30010
   399
  let
haftmann@37384
   400
    val (old_tyco_stypss, classes) = Vargraph.get_node (fst vardeps_data) c_k;
haftmann@37384
   401
  in if member (op =) old_tyco_stypss new_tyco_styps then vardeps_data
haftmann@30010
   402
  else
haftmann@30010
   403
    vardeps_data
haftmann@37384
   404
    |> (apfst o Vargraph.map_node c_k o apfst) (cons new_tyco_styps)
haftmann@55364
   405
    |> fold (ensure_typmatch_inst ctxt arities eqngr new_tyco_styps) classes
haftmann@30010
   406
  end
haftmann@55364
   407
and add_dep ctxt arities eqngr c_k c_k' vardeps_data =
haftmann@30010
   408
  let
haftmann@30010
   409
    val (_, classes) = Vargraph.get_node (fst vardeps_data) c_k;
haftmann@30010
   410
  in
haftmann@30010
   411
    vardeps_data
haftmann@55364
   412
    |> add_classes ctxt arities eqngr c_k' classes
haftmann@30010
   413
    |> apfst (Vargraph.add_edge (c_k, c_k'))
haftmann@30010
   414
  end
haftmann@55364
   415
and ensure_typmatch_inst ctxt arities eqngr (tyco, styps) class vardeps_data =
wenzelm@59840
   416
  if can (Proof_Context.arity_sorts ctxt tyco) [class]
haftmann@30010
   417
  then vardeps_data
haftmann@55364
   418
    |> ensure_inst ctxt arities eqngr (class, tyco)
haftmann@30010
   419
    |> fold_index (fn (k, styp) =>
haftmann@55364
   420
         ensure_typmatch ctxt arities eqngr styp (Inst (class, tyco), k)) styps
haftmann@30010
   421
  else vardeps_data (*permissive!*)
haftmann@55364
   422
and ensure_inst ctxt arities eqngr (inst as (class, tyco)) (vardeps_data as (_, (_, insts))) =
haftmann@30054
   423
  if member (op =) insts inst then vardeps_data
haftmann@30054
   424
  else let
haftmann@37384
   425
    val (classess, (super_classes, inst_params)) =
haftmann@55757
   426
      obtain_instance ctxt arities inst;
haftmann@30010
   427
  in
haftmann@30010
   428
    vardeps_data
haftmann@30054
   429
    |> (apsnd o apsnd) (insert (op =) inst)
haftmann@30083
   430
    |> fold_index (fn (k, _) =>
haftmann@30083
   431
         apfst (Vargraph.new_node ((Inst (class, tyco), k), ([] ,[])))) classess
haftmann@55364
   432
    |> fold (fn super_class => ensure_inst ctxt arities eqngr (super_class, tyco)) super_classes
haftmann@55364
   433
    |> fold (ensure_fun ctxt arities eqngr) inst_params
haftmann@30010
   434
    |> fold_index (fn (k, classes) =>
haftmann@55364
   435
         add_classes ctxt arities eqngr (Inst (class, tyco), k) classes
haftmann@37384
   436
         #> fold (fn super_class =>
haftmann@55364
   437
             add_dep ctxt arities eqngr (Inst (super_class, tyco), k)
haftmann@37384
   438
             (Inst (class, tyco), k)) super_classes
haftmann@30010
   439
         #> fold (fn inst_param =>
haftmann@55364
   440
             add_dep ctxt arities eqngr (Fun inst_param, k)
haftmann@30010
   441
             (Inst (class, tyco), k)
haftmann@30010
   442
             ) inst_params
haftmann@30010
   443
         ) classess
haftmann@30010
   444
  end
haftmann@55364
   445
and ensure_typmatch ctxt arities eqngr (Tyco tyco_styps) c_k vardeps_data =
haftmann@30054
   446
      vardeps_data
haftmann@55364
   447
      |> add_styp ctxt arities eqngr c_k tyco_styps
haftmann@55364
   448
  | ensure_typmatch ctxt arities eqngr (Var c_k') c_k vardeps_data =
haftmann@30054
   449
      vardeps_data
haftmann@55364
   450
      |> add_dep ctxt arities eqngr c_k c_k'
haftmann@55364
   451
  | ensure_typmatch ctxt arities eqngr Free c_k vardeps_data =
haftmann@30054
   452
      vardeps_data
haftmann@55364
   453
and ensure_rhs ctxt arities eqngr (c', styps) vardeps_data =
haftmann@30054
   454
  vardeps_data
haftmann@55364
   455
  |> ensure_fun ctxt arities eqngr c'
haftmann@30054
   456
  |> fold_index (fn (k, styp) =>
haftmann@55364
   457
       ensure_typmatch ctxt arities eqngr styp (Fun c', k)) styps
haftmann@55364
   458
and ensure_fun ctxt arities eqngr c (vardeps_data as (_, (eqntab, _))) =
haftmann@30054
   459
  if Symtab.defined eqntab c then vardeps_data
haftmann@30054
   460
  else let
haftmann@55364
   461
    val ((lhs, rhss), eqns) = obtain_eqns ctxt eqngr c;
haftmann@30054
   462
    val rhss' = (map o apsnd o map) (styp_of (SOME (c, lhs))) rhss;
haftmann@30010
   463
  in
haftmann@30010
   464
    vardeps_data
haftmann@30054
   465
    |> (apsnd o apfst) (Symtab.update_new (c, (lhs, eqns)))
haftmann@30083
   466
    |> fold_index (fn (k, _) =>
haftmann@30083
   467
         apfst (Vargraph.new_node ((Fun c, k), ([] ,[])))) lhs
haftmann@55364
   468
    |> fold_index (fn (k, (_, sort)) => add_classes ctxt arities eqngr (Fun c, k)
haftmann@55364
   469
         (complete_proper_sort (Proof_Context.theory_of ctxt) sort)) lhs
haftmann@55364
   470
    |> fold (ensure_rhs ctxt arities eqngr) rhss'
haftmann@30054
   471
  end;
haftmann@30010
   472
haftmann@30010
   473
haftmann@30010
   474
(* applying instantiations *)
haftmann@30010
   475
haftmann@55757
   476
fun dicts_of ctxt (proj_sort, algebra) (T, sort) =
haftmann@30010
   477
  let
haftmann@55757
   478
    val thy = Proof_Context.theory_of ctxt;
haftmann@62538
   479
    fun class_relation _ (x, _) _ = x;
wenzelm@36102
   480
    fun type_constructor (tyco, _) xs class =
haftmann@30054
   481
      inst_params thy tyco (Sorts.complete_sort algebra [class])
haftmann@30054
   482
        @ (maps o maps) fst xs;
haftmann@30010
   483
    fun type_variable (TFree (_, sort)) = map (pair []) (proj_sort sort);
haftmann@30010
   484
  in
wenzelm@32795
   485
    flat (Sorts.of_sort_derivation algebra
wenzelm@36102
   486
      { class_relation = K class_relation, type_constructor = type_constructor,
haftmann@30010
   487
        type_variable = type_variable } (T, proj_sort sort)
haftmann@30010
   488
       handle Sorts.CLASS_ERROR _ => [] (*permissive!*))
haftmann@30010
   489
  end;
haftmann@30010
   490
haftmann@55757
   491
fun add_arity ctxt vardeps (class, tyco) =
haftmann@33063
   492
  AList.default (op =) ((class, tyco),
haftmann@34891
   493
    map_range (fn k => (snd o Vargraph.get_node vardeps) (Inst (class, tyco), k))
haftmann@55757
   494
      (Sign.arity_number (Proof_Context.theory_of ctxt) tyco));
haftmann@30010
   495
haftmann@55757
   496
fun add_cert ctxt vardeps (c, (proto_lhs, proto_cert)) (rhss, eqngr) =
haftmann@30058
   497
  if can (Graph.get_node eqngr) c then (rhss, eqngr)
haftmann@30058
   498
  else let
haftmann@55757
   499
    val thy = Proof_Context.theory_of ctxt;
haftmann@30010
   500
    val lhs = map_index (fn (k, (v, _)) =>
haftmann@30010
   501
      (v, snd (Vargraph.get_node vardeps (Fun c, k)))) proto_lhs;
haftmann@49971
   502
    val cert = proto_cert
haftmann@49971
   503
      |> Code.constrain_cert thy (map (Sign.minimize_sort thy o snd) lhs)
haftmann@49971
   504
      |> Code.conclude_cert;
haftmann@35224
   505
    val (vs, rhss') = Code.typargs_deps_of_cert thy cert;
haftmann@34891
   506
    val eqngr' = Graph.new_node (c, (vs, cert)) eqngr;
haftmann@30054
   507
  in (map (pair c) rhss' @ rhss, eqngr') end;
haftmann@30010
   508
haftmann@55757
   509
fun extend_arities_eqngr raw_ctxt cs ts (arities, (eqngr : code_graph)) =
haftmann@30010
   510
  let
haftmann@55757
   511
    val thy = Proof_Context.theory_of raw_ctxt;
haftmann@55364
   512
    val {pre, ...} = the_thmproc thy;
haftmann@55757
   513
    val ctxt = put_simpset pre raw_ctxt;
haftmann@30942
   514
    val cs_rhss = (fold o fold_aterms) (fn Const (c_ty as (c, _)) =>
haftmann@30942
   515
      insert (op =) (c, (map (styp_of NONE) o Sign.const_typargs thy) c_ty) | _ => I) ts [];
haftmann@30054
   516
    val (vardeps, (eqntab, insts)) = empty_vardeps_data
haftmann@55364
   517
      |> fold (ensure_fun ctxt arities eqngr) cs
haftmann@55364
   518
      |> fold (ensure_rhs ctxt arities eqngr) cs_rhss;
haftmann@55757
   519
    val arities' = fold (add_arity ctxt vardeps) insts arities;
wenzelm@61262
   520
    val algebra = Sorts.subalgebra (Context.Theory thy) (is_proper_class thy)
haftmann@30064
   521
      (AList.lookup (op =) arities') (Sign.classes_of thy);
haftmann@55757
   522
    val (rhss, eqngr') = Symtab.fold (add_cert ctxt vardeps) eqntab ([], eqngr);
haftmann@55757
   523
    fun deps_of (c, rhs) = c :: maps (dicts_of ctxt algebra)
haftmann@32873
   524
      (rhs ~~ sortargs eqngr' c);
haftmann@30054
   525
    val eqngr'' = fold (fn (c, rhs) => fold
haftmann@30054
   526
      (curry Graph.add_edge c) (deps_of rhs)) rhss eqngr';
haftmann@30942
   527
  in (algebra, (arities', eqngr'')) end;
haftmann@30010
   528
haftmann@30010
   529
haftmann@31125
   530
(** store for preprocessed arities and code equations **)
haftmann@30010
   531
haftmann@34173
   532
structure Wellsorted = Code_Data
haftmann@30010
   533
(
haftmann@30947
   534
  type T = ((string * class) * sort list) list * code_graph;
haftmann@30010
   535
  val empty = ([], Graph.empty);
haftmann@30010
   536
);
haftmann@30010
   537
haftmann@30010
   538
haftmann@31125
   539
(** retrieval and evaluation interfaces **)
haftmann@30010
   540
haftmann@63157
   541
(*
haftmann@63157
   542
  naming conventions
haftmann@63157
   543
  * evaluator "eval" is either
haftmann@63157
   544
    * conversion "conv"
haftmann@63157
   545
    * value computation "comp"
haftmann@63157
   546
  * "evaluation" is a lifting of an evaluator
haftmann@63157
   547
*)
haftmann@63157
   548
wenzelm@60697
   549
fun obtain ignore_cache ctxt consts ts = apsnd snd
wenzelm@60697
   550
  (Wellsorted.change_yield (if ignore_cache then NONE else SOME (Proof_Context.theory_of ctxt))
wenzelm@60697
   551
    (extend_arities_eqngr ctxt consts ts));
haftmann@38670
   552
haftmann@63157
   553
fun dynamic_evaluation eval ctxt t =
haftmann@30942
   554
  let
haftmann@30947
   555
    val consts = fold_aterms
haftmann@56968
   556
      (fn Const (c, _) => insert (op =) c | _ => I) t [];
wenzelm@60697
   557
    val (algebra, eqngr) = obtain false ctxt consts [t];
haftmann@56968
   558
  in eval algebra eqngr t end;
haftmann@30947
   559
haftmann@63157
   560
fun static_evaluation ctxt consts eval =
haftmann@63157
   561
  let
haftmann@63157
   562
    val (algebra, eqngr) = obtain true ctxt consts [];
haftmann@63157
   563
  in eval { algebra = algebra, eqngr = eqngr } end;
haftmann@63157
   564
haftmann@56968
   565
fun dynamic_conv ctxt conv =
haftmann@63157
   566
  Sandwich.conversion (value_sandwich ctxt)
haftmann@63157
   567
    (dynamic_evaluation conv) ctxt;
haftmann@56968
   568
haftmann@56968
   569
fun dynamic_value ctxt lift_postproc evaluator =
haftmann@63157
   570
  Sandwich.computation (value_sandwich ctxt) lift_postproc
haftmann@63157
   571
    (dynamic_evaluation evaluator) ctxt;
haftmann@31125
   572
haftmann@56973
   573
fun static_conv { ctxt, consts } conv =
haftmann@63157
   574
  Sandwich.conversion (value_sandwich ctxt)
haftmann@63157
   575
    (static_evaluation ctxt consts conv);
haftmann@38670
   576
haftmann@63157
   577
fun static_value { ctxt, lift_postproc, consts } comp =
haftmann@63157
   578
  Sandwich.computation (value_sandwich ctxt) lift_postproc
haftmann@63157
   579
    (static_evaluation ctxt consts comp);
haftmann@39475
   580
haftmann@31125
   581
haftmann@31125
   582
(** setup **)
haftmann@31125
   583
haftmann@59323
   584
val _ = Theory.setup (
haftmann@31125
   585
  let
haftmann@31125
   586
    fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
haftmann@56929
   587
    fun add_del_attribute_parser process =
haftmann@56929
   588
      Attrib.add_del (mk_attribute (process Simplifier.add_simp))
haftmann@56929
   589
        (mk_attribute (process Simplifier.del_simp));
haftmann@31125
   590
  in
haftmann@59323
   591
    Attrib.setup @{binding code_unfold} (add_del_attribute_parser process_unfold)
haftmann@59323
   592
      "preprocessing equations for code generator"
haftmann@59323
   593
    #> Attrib.setup @{binding code_post} (add_del_attribute_parser process_post)
haftmann@59323
   594
      "postprocessing equations for code generator"
haftmann@59323
   595
    #> Attrib.setup @{binding code_abbrev} (add_del_attribute_parser process_abbrev)
haftmann@59323
   596
      "post- and preprocessing equations for code generator"
haftmann@59323
   597
    #> Attrib.setup @{binding code_preproc_trace}
haftmann@59323
   598
      ((Scan.lift (Args.$$$ "off" >> K trace_none)
haftmann@59323
   599
      || (Scan.lift (Args.$$$ "only" |-- Args.colon |-- Scan.repeat1 Parse.term))
haftmann@59323
   600
         >> trace_only_ext
haftmann@59323
   601
      || Scan.succeed trace_all)
haftmann@59323
   602
      >> (Thm.declaration_attribute o K)) "tracing of the code generator preprocessor"
haftmann@59323
   603
  end);
haftmann@31125
   604
haftmann@31125
   605
val _ =
wenzelm@59936
   606
  Outer_Syntax.command @{command_keyword print_codeproc} "print code preprocessor setup"
wenzelm@60097
   607
    (Scan.succeed (Toplevel.keep (print_codeproc o Toplevel.context_of)));
haftmann@30010
   608
haftmann@30010
   609
end; (*struct*)