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