src/Pure/PIDE/document.ML
author wenzelm
Fri Mar 16 13:05:30 2012 +0100 (2012-03-16)
changeset 46958 0ec8f04e753a
parent 46950 d0181abdbdac
child 47051 b32e6de4a39b
permissions -rw-r--r--
define keywords early when processing the theory header, before running the body commands;
     1 (*  Title:      Pure/PIDE/document.ML
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, with asynchronous read/eval/print processes.
     6 *)
     7 
     8 signature DOCUMENT =
     9 sig
    10   type id = int
    11   type version_id = id
    12   type command_id = id
    13   type exec_id = id
    14   val no_id: id
    15   val new_id: unit -> id
    16   val parse_id: string -> id
    17   val print_id: id -> string
    18   type node_header = (string * Thy_Header.header) Exn.result
    19   datatype node_edit =
    20     Clear |
    21     Edits of (command_id option * command_id option) list |
    22     Header of node_header |
    23     Perspective of command_id list
    24   type edit = string * node_edit
    25   type state
    26   val init_state: state
    27   val define_command: command_id -> string -> string -> state -> state
    28   val cancel_execution: state -> Future.task list
    29   val update_perspective: version_id -> version_id -> string -> command_id list -> state -> state
    30   val update: version_id -> version_id -> edit list -> state ->
    31     ((command_id * exec_id option) list * (string * command_id option) list) * state
    32   val execute: version_id -> state -> state
    33   val remove_versions: version_id list -> state -> state
    34   val state: unit -> state
    35   val change_state: (state -> state) -> unit
    36 end;
    37 
    38 structure Document: DOCUMENT =
    39 struct
    40 
    41 (* unique identifiers *)
    42 
    43 type id = int;
    44 type version_id = id;
    45 type command_id = id;
    46 type exec_id = id;
    47 
    48 val no_id = 0;
    49 val new_id = Synchronized.counter ();
    50 
    51 val parse_id = Markup.parse_int;
    52 val print_id = Markup.print_int;
    53 
    54 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    55 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    56 
    57 
    58 
    59 (** document structure **)
    60 
    61 type node_header = (string * Thy_Header.header) Exn.result;
    62 type perspective = (command_id -> bool) * command_id option; (*visible commands, last*)
    63 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    64 
    65 type exec = exec_id * (Toplevel.state * unit lazy) lazy;  (*eval/print process*)
    66 val no_print = Lazy.value ();
    67 val no_exec = (no_id, Lazy.value (Toplevel.toplevel, no_print));
    68 
    69 abstype node = Node of
    70  {touched: bool,
    71   header: node_header,
    72   perspective: perspective,
    73   entries: exec option Entries.T,  (*command entries with excecutions*)
    74   last_exec: command_id option,  (*last command with exec state assignment*)
    75   result: Toplevel.state lazy}
    76 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    77 with
    78 
    79 fun make_node (touched, header, perspective, entries, last_exec, result) =
    80   Node {touched = touched, header = header, perspective = perspective,
    81     entries = entries, last_exec = last_exec, result = result};
    82 
    83 fun map_node f (Node {touched, header, perspective, entries, last_exec, result}) =
    84   make_node (f (touched, header, perspective, entries, last_exec, result));
    85 
    86 fun make_perspective command_ids : perspective =
    87   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    88 
    89 val no_header = Exn.Exn (ERROR "Bad theory header");
    90 val no_perspective = make_perspective [];
    91 val no_result = Lazy.value Toplevel.toplevel;
    92 
    93 val empty_node = make_node (false, no_header, no_perspective, Entries.empty, NONE, no_result);
    94 val clear_node = map_node (fn (_, header, _, _, _, _) =>
    95   (false, header, no_perspective, Entries.empty, NONE, no_result));
    96 
    97 
    98 (* basic components *)
    99 
   100 fun is_touched (Node {touched, ...}) = touched;
   101 fun set_touched touched =
   102   map_node (fn (_, header, perspective, entries, last_exec, result) =>
   103     (touched, header, perspective, entries, last_exec, result));
   104 
   105 fun get_header (Node {header, ...}) = header;
   106 fun set_header header =
   107   map_node (fn (touched, _, perspective, entries, last_exec, result) =>
   108     (touched, header, perspective, entries, last_exec, result));
   109 
   110 fun get_perspective (Node {perspective, ...}) = perspective;
   111 fun set_perspective ids =
   112   map_node (fn (touched, header, _, entries, last_exec, result) =>
   113     (touched, header, make_perspective ids, entries, last_exec, result));
   114 
   115 fun map_entries f =
   116   map_node (fn (touched, header, perspective, entries, last_exec, result) =>
   117     (touched, header, perspective, f entries, last_exec, result));
   118 fun get_entries (Node {entries, ...}) = entries;
   119 
   120 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   121 fun iterate_entries_after start f (Node {entries, ...}) =
   122   (case Entries.get_after entries start of
   123     NONE => I
   124   | SOME id => Entries.iterate (SOME id) f entries);
   125 
   126 fun get_last_exec (Node {last_exec, ...}) = last_exec;
   127 fun set_last_exec last_exec =
   128   map_node (fn (touched, header, perspective, entries, _, result) =>
   129     (touched, header, perspective, entries, last_exec, result));
   130 
   131 fun get_theory pos (Node {result, ...}) = Toplevel.end_theory pos (Lazy.force result);
   132 fun set_result result =
   133   map_node (fn (touched, header, perspective, entries, last_exec, _) =>
   134     (touched, header, perspective, entries, last_exec, result));
   135 
   136 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   137 fun default_node name = Graph.default_node (name, empty_node);
   138 fun update_node name f = default_node name #> Graph.map_node name f;
   139 
   140 
   141 (* node edits and associated executions *)
   142 
   143 datatype node_edit =
   144   Clear |
   145   Edits of (command_id option * command_id option) list |
   146   Header of node_header |
   147   Perspective of command_id list;
   148 
   149 type edit = string * node_edit;
   150 
   151 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   152 
   153 fun lookup_entry (Node {entries, ...}) id =
   154   (case Entries.lookup entries id of
   155     NONE => NONE
   156   | SOME (exec, _) => exec);
   157 
   158 fun the_entry (Node {entries, ...}) id =
   159   (case Entries.lookup entries id of
   160     NONE => err_undef "command entry" id
   161   | SOME (exec, _) => exec);
   162 
   163 fun the_default_entry node (SOME id) = (id, (the_default no_exec (the_entry node id)))
   164   | the_default_entry _ NONE = (no_id, no_exec);
   165 
   166 fun update_entry id exec =
   167   map_entries (Entries.update (id, exec));
   168 
   169 fun reset_entry id node =
   170   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   171 
   172 fun reset_after id entries =
   173   (case Entries.get_after entries id of
   174     NONE => entries
   175   | SOME next => Entries.update (next, NONE) entries);
   176 
   177 val edit_node = map_entries o fold
   178   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   179     | (id, NONE) => Entries.delete_after id #> reset_after id);
   180 
   181 
   182 (* version operations *)
   183 
   184 val empty_version = Version Graph.empty;
   185 
   186 fun nodes_of (Version nodes) = nodes;
   187 val node_of = get_node o nodes_of;
   188 
   189 local
   190 
   191 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   192 
   193 fun touch_node name nodes =
   194   fold (fn desc =>
   195       update_node desc
   196         (set_touched true #>
   197           desc <> name ? (map_entries (reset_after NONE) #> set_result no_result)))
   198     (Graph.all_succs nodes [name]) nodes;
   199 
   200 in
   201 
   202 fun edit_nodes (name, node_edit) (Version nodes) =
   203   Version
   204     (case node_edit of
   205       Clear =>
   206         nodes
   207         |> update_node name clear_node
   208         |> touch_node name
   209     | Edits edits =>
   210         nodes
   211         |> update_node name (edit_node edits)
   212         |> touch_node name
   213     | Header header =>
   214         let
   215           val imports = (case header of Exn.Res (_, {imports, ...}) => imports | _ => []);
   216           val header' =
   217             ((case header of Exn.Res (_, h) => Thy_Header.define_keywords h | _ => ()); header)
   218               handle exn as ERROR _ => Exn.Exn exn;
   219           val nodes1 = nodes
   220             |> default_node name
   221             |> fold default_node imports;
   222           val nodes2 = nodes1
   223             |> Graph.Keys.fold
   224                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   225           val (header'', nodes3) =
   226             (header', Graph.add_deps_acyclic (name, imports) nodes2)
   227               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   228         in Graph.map_node name (set_header header'') nodes3 end
   229         |> touch_node name
   230     | Perspective perspective =>
   231         update_node name (set_perspective perspective) nodes);
   232 
   233 end;
   234 
   235 fun put_node (name, node) (Version nodes) =
   236   Version (update_node name (K node) nodes);
   237 
   238 end;
   239 
   240 
   241 
   242 (** global state -- document structure and execution process **)
   243 
   244 abstype state = State of
   245  {versions: version Inttab.table,  (*version_id -> document content*)
   246   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> name * span*)
   247   execution: version_id * Future.group}  (*current execution process*)
   248 with
   249 
   250 fun make_state (versions, commands, execution) =
   251   State {versions = versions, commands = commands, execution = execution};
   252 
   253 fun map_state f (State {versions, commands, execution}) =
   254   make_state (f (versions, commands, execution));
   255 
   256 val init_state =
   257   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty, (no_id, Future.new_group NONE));
   258 
   259 
   260 (* document versions *)
   261 
   262 fun define_version (id: version_id) version =
   263   map_state (fn (versions, commands, execution) =>
   264     let val versions' = Inttab.update_new (id, version) versions
   265       handle Inttab.DUP dup => err_dup "document version" dup
   266     in (versions', commands, execution) end);
   267 
   268 fun the_version (State {versions, ...}) (id: version_id) =
   269   (case Inttab.lookup versions id of
   270     NONE => err_undef "document version" id
   271   | SOME version => version);
   272 
   273 fun delete_version (id: version_id) versions = Inttab.delete id versions
   274   handle Inttab.UNDEF _ => err_undef "document version" id;
   275 
   276 
   277 (* commands *)
   278 
   279 fun parse_command id text =
   280   Position.setmp_thread_data (Position.id_only id)
   281     (fn () =>
   282       let
   283         val toks = Thy_Syntax.parse_tokens (#1 (Outer_Syntax.get_syntax ())) (Position.id id) text;
   284         val _ = Output.status (Markup.markup_only Isabelle_Markup.parsed);
   285       in toks end) ();
   286 
   287 fun define_command (id: command_id) name text =
   288   map_state (fn (versions, commands, execution) =>
   289     let
   290       val span = Lazy.lazy (fn () => parse_command (print_id id) text);
   291       val commands' =
   292         Inttab.update_new (id, (name, span)) commands
   293           handle Inttab.DUP dup => err_dup "command" dup;
   294     in (versions, commands', execution) end);
   295 
   296 fun the_command (State {commands, ...}) (id: command_id) =
   297   (case Inttab.lookup commands id of
   298     NONE => err_undef "command" id
   299   | SOME command => command);
   300 
   301 
   302 (* document execution *)
   303 
   304 fun cancel_execution (State {execution, ...}) = Future.cancel_group (#2 execution);
   305 
   306 end;
   307 
   308 
   309 (* toplevel transactions *)
   310 
   311 local
   312 
   313 fun timing tr t =
   314   if Timing.is_relevant t then Toplevel.status tr (Isabelle_Markup.timing t) else ();
   315 
   316 fun proof_status tr st =
   317   (case try Toplevel.proof_of st of
   318     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   319   | NONE => ());
   320 
   321 fun print_state tr st =
   322   (Lazy.lazy o Toplevel.setmp_thread_position tr)
   323     (fn () => Toplevel.print_state false st);
   324 
   325 fun run int tr st =
   326   (case Toplevel.transition int tr st of
   327     SOME (st', NONE) => ([], SOME st')
   328   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages exn, NONE)
   329   | NONE => ([(serial (), ML_Compiler.exn_message Runtime.TERMINATE)], NONE));
   330 
   331 in
   332 
   333 fun run_command tr st =
   334   let
   335     val is_init = Toplevel.is_init tr;
   336     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   337 
   338     val _ = Multithreading.interrupted ();
   339     val _ = Toplevel.status tr Isabelle_Markup.forked;
   340     val start = Timing.start ();
   341     val (errs, result) = run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   342     val _ = timing tr (Timing.result start);
   343     val _ = Toplevel.status tr Isabelle_Markup.joined;
   344     val _ = List.app (Toplevel.error_msg tr) errs;
   345   in
   346     (case result of
   347       NONE =>
   348         let
   349           val _ = if null errs then Exn.interrupt () else ();
   350           val _ = Toplevel.status tr Isabelle_Markup.failed;
   351         in (st, no_print) end
   352     | SOME st' =>
   353         let
   354           val _ = Toplevel.status tr Isabelle_Markup.finished;
   355           val _ = proof_status tr st';
   356           val do_print =
   357             not is_init andalso
   358               (Toplevel.print_of tr orelse (is_proof andalso Toplevel.is_proof st'));
   359         in (st', if do_print then print_state tr st' else no_print) end)
   360   end;
   361 
   362 end;
   363 
   364 
   365 
   366 
   367 (** update **)
   368 
   369 (* perspective *)
   370 
   371 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   372   let
   373     val old_version = the_version state old_id;
   374     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   375     val new_version = edit_nodes (name, Perspective perspective) old_version;
   376   in define_version new_id new_version state end;
   377 
   378 
   379 (* edits *)
   380 
   381 local
   382 
   383 fun last_common state last_visible node0 node =
   384   let
   385     fun update_flags prev (visible, initial) =
   386       let
   387         val visible' = visible andalso prev <> last_visible;
   388         val initial' = initial andalso
   389           (case prev of
   390             NONE => true
   391           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   392       in (visible', initial') end;
   393     fun get_common ((prev, id), exec) (found, (_, flags)) =
   394       if found then NONE
   395       else
   396         let val found' =
   397           is_none exec orelse op <> (pairself (Option.map #1) (exec, lookup_entry node0 id));
   398         in SOME (found', (prev, update_flags prev flags)) end;
   399     val (found, (common, flags)) =
   400       iterate_entries get_common node (false, (NONE, (true, true)));
   401   in
   402     if found then (common, flags)
   403     else
   404       let val last = Entries.get_after (get_entries node) common
   405       in (last, update_flags last flags) end
   406   end;
   407 
   408 fun illegal_init () = error "Illegal theory header after end of theory";
   409 
   410 fun new_exec state bad_init command_id' (execs, command_exec, init) =
   411   if bad_init andalso is_none init then NONE
   412   else
   413     let
   414       val (name, span) = the_command state command_id' ||> Lazy.force;
   415       val (modify_init, init') =
   416         if Keyword.is_theory_begin name then
   417           (Toplevel.modify_init (the_default illegal_init init), NONE)
   418         else (I, init);
   419       val exec_id' = new_id ();
   420       val exec_id'_string = print_id exec_id';
   421       val tr =
   422         Position.setmp_thread_data (Position.id_only exec_id'_string)
   423           (fn () =>
   424             #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   425             |> modify_init
   426             |> Toplevel.put_id exec_id'_string);
   427       val exec' = snd (snd command_exec) |> Lazy.map (fn (st, _) => run_command (tr ()) st);
   428       val command_exec' = (command_id', (exec_id', exec'));
   429     in SOME (command_exec' :: execs, command_exec', init') end;
   430 
   431 fun make_required nodes =
   432   let
   433     val all_visible =
   434       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   435       |> Graph.all_preds nodes;
   436     val required =
   437       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   438         all_visible Symtab.empty;
   439   in Symtab.defined required end;
   440 
   441 fun check_theory nodes name =
   442   is_some (Thy_Info.lookup_theory name) orelse  (* FIXME more robust!? *)
   443   is_some (Exn.get_res (get_header (get_node nodes name)));
   444 
   445 fun init_theory deps node =
   446   let
   447     (* FIXME provide files via Scala layer, not master_dir *)
   448     val (master_dir, header) = Exn.release (get_header node);
   449     val parents =
   450       #imports header |> map (fn import =>
   451         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   452           SOME thy => thy
   453         | NONE =>
   454             get_theory (Position.file_only import)
   455               (snd (Future.join (the (AList.lookup (op =) deps import))))));
   456   in Thy_Load.begin_theory (Path.explode master_dir) header parents end;
   457 
   458 in
   459 
   460 fun update (old_id: version_id) (new_id: version_id) edits state =
   461   let
   462     val old_version = the_version state old_id;
   463     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   464     val new_version = fold edit_nodes edits old_version;
   465 
   466     val nodes = nodes_of new_version;
   467     val is_required = make_required nodes;
   468 
   469     val updated =
   470       nodes |> Graph.schedule
   471         (fn deps => fn (name, node) =>
   472           if not (is_touched node orelse is_required name)
   473           then Future.value (([], [], []), node)
   474           else
   475             let
   476               val node0 = node_of old_version name;
   477               fun init () = init_theory deps node;
   478               val bad_init =
   479                 not (check_theory nodes name andalso forall (check_theory nodes o #1) deps);
   480             in
   481               (singleton o Future.forks)
   482                 {name = "Document.update", group = NONE,
   483                   deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   484                 (fn () =>
   485                   let
   486                     val required = is_required name;
   487                     val last_visible = #2 (get_perspective node);
   488                     val (common, (visible, initial)) = last_common state last_visible node0 node;
   489                     val common_command_exec = the_default_entry node common;
   490 
   491                     val (execs, (command_id, (_, exec)), _) =
   492                       ([], common_command_exec, if initial then SOME init else NONE) |>
   493                       (visible orelse required) ?
   494                         iterate_entries_after common
   495                           (fn ((prev, id), _) => fn res =>
   496                             if not required andalso prev = last_visible then NONE
   497                             else new_exec state bad_init id res) node;
   498 
   499                     val no_execs =
   500                       iterate_entries_after common
   501                         (fn ((_, id0), exec0) => fn res =>
   502                           if is_none exec0 then NONE
   503                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   504                           else SOME (id0 :: res)) node0 [];
   505 
   506                     val last_exec = if command_id = no_id then NONE else SOME command_id;
   507                     val result =
   508                       if is_some (after_entry node last_exec) then no_result
   509                       else Lazy.map #1 exec;
   510 
   511                     val node' = node
   512                       |> fold reset_entry no_execs
   513                       |> fold (fn (id, exec) => update_entry id (SOME exec)) execs
   514                       |> set_last_exec last_exec
   515                       |> set_result result
   516                       |> set_touched false;
   517                   in ((no_execs, execs, [(name, node')]), node') end)
   518             end)
   519       |> Future.joins |> map #1;
   520 
   521     val command_execs =
   522       map (rpair NONE) (maps #1 updated) @
   523       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   524     val updated_nodes = maps #3 updated;
   525     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   526 
   527     val state' = state
   528       |> define_version new_id (fold put_node updated_nodes new_version);
   529   in ((command_execs, last_execs), state') end;
   530 
   531 end;
   532 
   533 
   534 (* execute *)
   535 
   536 fun execute version_id state =
   537   state |> map_state (fn (versions, commands, _) =>
   538     let
   539       val version = the_version state version_id;
   540 
   541       fun force_exec _ _ NONE = ()
   542         | force_exec node command_id (SOME (_, exec)) =
   543             let
   544               val (_, print) = Lazy.force exec;
   545               val _ =
   546                 if #1 (get_perspective node) command_id
   547                 then ignore (Lazy.future Future.default_params print)
   548                 else ();
   549             in () end;
   550 
   551       val group = Future.new_group NONE;
   552       val _ =
   553         nodes_of version |> Graph.schedule
   554           (fn deps => fn (name, node) =>
   555             (singleton o Future.forks)
   556               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   557                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   558               (iterate_entries (fn ((_, id), exec) => fn () =>
   559                 SOME (force_exec node id exec)) node));
   560 
   561     in (versions, commands, (version_id, group)) end);
   562 
   563 
   564 (* remove versions *)
   565 
   566 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   567   let
   568     val _ = member (op =) ids (#1 execution) andalso
   569       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   570 
   571     val versions' = fold delete_version ids versions;
   572     val commands' =
   573       (versions', Inttab.empty) |->
   574         Inttab.fold (fn (_, version) => nodes_of version |>
   575           Graph.fold (fn (_, (node, _)) => node |>
   576             iterate_entries (fn ((_, id), _) =>
   577               SOME o Inttab.insert (K true) (id, the_command state id))));
   578   in (versions', commands', execution) end);
   579 
   580 
   581 
   582 (** global state **)
   583 
   584 val global_state = Synchronized.var "Document" init_state;
   585 
   586 fun state () = Synchronized.value global_state;
   587 val change_state = Synchronized.change global_state;
   588 
   589 end;
   590