src/Pure/ML/ml_context.ML
author wenzelm
Mon Jun 01 23:28:07 2009 +0200 (2009-06-01)
changeset 31334 999fa9e1dbdd
parent 31325 700951b53d21
child 32738 15bb09ca0378
permissions -rw-r--r--
structure ML_Compiler;
     1 (*  Title:      Pure/ML/ml_context.ML
     2     Author:     Makarius
     3 
     4 ML context and antiquotations.
     5 *)
     6 
     7 signature BASIC_ML_CONTEXT =
     8 sig
     9   val bind_thm: string * thm -> unit
    10   val bind_thms: string * thm list -> unit
    11   val thm: xstring -> thm
    12   val thms: xstring -> thm list
    13 end
    14 
    15 signature ML_CONTEXT =
    16 sig
    17   include BASIC_ML_CONTEXT
    18   val the_generic_context: unit -> Context.generic
    19   val the_global_context: unit -> theory
    20   val the_local_context: unit -> Proof.context
    21   val exec: (unit -> unit) -> Context.generic -> Context.generic
    22   val stored_thms: thm list ref
    23   val ml_store_thm: string * thm -> unit
    24   val ml_store_thms: string * thm list -> unit
    25   type antiq =
    26     {struct_name: string, background: Proof.context} ->
    27       (Proof.context -> string * string) * Proof.context
    28   val add_antiq: string -> (Position.T -> antiq context_parser) -> unit
    29   val trace: bool ref
    30   val eval_antiquotes: ML_Lex.token Antiquote.antiquote list * Position.T ->
    31     Context.generic option -> (ML_Lex.token list * ML_Lex.token list) * Context.generic option
    32   val eval: bool -> Position.T -> Symbol_Pos.text -> unit
    33   val eval_file: Path.T -> unit
    34   val eval_in: Proof.context option -> bool -> Position.T -> Symbol_Pos.text -> unit
    35   val evaluate: Proof.context -> bool -> string * (unit -> 'a) option ref -> string -> 'a
    36   val expression: Position.T -> string -> string -> string -> Context.generic -> Context.generic
    37 end
    38 
    39 structure ML_Context: ML_CONTEXT =
    40 struct
    41 
    42 (** implicit ML context **)
    43 
    44 val the_generic_context = Context.the_thread_data;
    45 val the_global_context = Context.theory_of o the_generic_context;
    46 val the_local_context = Context.proof_of o the_generic_context;
    47 
    48 fun exec (e: unit -> unit) context =
    49   (case Context.setmp_thread_data (SOME context) (fn () => (e (); Context.thread_data ())) () of
    50     SOME context' => context'
    51   | NONE => error "Missing context after execution");
    52 
    53 
    54 (* theorem bindings *)
    55 
    56 val stored_thms: thm list ref = ref [];
    57 
    58 fun ml_store sel (name, ths) =
    59   let
    60     val ths' = Context.>>> (Context.map_theory_result
    61       (PureThy.store_thms (Binding.name name, ths)));
    62     val _ =
    63       if name = "" then ()
    64       else if not (ML_Syntax.is_identifier name) then
    65         error ("Cannot bind theorem(s) " ^ quote name ^ " as ML value")
    66       else setmp stored_thms ths' (fn () =>
    67         ML_Compiler.eval true Position.none
    68           (ML_Lex.tokenize ("val " ^ name ^ " = " ^ sel ^ "(! ML_Context.stored_thms);"))) ();
    69   in () end;
    70 
    71 val ml_store_thms = ml_store "";
    72 fun ml_store_thm (name, th) = ml_store "hd" (name, [th]);
    73 
    74 fun bind_thm (name, thm) = ml_store_thm (name, Drule.standard thm);
    75 fun bind_thms (name, thms) = ml_store_thms (name, map Drule.standard thms);
    76 
    77 fun thm name = ProofContext.get_thm (the_local_context ()) name;
    78 fun thms name = ProofContext.get_thms (the_local_context ()) name;
    79 
    80 
    81 
    82 (** ML antiquotations **)
    83 
    84 (* antiquotation commands *)
    85 
    86 type antiq =
    87   {struct_name: string, background: Proof.context} ->
    88     (Proof.context -> string * string) * Proof.context;
    89 
    90 local
    91 
    92 val global_parsers = ref (Symtab.empty: (Position.T -> antiq context_parser) Symtab.table);
    93 
    94 in
    95 
    96 fun add_antiq name scan = CRITICAL (fn () =>
    97   change global_parsers (fn tab =>
    98    (if not (Symtab.defined tab name) then ()
    99     else warning ("Redefined ML antiquotation: " ^ quote name);
   100     Symtab.update (name, scan) tab)));
   101 
   102 fun antiquotation src ctxt =
   103   let val ((name, _), pos) = Args.dest_src src in
   104     (case Symtab.lookup (! global_parsers) name of
   105       NONE => error ("Unknown ML antiquotation command: " ^ quote name ^ Position.str_of pos)
   106     | SOME scan => (Position.report (Markup.ML_antiq name) pos;
   107         Args.context_syntax "ML antiquotation" (scan pos) src ctxt))
   108   end;
   109 
   110 end;
   111 
   112 
   113 (* parsing and evaluation *)
   114 
   115 local
   116 
   117 structure P = OuterParse;
   118 structure T = OuterLex;
   119 
   120 val antiq =
   121   P.!!! (P.position P.xname -- Args.parse --| Scan.ahead P.eof)
   122   >> (fn ((x, pos), y) => Args.src ((x, y), pos));
   123 
   124 val struct_name = "Isabelle";
   125 val begin_env = ML_Lex.tokenize ("structure " ^ struct_name ^ " =\nstruct\n");
   126 val end_env = ML_Lex.tokenize "end;";
   127 val reset_env = ML_Lex.tokenize "structure Isabelle = struct end";
   128 
   129 in
   130 
   131 fun eval_antiquotes (ants, pos) opt_context =
   132   let
   133     val opt_ctxt = Option.map (Context.Proof o Context.proof_of) opt_context;
   134     val ((ml_env, ml_body), opt_ctxt') =
   135       if forall Antiquote.is_text ants
   136       then (([], map (fn Antiquote.Text tok => tok) ants), opt_ctxt)
   137       else
   138         let
   139           val ctxt =
   140             (case opt_ctxt of
   141               NONE => error ("No context -- cannot expand ML antiquotations" ^ Position.str_of pos)
   142             | SOME ctxt => Context.proof_of ctxt);
   143 
   144           val lex = #1 (OuterKeyword.get_lexicons ());
   145           fun no_decl _ = ([], []);
   146 
   147           fun expand (Antiquote.Text tok) state = (K ([], [tok]), state)
   148             | expand (Antiquote.Antiq (ss, range)) (scope, background) =
   149                 let
   150                   val context = Stack.top scope;
   151                   val (f, context') = antiquotation (T.read_antiq lex antiq (ss, #1 range)) context;
   152                   val (decl, background') = f {background = background, struct_name = struct_name};
   153                   val decl' = decl #> pairself (ML_Lex.tokenize #> map (ML_Lex.set_range range));
   154                 in (decl', (Stack.map_top (K context') scope, background')) end
   155             | expand (Antiquote.Open _) (scope, background) =
   156                 (no_decl, (Stack.push scope, background))
   157             | expand (Antiquote.Close _) (scope, background) =
   158                 (no_decl, (Stack.pop scope, background));
   159 
   160           val (decls, (_, ctxt')) = fold_map expand ants (Stack.init ctxt, ctxt);
   161           val ml = decls |> map (fn decl => decl ctxt') |> split_list |> pairself flat;
   162         in (ml, SOME (Context.Proof ctxt')) end;
   163   in ((begin_env @ ml_env @ end_env, ml_body), opt_ctxt') end;
   164 
   165 val trace = ref false;
   166 
   167 fun eval verbose pos txt =
   168   let
   169     (*prepare source text*)
   170     val _ = Position.report Markup.ML_source pos;
   171     val ants = ML_Lex.read_antiq (Symbol_Pos.explode (txt, pos), pos);
   172     val ((env, body), env_ctxt) = eval_antiquotes (ants, pos) (Context.thread_data ());
   173     val _ =
   174       if ! trace then tracing (cat_lines [ML_Lex.flatten env, ML_Lex.flatten body])
   175       else ();
   176 
   177     (*prepare static ML environment*)
   178     val _ = Context.setmp_thread_data env_ctxt
   179         (fn () => (ML_Compiler.eval false Position.none env; Context.thread_data ())) ()
   180       |> (fn NONE => () | SOME context' => Context.>> (ML_Env.inherit context'));
   181 
   182     val _ = ML_Compiler.eval verbose pos body;
   183     val _ = ML_Compiler.eval false Position.none reset_env;
   184   in () end;
   185 
   186 end;
   187 
   188 
   189 (* derived versions *)
   190 
   191 fun eval_file path = eval true (Path.position path) (File.read path);
   192 
   193 fun eval_in ctxt verbose pos txt =
   194   Context.setmp_thread_data (Option.map Context.Proof ctxt) (fn () => eval verbose pos txt) ();
   195 
   196 fun evaluate ctxt verbose (ref_name, r) txt = NAMED_CRITICAL "ML" (fn () =>
   197   let
   198     val _ = r := NONE;
   199     val _ = Context.setmp_thread_data (SOME (Context.Proof ctxt)) (fn () =>
   200       eval verbose Position.none ("val _ = (" ^ ref_name ^ " := SOME (fn () => " ^ txt ^ "))")) ();
   201   in (case ! r of NONE => error ("Bad evaluation for " ^ ref_name) | SOME e => e) end) ();
   202 
   203 fun expression pos bind body txt =
   204   exec (fn () => eval false pos
   205     ("Context.set_thread_data (SOME (let " ^ bind ^ " = " ^ txt ^ " in " ^ body ^
   206       " end (ML_Context.the_generic_context ())));"));
   207 
   208 end;
   209 
   210 structure Basic_ML_Context: BASIC_ML_CONTEXT = ML_Context;
   211 open Basic_ML_Context;