src/Pure/PIDE/document.ML
author wenzelm
Mon, 15 Aug 2011 21:05:30 +0200
changeset 45072 6429ab1b6883
parent 45071 ce0112e26b3b
child 45073 44c4ae5c5ce2
permissions -rw-r--r--
parellel scheduling of node edits and execution;
     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, associated with asynchronous execution process.
     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 * string list * (string * bool) list) Exn.result
    19   datatype node_edit =
    20     Clear |
    21     Edits of (command_id option * command_id option) list |
    22     Header of node_header
    23   type edit = string * node_edit
    24   type state
    25   val init_state: state
    26   val join_commands: state -> unit
    27   val cancel_execution: state -> unit -> unit
    28   val define_command: command_id -> string -> state -> state
    29   val edit: version_id -> version_id -> edit list -> state -> (command_id * exec_id) list * state
    30   val execute: version_id -> state -> state
    31   val state: unit -> state
    32   val change_state: (state -> state) -> unit
    33 end;
    34 
    35 structure Document: DOCUMENT =
    36 struct
    37 
    38 (* unique identifiers *)
    39 
    40 type id = int;
    41 type version_id = id;
    42 type command_id = id;
    43 type exec_id = id;
    44 
    45 val no_id = 0;
    46 val new_id = Synchronized.counter ();
    47 
    48 val parse_id = Markup.parse_int;
    49 val print_id = Markup.print_int;
    50 
    51 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    52 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    53 
    54 
    55 
    56 (** document structure **)
    57 
    58 type node_header = (string * string list * (string * bool) list) Exn.result;
    59 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    60 
    61 abstype node = Node of
    62  {header: node_header,
    63   entries: exec_id option Entries.T,  (*command entries with excecutions*)
    64   result: Toplevel.state lazy}
    65 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    66 with
    67 
    68 fun make_node (header, entries, result) =
    69   Node {header = header, entries = entries, result = result};
    70 
    71 fun map_node f (Node {header, entries, result}) =
    72   make_node (f (header, entries, result));
    73 
    74 fun get_header (Node {header, ...}) = header;
    75 fun set_header header = map_node (fn (_, entries, result) => (header, entries, result));
    76 
    77 fun map_entries f (Node {header, entries, result}) = make_node (header, f entries, result);
    78 fun fold_entries start f (Node {entries, ...}) = Entries.fold start f entries;
    79 fun first_entry start P (Node {entries, ...}) = Entries.get_first start P entries;
    80 
    81 fun get_theory pos (Node {result, ...}) = Toplevel.end_theory pos (Lazy.get_finished result);
    82 fun set_result result = map_node (fn (header, entries, _) => (header, entries, result));
    83 
    84 val empty_exec = Lazy.value Toplevel.toplevel;
    85 val empty_node = make_node (Exn.Exn (ERROR "Bad theory header"), Entries.empty, empty_exec);
    86 val clear_node = map_node (fn (header, _, _) => (header, Entries.empty, empty_exec));
    87 
    88 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
    89 fun remove_node name nodes = Graph.del_node name nodes handle Graph.UNDEF _ => nodes;
    90 fun update_node name f = Graph.default_node (name, empty_node) #> Graph.map_node name f;
    91 
    92 
    93 (* node edits and associated executions *)
    94 
    95 datatype node_edit =
    96   Clear |
    97   Edits of (command_id option * command_id option) list |
    98   Header of node_header;
    99 
   100 type edit = string * node_edit;
   101 
   102 fun the_entry (Node {entries, ...}) id =
   103   (case Entries.lookup entries id of
   104     NONE => err_undef "command entry" id
   105   | SOME entry => entry);
   106 
   107 fun update_entry (id, exec_id) =
   108   map_entries (Entries.update (id, SOME exec_id));
   109 
   110 fun reset_after id entries =
   111   (case Entries.get_after entries id of
   112     NONE => entries
   113   | SOME next => Entries.update (next, NONE) entries);
   114 
   115 val edit_node = map_entries o fold
   116   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   117     | (id, NONE) => Entries.delete_after id #> reset_after id);
   118 
   119 
   120 (* version operations *)
   121 
   122 val empty_version = Version Graph.empty;
   123 
   124 fun nodes_of (Version nodes) = nodes;
   125 val node_of = get_node o nodes_of;
   126 
   127 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   128 
   129 fun edit_nodes (name, node_edit) (Version nodes) =
   130   Version
   131     (case node_edit of
   132       Clear => update_node name clear_node nodes
   133     | Edits edits => update_node name (edit_node edits) nodes
   134     | Header header =>
   135         let
   136           val node = get_node nodes name;
   137           val nodes' = Graph.new_node (name, node) (remove_node name nodes);
   138           val parents =
   139             (case header of Exn.Res (_, parents, _) => parents | _ => [])
   140             |> filter (can (Graph.get_node nodes'));
   141           val (header', nodes'') =
   142             (header, Graph.add_deps_acyclic (name, parents) nodes')
   143               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes');
   144         in Graph.map_node name (set_header header') nodes'' end);
   145 
   146 fun put_node (name, node) (Version nodes) =
   147   Version (nodes
   148     |> Graph.default_node (name, empty_node)
   149     |> Graph.map_node name (K node));
   150 
   151 end;
   152 
   153 
   154 
   155 (** global state -- document structure and execution process **)
   156 
   157 abstype state = State of
   158  {versions: version Inttab.table,  (*version_id -> document content*)
   159   commands: Toplevel.transition future Inttab.table,  (*command_id -> transition (future parsing)*)
   160   execs: Toplevel.state lazy Inttab.table,  (*exec_id -> execution process*)
   161   execution: unit future list}  (*global execution process*)
   162 with
   163 
   164 fun make_state (versions, commands, execs, execution) =
   165   State {versions = versions, commands = commands, execs = execs, execution = execution};
   166 
   167 fun map_state f (State {versions, commands, execs, execution}) =
   168   make_state (f (versions, commands, execs, execution));
   169 
   170 val init_state =
   171   make_state (Inttab.make [(no_id, empty_version)],
   172     Inttab.make [(no_id, Future.value Toplevel.empty)],
   173     Inttab.make [(no_id, empty_exec)],
   174     []);
   175 
   176 
   177 (* document versions *)
   178 
   179 fun define_version (id: version_id) version =
   180   map_state (fn (versions, commands, execs, execution) =>
   181     let val versions' = Inttab.update_new (id, version) versions
   182       handle Inttab.DUP dup => err_dup "document version" dup
   183     in (versions', commands, execs, execution) end);
   184 
   185 fun the_version (State {versions, ...}) (id: version_id) =
   186   (case Inttab.lookup versions id of
   187     NONE => err_undef "document version" id
   188   | SOME version => version);
   189 
   190 
   191 (* commands *)
   192 
   193 fun define_command (id: command_id) text =
   194   map_state (fn (versions, commands, execs, execution) =>
   195     let
   196       val id_string = print_id id;
   197       val tr = Future.fork_pri 2 (fn () =>
   198         Position.setmp_thread_data (Position.id_only id_string)
   199           (fn () => Outer_Syntax.prepare_command (Position.id id_string) text) ());
   200       val commands' =
   201         Inttab.update_new (id, tr) commands
   202           handle Inttab.DUP dup => err_dup "command" dup;
   203     in (versions, commands', execs, execution) end);
   204 
   205 fun the_command (State {commands, ...}) (id: command_id) =
   206   (case Inttab.lookup commands id of
   207     NONE => err_undef "command" id
   208   | SOME tr => tr);
   209 
   210 fun join_commands (State {commands, ...}) =
   211   Inttab.fold (fn (_, tr) => fn () => ignore (Future.join_result tr)) commands ();
   212 
   213 
   214 (* command executions *)
   215 
   216 fun define_exec (exec_id, exec) =
   217   map_state (fn (versions, commands, execs, execution) =>
   218     let val execs' = Inttab.update_new (exec_id, exec) execs
   219       handle Inttab.DUP dup => err_dup "command execution" dup
   220     in (versions, commands, execs', execution) end);
   221 
   222 fun the_exec (State {execs, ...}) exec_id =
   223   (case Inttab.lookup execs exec_id of
   224     NONE => err_undef "command execution" exec_id
   225   | SOME exec => exec);
   226 
   227 
   228 (* document execution *)
   229 
   230 fun cancel_execution (State {execution, ...}) =
   231   (List.app Future.cancel execution;
   232     fn () => ignore (Future.join_results execution));
   233 
   234 end;
   235 
   236 
   237 
   238 (* toplevel transactions *)
   239 
   240 local
   241 
   242 fun timing tr t = Toplevel.status tr (Markup.timing t);
   243 
   244 fun proof_status tr st =
   245   (case try Toplevel.proof_of st of
   246     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   247   | NONE => ());
   248 
   249 fun async_state tr st =
   250   ignore
   251     (singleton
   252       (Future.forks {name = "Document.async_state",
   253         group = SOME (Task_Queue.new_group NONE), deps = [], pri = 0, interrupts = true})
   254       (fn () =>
   255         Toplevel.setmp_thread_position tr
   256           (fn () => Toplevel.print_state false st) ()));
   257 
   258 fun run int tr st =
   259   (case Toplevel.transition int tr st of
   260     SOME (st', NONE) => ([], SOME st')
   261   | SOME (_, SOME exn_info) =>
   262       (case ML_Compiler.exn_messages (Runtime.EXCURSION_FAIL exn_info) of
   263         [] => Exn.interrupt ()
   264       | errs => (errs, NONE))
   265   | NONE => ([ML_Compiler.exn_message Runtime.TERMINATE], NONE));
   266 
   267 in
   268 
   269 fun run_command tr st =
   270   let
   271     val is_init = Toplevel.is_init tr;
   272     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   273     val do_print = not is_init andalso (Toplevel.print_of tr orelse is_proof);
   274 
   275     val start = Timing.start ();
   276     val (errs, result) =
   277       if Toplevel.is_toplevel st andalso not is_init then ([], SOME st)
   278       else run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   279     val _ = timing tr (Timing.result start);
   280     val _ = List.app (Toplevel.error_msg tr) errs;
   281   in
   282     (case result of
   283       NONE => (Toplevel.status tr Markup.failed; st)
   284     | SOME st' =>
   285        (Toplevel.status tr Markup.finished;
   286         proof_status tr st';
   287         if do_print then async_state tr st' else ();
   288         st'))
   289   end;
   290 
   291 end;
   292 
   293 
   294 
   295 
   296 (** editing **)
   297 
   298 (* edit *)
   299 
   300 local
   301 
   302 fun is_changed node' ((_, id), exec) =
   303   (case try (the_entry node') id of
   304     NONE => true
   305   | SOME exec' => exec' <> exec);
   306 
   307 fun new_exec (command_id, command) (assigns, execs, exec) =
   308   let
   309     val exec_id' = new_id ();
   310     val exec' =
   311       Lazy.lazy (fn () =>
   312         let
   313           val tr = Toplevel.put_id (print_id exec_id') (Future.get_finished command);
   314           val st = Lazy.get_finished exec;
   315         in run_command tr st end);
   316   in ((command_id, exec_id') :: assigns, (exec_id', exec') :: execs, exec') end;
   317 
   318 in
   319 
   320 fun edit (old_id: version_id) (new_id: version_id) edits state =
   321   let
   322     val old_version = the_version state old_id;
   323     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   324     val new_version = fold edit_nodes edits old_version;
   325 
   326     val updates =
   327       nodes_of new_version |> Graph.schedule
   328         (fn deps => fn (name, node) =>
   329           (case first_entry NONE (is_changed (node_of old_version name)) node of
   330             NONE => Future.value (([], [], []), node)
   331           | SOME ((prev, id), _) =>
   332               let
   333                 fun init () =
   334                   let
   335                     val (thy_name, imports, uses) = Exn.release (get_header node);
   336                     (* FIXME provide files via Scala layer *)
   337                     val dir = Path.dir (Path.explode name);
   338                     val files = map (apfst Path.explode) uses;
   339 
   340                     val parents =
   341                       imports |> map (fn import =>
   342                         (case AList.lookup (op =) deps import of
   343                           SOME parent_future =>
   344                             get_theory (Position.file_only (import ^ ".thy"))
   345                               (#2 (Future.join parent_future))
   346                         | NONE => Thy_Info.get_theory (Thy_Info.base_name import)));
   347                   in Thy_Load.begin_theory dir thy_name imports files parents end
   348                 fun get_command id =
   349                   (id, the_command state id |> Future.map (Toplevel.modify_init init));
   350               in
   351                 singleton
   352                   (Future.forks {name = "Document.edit", group = NONE,
   353                     deps = map (Future.task_of o #2) deps, pri = 2, interrupts = false})
   354                   (fn () =>
   355                     let
   356                       val prev_exec =
   357                         (case prev of
   358                           NONE => no_id
   359                         | SOME prev_id => the_default no_id (the_entry node prev_id));
   360                       val (assigns, execs, result) =
   361                         fold_entries (SOME id) (new_exec o get_command o #2 o #1)
   362                           node ([], [], the_exec state prev_exec);
   363                       val node' = node
   364                         |> fold update_entry assigns
   365                         |> set_result result;
   366                     in ((assigns, execs, [(name, node')]), node') end)
   367               end))
   368       |> Future.join_results |> Exn.release_all |> map #1;
   369 
   370     val state' = state
   371       |> fold (fold define_exec o #2) updates
   372       |> define_version new_id (fold (fold put_node o #3) updates new_version);
   373 
   374   in (maps #1 (rev updates), state') end;
   375 
   376 end;
   377 
   378 
   379 (* execute *)
   380 
   381 fun execute version_id state =
   382   state |> map_state (fn (versions, commands, execs, _) =>
   383     let
   384       val version = the_version state version_id;
   385 
   386       fun force_exec NONE = ()
   387         | force_exec (SOME exec_id) = ignore (Lazy.force (the_exec state exec_id));
   388 
   389       val execution' =
   390         nodes_of version |> Graph.schedule
   391           (fn deps => fn (name, node) =>
   392             singleton
   393               (Future.forks
   394                 {name = "theory:" ^ name, group = NONE,
   395                   deps = map (Future.task_of o #2) deps,
   396                   pri = 1, interrupts = true})
   397               (fold_entries NONE (fn (_, exec) => fn () => force_exec exec) node));
   398 
   399     in (versions, commands, execs, execution') end);
   400 
   401 
   402 
   403 (** global state **)
   404 
   405 val global_state = Synchronized.var "Document" init_state;
   406 
   407 fun state () = Synchronized.value global_state;
   408 val change_state = Synchronized.change global_state;
   409 
   410 end;
   411