src/Tools/Code/code_runtime.ML
author haftmann
Tue Feb 07 22:15:03 2017 +0100 (2017-02-07)
changeset 64995 a7af4045f873
parent 64993 4fb84597ec5a
child 65005 3278831c226d
permissions -rw-r--r--
preprocessing rules must always stem from static context
     1 (*  Title:      Tools/Code/code_runtime.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Runtime services building on code generation into implementation language SML.
     5 *)
     6 
     7 signature CODE_RUNTIME =
     8 sig
     9   val target: string
    10   val value: Proof.context ->
    11     (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string ->
    12     string * string -> 'a
    13   type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string
    14   val dynamic_value: 'a cookie -> Proof.context -> string option
    15     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a option
    16   val dynamic_value_strict: 'a cookie -> Proof.context -> string option
    17     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a
    18   val dynamic_value_exn: 'a cookie -> Proof.context -> string option
    19     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a Exn.result
    20   val static_value: 'a cookie -> { ctxt: Proof.context, target: string option,
    21     lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
    22     -> Proof.context -> term -> 'a option
    23   val static_value_strict: 'a cookie -> { ctxt: Proof.context, target: string option,
    24     lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
    25     -> Proof.context -> term -> 'a
    26   val static_value_exn: 'a cookie -> { ctxt: Proof.context, target: string option,
    27     lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
    28     -> Proof.context -> term -> 'a Exn.result
    29   val dynamic_holds_conv: Proof.context -> conv
    30   val static_holds_conv: { ctxt: Proof.context, consts: string list } -> Proof.context -> conv
    31   val code_reflect: (string * string list option) list -> string list -> string
    32     -> string option -> theory -> theory
    33   datatype truth = Holds
    34   val put_truth: (unit -> truth) -> Proof.context -> Proof.context
    35   val mount_computation: Proof.context -> (string * typ) list -> typ
    36     -> (term -> 'ml) -> ((term -> term) -> 'ml option -> 'a) -> Proof.context -> term -> 'a
    37   val mount_computation_conv: Proof.context -> (string * typ) list -> typ
    38     -> (term -> 'ml) -> ('ml -> conv) -> Proof.context -> conv
    39   val mount_computation_check: Proof.context -> (string * typ) list
    40     -> (term -> truth) -> Proof.context -> conv
    41   val polyml_as_definition: (binding * typ) list -> Path.T list -> theory -> theory
    42   val trace: bool Config.T
    43 end;
    44 
    45 structure Code_Runtime : CODE_RUNTIME =
    46 struct
    47 
    48 open Basic_Code_Symbol;
    49 
    50 (** ML compiler as evaluation environment **)
    51 
    52 (* technical prerequisites *)
    53 
    54 val thisN = "Code_Runtime";
    55 val prefix_this = Long_Name.append thisN;
    56 val truthN = prefix_this "truth";
    57 val HoldsN = prefix_this "Holds";
    58 
    59 val target = "Eval";
    60 
    61 datatype truth = Holds;
    62 
    63 val _ = Theory.setup
    64   (Code_Target.add_derived_target (target, [(Code_ML.target_SML, I)])
    65   #> Code_Target.set_printings (Type_Constructor (@{type_name prop},
    66     [(target, SOME (0, (K o K o K) (Code_Printer.str truthN)))]))
    67   #> Code_Target.set_printings (Constant (@{const_name Code_Generator.holds},
    68     [(target, SOME (Code_Printer.plain_const_syntax HoldsN))]))
    69   #> Code_Target.add_reserved target thisN
    70   #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]);
    71        (*avoid further pervasive infix names*)
    72 
    73 val trace = Attrib.setup_config_bool @{binding "code_runtime_trace"} (K false);
    74 
    75 fun compile_ML verbose code context =
    76  (if Config.get_generic context trace then tracing code else ();
    77   Code_Preproc.timed "compiling ML" Context.proof_of
    78     (ML_Context.exec (fn () => ML_Compiler0.ML ML_Env.context
    79     {line = 0, file = "generated code", verbose = verbose,
    80        debug = false} code)) context);
    81 
    82 fun value ctxt (get, put, put_ml) (prelude, value) =
    83   let
    84     val code =
    85       prelude ^ "\nval _ = Context.put_generic_context (SOME (Context.map_proof (" ^
    86       put_ml ^ " (fn () => " ^ value ^ ")) (Context.the_generic_context ())))";
    87     val ctxt' = ctxt
    88       |> put (fn () => error ("Bad compilation for " ^ quote put_ml))
    89       |> Context.proof_map (compile_ML false code);
    90     val computator = get ctxt';
    91   in Code_Preproc.timed_exec "running ML" computator ctxt' end;
    92 
    93 
    94 (* evaluation into ML language values *)
    95 
    96 type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
    97 
    98 fun reject_vars ctxt t =
    99   ((Sign.no_frees ctxt o Sign.no_vars ctxt o map_types (K dummyT)) t; t);
   100 
   101 fun build_compilation_text ctxt some_target program consts =
   102   Code_Target.compilation_text ctxt (the_default target some_target) program consts false
   103   #>> (fn ml_modules => space_implode "\n\n" (map snd ml_modules));
   104 
   105 fun run_compilation_text cookie ctxt comp vs_t args =
   106   let
   107     val (program_code, value_name) = comp vs_t;
   108     val value_code = space_implode " "
   109       (value_name :: "()" :: map (enclose "(" ")") args);
   110   in Exn.interruptible_capture (value ctxt cookie) (program_code, value_code) end;
   111 
   112 fun partiality_as_none e = SOME (Exn.release e)
   113   handle General.Match => NONE
   114     | General.Bind => NONE
   115     | General.Fail _ => NONE;
   116 
   117 fun dynamic_value_exn cookie ctxt some_target postproc t args =
   118   let
   119     val _ = reject_vars ctxt t;
   120     val _ = if Config.get ctxt trace
   121       then tracing ("Evaluation of term " ^ quote (Syntax.string_of_term ctxt t))
   122       else ()
   123     fun comp program _ vs_ty_t deps =
   124       run_compilation_text cookie ctxt (build_compilation_text ctxt some_target program deps) vs_ty_t args;
   125   in Code_Thingol.dynamic_value ctxt (Exn.map_res o postproc) comp t end;
   126 
   127 fun dynamic_value_strict cookie ctxt some_target postproc t args =
   128   Exn.release (dynamic_value_exn cookie ctxt some_target postproc t args);
   129 
   130 fun dynamic_value cookie ctxt some_target postproc t args =
   131   partiality_as_none (dynamic_value_exn cookie ctxt some_target postproc t args);
   132 
   133 fun static_value_exn cookie { ctxt, target, lift_postproc, consts } =
   134   let
   135     fun compilation' { program, deps } =
   136       let
   137         val compilation'' = run_compilation_text cookie ctxt
   138           (build_compilation_text ctxt target program (map Constant deps));
   139       in fn _ => fn _ => fn vs_ty_t => fn _ => compilation'' vs_ty_t [] end;
   140     val compilation = Code_Thingol.static_value { ctxt = ctxt,
   141       lift_postproc = Exn.map_res o lift_postproc, consts = consts }
   142       compilation';
   143   in fn ctxt' => compilation ctxt' o reject_vars ctxt' end;
   144 
   145 fun static_value_strict cookie x = Exn.release oo static_value_exn cookie x;
   146 
   147 fun static_value cookie x = partiality_as_none oo static_value_exn cookie x;
   148 
   149 
   150 (* evaluation for truth or nothing *)
   151 
   152 structure Truth_Result = Proof_Data
   153 (
   154   type T = unit -> truth;
   155   val empty: T = fn () => raise Fail "Truth_Result";
   156   fun init _ = empty;
   157 );
   158 val put_truth = Truth_Result.put;
   159 val truth_cookie = (Truth_Result.get, put_truth, prefix_this "put_truth");
   160 
   161 local
   162 
   163 val reject_vars = fn ctxt => tap (reject_vars ctxt o Thm.term_of);
   164 
   165 fun check_holds ctxt evaluator vs_t ct =
   166   let
   167     val t = Thm.term_of ct;
   168     val _ = if fastype_of t <> propT
   169       then error ("Not a proposition: " ^ Syntax.string_of_term ctxt t)
   170       else ();
   171     val iff = Thm.cterm_of ctxt (Term.Const (@{const_name Pure.eq}, propT --> propT --> propT));
   172     val result = case partiality_as_none (run_compilation_text truth_cookie ctxt evaluator vs_t [])
   173      of SOME Holds => true
   174       | _ => false;
   175   in
   176     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   177   end;
   178 
   179 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   180   (Thm.add_oracle (@{binding holds_by_evaluation},
   181   fn (ctxt, evaluator, vs_t, ct) => check_holds ctxt evaluator vs_t ct)));
   182 
   183 fun check_holds_oracle ctxt evaluator vs_ty_t ct =
   184   raw_check_holds_oracle (ctxt, evaluator, vs_ty_t, ct);
   185 
   186 in
   187 
   188 fun dynamic_holds_conv ctxt = Code_Thingol.dynamic_conv ctxt
   189   (fn program => fn vs_t => fn deps =>
   190     check_holds_oracle ctxt (build_compilation_text ctxt NONE program deps) vs_t)
   191       o reject_vars ctxt;
   192 
   193 fun static_holds_conv (ctxt_consts as { ctxt, ... }) =
   194   Code_Thingol.static_conv_thingol ctxt_consts (fn { program, deps } => fn ctxt' => fn vs_t =>
   195     K (check_holds_oracle ctxt' (build_compilation_text ctxt NONE program (map Constant deps)) vs_t o reject_vars ctxt'));
   196 
   197 end; (*local*)
   198 
   199 
   200 (** generator for computations -- partial implementations of the universal morphism from Isabelle to ML terms **)
   201 
   202 (* auxiliary *)
   203 
   204 val generated_computationN = "Generated_Computation";
   205 
   206 
   207 (* possible type signatures of constants *)
   208 
   209 fun typ_signatures' T =
   210   let
   211     val (Ts, T') = strip_type T;
   212   in map_range (fn n => (drop n Ts ---> T', take n Ts)) (length Ts + 1) end;
   213 
   214 fun typ_signatures cTs =
   215   let
   216     fun add (c, T) =
   217       fold (fn (T, Ts) => Typtab.map_default (T, []) (cons (c, Ts)))
   218         (typ_signatures' T);
   219   in
   220     Typtab.empty
   221     |> fold add cTs
   222     |> Typtab.lookup_list
   223   end;
   224 
   225 
   226 (* name mangling *)
   227 
   228 local
   229 
   230 fun tycos_of (Type (tyco, Ts)) = maps tycos_of Ts @ [tyco]
   231   | tycos_of _ = [];
   232 
   233 val ml_name_of = Name.desymbolize NONE o Long_Name.base_name;
   234 
   235 in
   236 
   237 val covered_constsN = "covered_consts";
   238 
   239 fun of_term_for_typ Ts =
   240   let
   241     val names = Ts
   242       |> map (suffix "_of_term" o space_implode "_" o map ml_name_of o tycos_of)
   243       |> Name.variant_list [];
   244   in the o AList.lookup (op =) (Ts ~~ names) end;
   245 
   246 fun eval_for_const ctxt cTs =
   247   let
   248     fun symbol_list (c, T) = c :: maps tycos_of (Sign.const_typargs (Proof_Context.theory_of ctxt) (c, T))
   249     val names = cTs
   250       |> map (prefix "eval_" o space_implode "_" o map ml_name_of o symbol_list)
   251       |> Name.variant_list [];
   252   in the o AList.lookup (op =) (cTs ~~ names) end;
   253 
   254 end;
   255 
   256 
   257 (* checks for input terms *)
   258 
   259 fun monomorphic T = fold_atyps ((K o K) false) T true;
   260 
   261 fun check_typ ctxt T t =
   262   Syntax.check_term ctxt (Type.constraint T t);
   263 
   264 fun check_computation_input ctxt cTs t =
   265   let
   266     fun check t = check_comb (strip_comb t)
   267     and check_comb (t as Abs _, _) =
   268           error ("Bad term, contains abstraction: " ^ Syntax.string_of_term ctxt t)
   269       | check_comb (t as Const (cT as (c, T)), ts) =
   270           let
   271             val _ = if not (member (op =) cTs cT)
   272               then error ("Bad term, computation cannot proceed on constant " ^ Syntax.string_of_term ctxt t)
   273               else ();
   274             val _ = if not (monomorphic T)
   275               then error ("Bad term, contains polymorphic constant " ^ Syntax.string_of_term ctxt t)
   276               else ();
   277             val _ = map check ts;
   278           in () end;
   279     val _ = check t;
   280   in t end;
   281 
   282 
   283 (* code generation for of the universal morphism *)
   284 
   285 val print_const = ML_Syntax.print_pair ML_Syntax.print_string ML_Syntax.print_typ;
   286 
   287 fun print_of_term_funs { typ_signatures_for, eval_for_const, of_term_for_typ } Ts =
   288   let
   289     val var_names = map_range (fn n => "t" ^ string_of_int (n + 1));
   290     fun print_lhs c xs = "Const (" ^ quote c ^ ", _)"
   291       |> fold (fn x => fn s => s ^ " $ " ^ x) xs
   292       |> enclose "(" ")";
   293     fun print_rhs c Ts T xs = eval_for_const (c, Ts ---> T)
   294       |> fold2 (fn T' => fn x => fn s =>
   295          s ^ (" (" ^ of_term_for_typ T' ^ " " ^ x ^ ")")) Ts xs
   296     fun print_eq T (c, Ts) =
   297       let
   298         val xs = var_names (length Ts);
   299       in print_lhs c xs ^ " = " ^ print_rhs c Ts T xs end;
   300     fun print_eqs T =
   301       let
   302         val typ_signs = typ_signatures_for T;
   303         val name = of_term_for_typ T;
   304       in
   305         map (print_eq T) typ_signs
   306         |> map (prefix (name ^ " "))
   307         |> space_implode "\n  | "
   308       end;
   309   in
   310     map print_eqs Ts
   311     |> space_implode "\nand "
   312     |> prefix "fun "
   313   end;
   314 
   315 fun print_computation_code ctxt compiled_value [] requested_Ts =
   316       if null requested_Ts then ("", [])
   317       else error ("No equation available for requested type "
   318         ^ Syntax.string_of_typ ctxt (hd requested_Ts))
   319   | print_computation_code ctxt compiled_value cTs requested_Ts =
   320       let
   321         val proper_cTs = map_filter I cTs;
   322         val typ_signatures_for = typ_signatures proper_cTs;
   323         fun add_typ T Ts =
   324           if member (op =) Ts T
   325           then Ts
   326           else case typ_signatures_for T of
   327             [] => error ("No equation available for requested type "
   328               ^ Syntax.string_of_typ ctxt T)
   329           | typ_signs =>
   330               Ts
   331               |> cons T
   332               |> fold (fold add_typ o snd) typ_signs;
   333         val required_Ts = fold add_typ requested_Ts [];
   334         val of_term_for_typ' = of_term_for_typ required_Ts;
   335         val eval_for_const' = eval_for_const ctxt proper_cTs;
   336         val eval_for_const'' = the_default "_" o Option.map eval_for_const';
   337         val eval_tuple = enclose "(" ")" (commas (map eval_for_const' proper_cTs));
   338         fun mk_abs s = "fn " ^ s ^ " => ";
   339         val eval_abs = space_implode ""
   340           (map (mk_abs o eval_for_const'') cTs);
   341         val of_term_code = print_of_term_funs {
   342           typ_signatures_for = typ_signatures_for,
   343           eval_for_const = eval_for_const',
   344           of_term_for_typ = of_term_for_typ' } required_Ts;
   345         val of_term_names = map (Long_Name.append generated_computationN
   346           o of_term_for_typ') requested_Ts;
   347       in
   348         cat_lines [
   349           "structure " ^ generated_computationN ^ " =",
   350           "struct",
   351           "",
   352           "val " ^ covered_constsN ^ " = " ^ ML_Syntax.print_list print_const proper_cTs ^ ";",
   353           "",
   354           "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
   355           "  (" ^ eval_abs,
   356           "    " ^ eval_tuple ^ ");",
   357           "",
   358           of_term_code,
   359           "",
   360           "end"
   361         ] |> rpair of_term_names
   362       end;
   363 
   364 
   365 (* dedicated preprocessor for computations *)
   366 
   367 structure Computation_Preproc_Data = Theory_Data
   368 (
   369   type T = thm list;
   370   val empty = [];
   371   val extend = I;
   372   val merge = Library.merge Thm.eq_thm_prop;
   373 );
   374 
   375 local
   376 
   377 fun add thm thy =
   378   let
   379     val thms = Simplifier.mksimps (Proof_Context.init_global thy) thm;
   380   in
   381     thy
   382     |> Computation_Preproc_Data.map (union Thm.eq_thm_prop thms)
   383   end;
   384 
   385 fun get ctxt = Computation_Preproc_Data.get (Proof_Context.theory_of ctxt);
   386 
   387 in
   388 
   389 fun preprocess_conv { ctxt } = 
   390   let
   391     val rules = get ctxt;
   392   in fn ctxt' => Raw_Simplifier.rewrite ctxt' false rules end;
   393 
   394 fun preprocess_term { ctxt } =
   395   let
   396     val rules = map (Logic.dest_equals o Thm.plain_prop_of) (get ctxt);
   397   in fn ctxt' => Pattern.rewrite_term (Proof_Context.theory_of ctxt') rules [] end;
   398 
   399 val _ = Theory.setup
   400   (Attrib.setup @{binding code_computation_unfold}
   401     (Scan.succeed (Thm.declaration_attribute (fn thm => Context.mapping (add thm) I)))
   402     "preprocessing equations for computation");
   403 
   404 end;
   405 
   406 
   407 (* mounting computations *)
   408 
   409 fun prechecked_computation T raw_computation ctxt =
   410   check_typ ctxt T
   411   #> reject_vars ctxt
   412   #> raw_computation ctxt;
   413 
   414 fun prechecked_conv T raw_conv ctxt =
   415   tap (check_typ ctxt T o reject_vars ctxt o Thm.term_of)
   416   #> raw_conv ctxt;
   417 
   418 fun checked_computation cTs raw_computation ctxt =
   419   check_computation_input ctxt cTs
   420   #> Exn.capture raw_computation
   421   #> partiality_as_none;
   422 
   423 fun mount_computation ctxt cTs T raw_computation lift_postproc =
   424   let
   425     val preprocess = preprocess_term { ctxt = ctxt };
   426     val computation = prechecked_computation T (Code_Preproc.static_value
   427       { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
   428       (K (checked_computation cTs raw_computation)));
   429   in fn ctxt' => preprocess ctxt' #> computation ctxt' end;
   430 
   431 fun mount_computation_conv ctxt cTs T raw_computation conv =
   432   let
   433     val preprocess = preprocess_conv { ctxt = ctxt };
   434     val computation_conv = prechecked_conv T (Code_Preproc.static_conv
   435       { ctxt = ctxt, consts = [] }
   436       (K (fn ctxt' => fn t =>
   437         case checked_computation cTs raw_computation ctxt' t of
   438           SOME x => conv x
   439         | NONE => Conv.all_conv)));
   440   in fn ctxt' => preprocess ctxt' then_conv computation_conv ctxt' end;
   441 
   442 local
   443 
   444 fun holds ct = Thm.mk_binop @{cterm "Pure.eq :: prop \<Rightarrow> prop \<Rightarrow> prop"}
   445   ct @{cprop "PROP Code_Generator.holds"};
   446 
   447 val (_, holds_oracle) = Context.>>> (Context.map_theory_result
   448   (Thm.add_oracle (@{binding holds}, holds)));
   449 
   450 in
   451 
   452 fun mount_computation_check ctxt cTs raw_computation =
   453   mount_computation_conv ctxt cTs @{typ prop} raw_computation
   454     (K holds_oracle);
   455 
   456 end;
   457 
   458 
   459 (** variants of universal runtime code generation **)
   460 
   461 (*FIXME consolidate variants*)
   462 
   463 fun runtime_code'' ctxt module_name program tycos consts =
   464   let
   465     val thy = Proof_Context.theory_of ctxt;
   466     val (ml_modules, target_names) =
   467       Code_Target.produce_code_for ctxt
   468         target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
   469     val ml_code = space_implode "\n\n" (map snd ml_modules);
   470     val (consts', tycos') = chop (length consts) target_names;
   471     val consts_map = map2 (fn const =>
   472       fn NONE =>
   473           error ("Constant " ^ (quote o Code.string_of_const thy) const ^
   474             "\nhas a user-defined serialization")
   475        | SOME const' => (const, const')) consts consts'
   476     val tycos_map = map2 (fn tyco =>
   477       fn NONE =>
   478           error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   479             "\nhas a user-defined serialization")
   480         | SOME tyco' => (tyco, tyco')) tycos tycos';
   481   in (ml_code, (tycos_map, consts_map)) end;
   482 
   483 fun runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   484   let
   485     val thy = Proof_Context.theory_of ctxt;
   486     fun the_const (Const cT) = cT
   487       | the_const t = error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)
   488     val raw_computation_cTs = case evals of
   489         Abs (_, _, t) => (map the_const o snd o strip_comb) t
   490       | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
   491     val computation_cTs = fold_rev (fn cT => fn cTs =>
   492       (if member (op =) cTs (SOME cT) then NONE else SOME cT) :: cTs) raw_computation_cTs [];
   493     val consts' = fold (fn NONE => I | SOME (c, _) => insert (op =) c)
   494       computation_cTs named_consts;
   495     val program' = Code_Thingol.consts_program ctxt consts';
   496       (*FIXME insufficient interfaces require double invocation of code generator*)
   497     val ((ml_modules, compiled_value), deresolve) =
   498       Code_Target.compilation_text' ctxt target some_module_name program'
   499         (map Code_Symbol.Type_Constructor named_tycos @ map Code_Symbol.Constant consts' @ deps) true vs_ty_evals;
   500         (*FIXME constrain signature*)
   501     fun deresolve_const c = case (deresolve o Code_Symbol.Constant) c of
   502           NONE => error ("Constant " ^ (quote o Code.string_of_const thy) c ^
   503             "\nhas a user-defined serialization")
   504         | SOME c' => c';
   505     fun deresolve_tyco tyco = case (deresolve o Code_Symbol.Type_Constructor) tyco of
   506           NONE => error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   507             "\nhas a user-defined serialization")
   508         | SOME c' => c';
   509     val tyco_names =  map deresolve_const named_tycos;
   510     val const_names = map deresolve_const named_consts;
   511     val generated_code = space_implode "\n\n" (map snd ml_modules);
   512     val (of_term_code, of_term_names) =
   513       print_computation_code ctxt compiled_value computation_cTs computation_Ts;
   514     val compiled_computation = generated_code ^ "\n" ^ of_term_code;
   515   in
   516     compiled_computation
   517     |> rpair { tyco_map = named_tycos ~~ tyco_names,
   518       const_map = named_consts ~~ const_names,
   519       of_term_map = computation_Ts ~~ of_term_names }
   520   end;
   521 
   522 fun funs_of_maps { tyco_map, const_map, of_term_map } =
   523   { name_for_tyco = the o AList.lookup (op =) tyco_map,
   524     name_for_const = the o AList.lookup (op =) const_map,
   525     of_term_for_typ = the o AList.lookup (op =) of_term_map };
   526 
   527 fun runtime_code ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   528   runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps
   529   ||> funs_of_maps;
   530 
   531 
   532 (** code and computation antiquotations **)
   533 
   534 local
   535 
   536 val mount_computationN = prefix_this "mount_computation";
   537 val mount_computation_convN = prefix_this "mount_computation_conv";
   538 val mount_computation_checkN = prefix_this "mount_computation_check";
   539 
   540 structure Code_Antiq_Data = Proof_Data
   541 (
   542   type T = { named_consts: string list,
   543     computation_Ts: typ list, computation_cTs: (string * typ) list,
   544     position_index: int,
   545     generated_code: (string * {
   546       name_for_tyco: string -> string,
   547       name_for_const: string -> string,
   548       of_term_for_typ: typ -> string
   549     }) lazy
   550   };
   551   val empty: T = { named_consts = [],
   552     computation_Ts = [], computation_cTs = [],
   553     position_index = 0,
   554     generated_code = Lazy.lazy (fn () => raise Fail "empty")
   555   };
   556   fun init _ = empty;
   557 );
   558 
   559 val current_position_index = #position_index o Code_Antiq_Data.get;
   560 
   561 fun register { named_consts, computation_Ts, computation_cTs } ctxt =
   562   let
   563     val data = Code_Antiq_Data.get ctxt;
   564     val named_consts' = union (op =) named_consts (#named_consts data);
   565     val computation_Ts' = union (op =) computation_Ts (#computation_Ts data);
   566     val computation_cTs' = union (op =) computation_cTs (#computation_cTs data);
   567     val position_index' = #position_index data + 1;
   568     fun generated_code' () =
   569       let
   570         val evals = Abs ("eval", map snd computation_cTs' --->
   571           TFree (Name.aT, []), list_comb (Bound 0, map Const computation_cTs'))
   572           |> preprocess_term { ctxt = ctxt } ctxt
   573       in Code_Thingol.dynamic_value ctxt
   574         (K I) (runtime_code ctxt NONE [] named_consts' computation_Ts') evals
   575       end;
   576   in
   577     ctxt
   578     |> Code_Antiq_Data.put { 
   579         named_consts = named_consts',
   580         computation_Ts = computation_Ts',
   581         computation_cTs = computation_cTs',
   582         position_index = position_index',
   583         generated_code = Lazy.lazy generated_code'
   584       }
   585   end;
   586 
   587 fun register_const const =
   588   register { named_consts = [const],
   589     computation_Ts = [],
   590     computation_cTs = [] };
   591 
   592 fun register_computation cTs T =
   593   register { named_consts = [],
   594     computation_Ts = [T],
   595     computation_cTs = cTs };
   596 
   597 fun print body_code_for ctxt ctxt' =
   598   let
   599     val position_index = current_position_index ctxt;
   600     val (code, name_ofs) = (Lazy.force o #generated_code o Code_Antiq_Data.get) ctxt';
   601     val context_code = if position_index = 0 then code else "";
   602     val body_code = body_code_for name_ofs (ML_Context.struct_name ctxt');
   603   in (context_code, body_code) end;
   604 
   605 fun print_code ctxt const =
   606   print (fn { name_for_const, ... } => fn prfx =>
   607     Long_Name.append prfx (name_for_const const)) ctxt;
   608 
   609 fun print_computation kind ctxt T =
   610   print (fn { of_term_for_typ, ... } => fn prfx =>
   611     space_implode " " [
   612       kind,
   613       "(Context.proof_of (Context.the_generic_context ()))",
   614       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   615       (ML_Syntax.atomic o ML_Syntax.print_typ) T,
   616       Long_Name.append prfx (of_term_for_typ T)
   617     ]) ctxt;
   618 
   619 fun print_computation_check ctxt =
   620   print (fn { of_term_for_typ, ... } => fn prfx =>
   621     space_implode " " [
   622       mount_computation_checkN,
   623       "(Context.proof_of (Context.the_generic_context ()))",
   624       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   625       Long_Name.append prfx (of_term_for_typ @{typ prop})
   626     ]) ctxt;
   627 
   628 
   629 fun add_all_constrs ctxt (dT as Type (tyco, Ts)) =
   630   let
   631     val ((vs, constrs), _) = Code.get_type (Proof_Context.theory_of ctxt) tyco;
   632     val subst_TFree = the o AList.lookup (op =) (map fst vs ~~ Ts);
   633     val cs = map (fn (c, (_, Ts')) =>
   634       (c, (map o map_atyps) (fn TFree (v, _) => subst_TFree v) Ts'
   635         ---> dT)) constrs;
   636   in
   637     union (op =) cs
   638     #> fold (add_all_constrs ctxt) Ts
   639   end;
   640 
   641 fun prep_spec ctxt (raw_ts, raw_dTs) =
   642   let
   643     val ts = map (Syntax.check_term ctxt) raw_ts;
   644     val dTs = map (Syntax.check_typ ctxt) raw_dTs;
   645   in
   646     []
   647     |> (fold o fold_aterms)
   648       (fn (t as Const (cT as (_, T))) =>
   649         if not (monomorphic T) then error ("Polymorphic constant: " ^ Syntax.string_of_term ctxt t)
   650         else insert (op =) cT | _ => I) ts
   651     |> fold (fn dT =>
   652         if not (monomorphic dT) then error ("Polymorphic datatype: " ^ Syntax.string_of_typ ctxt dT)
   653         else add_all_constrs ctxt dT) dTs
   654   end;
   655 
   656 in
   657 
   658 fun ml_code_antiq raw_const ctxt =
   659   let
   660     val thy = Proof_Context.theory_of ctxt;
   661     val const = Code.check_const thy raw_const;
   662   in (print_code ctxt const, register_const const ctxt) end;
   663 
   664 fun gen_ml_computation_antiq kind (raw_T, raw_spec) ctxt =
   665   let
   666     val cTs = prep_spec ctxt raw_spec;
   667     val T = Syntax.check_typ ctxt raw_T;
   668     val _ = if not (monomorphic T)
   669       then error ("Polymorphic type: " ^ Syntax.string_of_typ ctxt T)
   670       else ();
   671   in (print_computation kind ctxt T, register_computation cTs T ctxt) end;
   672 
   673 val ml_computation_antiq = gen_ml_computation_antiq mount_computationN;
   674 
   675 val ml_computation_conv_antiq = gen_ml_computation_antiq mount_computation_convN;
   676 
   677 fun ml_computation_check_antiq raw_spec ctxt =
   678   let
   679     val cTs = insert (op =) (dest_Const @{const holds}) (prep_spec ctxt raw_spec);
   680   in (print_computation_check ctxt, register_computation cTs @{typ prop} ctxt) end;
   681 
   682 end; (*local*)
   683 
   684 
   685 (** reflection support **)
   686 
   687 fun check_datatype thy tyco some_consts =
   688   let
   689     val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
   690     val constrs = case some_consts
   691      of SOME [] => []
   692       | SOME consts =>
   693           let
   694             val missing_constrs = subtract (op =) consts declared_constrs;
   695             val _ = if null missing_constrs then []
   696               else error ("Missing constructor(s) " ^ commas_quote missing_constrs
   697                 ^ " for datatype " ^ quote tyco);
   698             val false_constrs = subtract (op =) declared_constrs consts;
   699             val _ = if null false_constrs then []
   700               else error ("Non-constructor(s) " ^ commas_quote false_constrs
   701                 ^ " for datatype " ^ quote tyco)
   702           in consts end
   703       | NONE => declared_constrs;
   704   in (tyco, constrs) end;
   705 
   706 fun add_eval_tyco (tyco, tyco') thy =
   707   let
   708     val k = Sign.arity_number thy tyco;
   709     fun pr pr' _ [] = tyco'
   710       | pr pr' _ [ty] =
   711           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   712       | pr pr' _ tys =
   713           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   714   in
   715     thy
   716     |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
   717   end;
   718 
   719 fun add_eval_constr (const, const') thy =
   720   let
   721     val k = Code.args_number thy const;
   722     fun pr pr' fxy ts = Code_Printer.brackify fxy
   723       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   724   in
   725     thy
   726     |> Code_Target.set_printings (Constant (const,
   727       [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
   728   end;
   729 
   730 fun add_eval_const (const, const') = Code_Target.set_printings (Constant
   731   (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
   732 
   733 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   734       thy
   735       |> Code_Target.add_reserved target module_name
   736       |> Context.theory_map (compile_ML true code)
   737       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   738       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   739       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   740   | process_reflection (code, _) _ (SOME file_name) thy =
   741       let
   742         val preamble =
   743           "(* Generated from " ^
   744             Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
   745           "; DO NOT EDIT! *)";
   746         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   747       in
   748         thy
   749       end;
   750 
   751 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   752   let
   753     val ctxt = Proof_Context.init_global thy;
   754     val datatypes = map (fn (raw_tyco, raw_cos) =>
   755       (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
   756     val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
   757       |> apsnd flat;
   758     val functions = map (prep_const thy) raw_functions;
   759     val consts = constrs @ functions;
   760     val program = Code_Thingol.consts_program ctxt consts;
   761     val result = runtime_code'' ctxt module_name program tycos consts
   762       |> (apsnd o apsnd) (chop (length constrs));
   763   in
   764     thy
   765     |> process_reflection result module_name some_file
   766   end;
   767 
   768 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   769 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   770 
   771 
   772 (** Isar setup **)
   773 
   774 local
   775 
   776 val parse_consts_spec =
   777   Scan.optional (Scan.lift (Args.$$$ "terms" -- Args.colon) |-- Scan.repeat1 Args.term) []
   778   -- Scan.optional (Scan.lift (Args.$$$ "datatypes"  -- Args.colon) |-- Scan.repeat1 Args.typ) [];
   779 
   780 in
   781 
   782 val _ = Theory.setup
   783   (ML_Antiquotation.declaration @{binding code}
   784     Args.term (K ml_code_antiq)
   785   #> ML_Antiquotation.declaration @{binding computation}
   786     (Args.typ -- parse_consts_spec) (K ml_computation_antiq)
   787   #> ML_Antiquotation.declaration @{binding computation_conv}
   788     (Args.typ -- parse_consts_spec) (K ml_computation_conv_antiq)
   789   #> ML_Antiquotation.declaration @{binding computation_check}
   790     parse_consts_spec (K ml_computation_check_antiq));
   791 
   792 end;
   793 
   794 local
   795 
   796 val parse_datatype =
   797   Parse.name -- Scan.optional (@{keyword "="} |--
   798     (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
   799     || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
   800 
   801 in
   802 
   803 val _ =
   804   Outer_Syntax.command @{command_keyword code_reflect}
   805     "enrich runtime environment with generated code"
   806     (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
   807       ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
   808     -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
   809     -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
   810     >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   811       (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   812 
   813 end; (*local*)
   814 
   815 
   816 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   817 
   818 local
   819 
   820 structure Loaded_Values = Theory_Data
   821 (
   822   type T = string list
   823   val empty = []
   824   val extend = I
   825   fun merge data : T = Library.merge (op =) data
   826 );
   827 
   828 fun notify_val (string, value) = 
   829   let
   830     val _ = #enterVal ML_Env.name_space (string, value);
   831     val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
   832   in () end;
   833 
   834 fun abort _ = error "Only value bindings allowed.";
   835 
   836 val notifying_context : ML_Compiler0.context =
   837  {name_space =
   838    {lookupVal    = #lookupVal ML_Env.name_space,
   839     lookupType   = #lookupType ML_Env.name_space,
   840     lookupFix    = #lookupFix ML_Env.name_space,
   841     lookupStruct = #lookupStruct ML_Env.name_space,
   842     lookupSig    = #lookupSig ML_Env.name_space,
   843     lookupFunct  = #lookupFunct ML_Env.name_space,
   844     enterVal     = notify_val,
   845     enterType    = abort,
   846     enterFix     = abort,
   847     enterStruct  = abort,
   848     enterSig     = abort,
   849     enterFunct   = abort,
   850     allVal       = #allVal ML_Env.name_space,
   851     allType      = #allType ML_Env.name_space,
   852     allFix       = #allFix ML_Env.name_space,
   853     allStruct    = #allStruct ML_Env.name_space,
   854     allSig       = #allSig ML_Env.name_space,
   855     allFunct     = #allFunct ML_Env.name_space},
   856   print_depth = NONE,
   857   here = #here ML_Env.context,
   858   print = #print ML_Env.context,
   859   error = #error ML_Env.context};
   860 
   861 in
   862 
   863 fun use_file filepath thy =
   864   let
   865     val thy' = Loaded_Values.put [] thy;
   866     val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
   867     val _ =
   868       ML_Compiler0.ML notifying_context
   869         {line = 0, file = Path.implode filepath, verbose = false, debug = false}
   870         (File.read filepath);
   871     val thy'' = Context.the_global_context ();
   872     val names = Loaded_Values.get thy'';
   873   in (names, thy'') end;
   874 
   875 end;
   876 
   877 fun add_definiendum (ml_name, (b, T)) thy =
   878   thy
   879   |> Code_Target.add_reserved target ml_name
   880   |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
   881   |-> (fn ([Const (const, _)], _) =>
   882     Code_Target.set_printings (Constant (const,
   883       [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
   884   #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
   885 
   886 fun process_file filepath (definienda, thy) =
   887   let
   888     val (ml_names, thy') = use_file filepath thy;
   889     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   890     val _ = if null superfluous then ()
   891       else error ("Value binding(s) " ^ commas_quote superfluous
   892         ^ " found in external file " ^ Path.print filepath
   893         ^ " not present among the given contants binding(s).");
   894     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   895     val thy'' = fold add_definiendum these_definienda thy';
   896     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   897   in (definienda', thy'') end;
   898 
   899 fun polyml_as_definition bTs filepaths thy =
   900   let
   901     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   902     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   903     val _ = if null remaining then ()
   904       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   905         ^ " not present in external file(s).");
   906   in thy' end;
   907 
   908 end; (*struct*)