src/Pure/PIDE/document.ML
author wenzelm
Fri Apr 20 23:16:46 2012 +0200 (2012-04-20)
changeset 47633 e5c5e73f3e30
parent 47631 97d28302445c
child 48707 ba531af91148
permissions -rw-r--r--
improved interleaving of start_execution vs. cancel_execution of the next update;
     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 remove_versions: version_id list -> state -> state
    29   val discontinue_execution: state -> unit
    30   val cancel_execution: state -> unit
    31   val start_execution: state -> unit
    32   val timing: bool Unsynchronized.ref
    33   val update: version_id -> version_id -> edit list -> state ->
    34     (command_id * exec_id option) list * state
    35   val state: unit -> state
    36   val change_state: (state -> state) -> unit
    37 end;
    38 
    39 structure Document: DOCUMENT =
    40 struct
    41 
    42 (* unique identifiers *)
    43 
    44 type id = int;
    45 type version_id = id;
    46 type command_id = id;
    47 type exec_id = id;
    48 
    49 val no_id = 0;
    50 val new_id = Synchronized.counter ();
    51 
    52 val parse_id = Markup.parse_int;
    53 val print_id = Markup.print_int;
    54 
    55 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    56 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    57 
    58 
    59 
    60 (** document structure **)
    61 
    62 type node_header = (string * Thy_Header.header) Exn.result;
    63 type perspective = (command_id -> bool) * command_id option;
    64 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    65 
    66 type exec = (Toplevel.state * unit lazy) Command.memo;  (*eval/print process*)
    67 val no_exec = Command.memo_value (Toplevel.toplevel, Lazy.value ());
    68 
    69 abstype node = Node of
    70  {header: node_header,
    71   perspective: perspective,  (*visible commands, last*)
    72   entries: (exec_id * exec) option Entries.T,  (*command entries with excecutions*)
    73   result: exec option}  (*result of last execution*)
    74 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    75 with
    76 
    77 fun make_node (header, perspective, entries, result) =
    78   Node {header = header, perspective = perspective, entries = entries, result = result};
    79 
    80 fun map_node f (Node {header, perspective, entries, result}) =
    81   make_node (f (header, perspective, entries, result));
    82 
    83 fun make_perspective command_ids : perspective =
    84   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    85 
    86 val no_header = Exn.Exn (ERROR "Bad theory header");
    87 val no_perspective = make_perspective [];
    88 
    89 val empty_node = make_node (no_header, no_perspective, Entries.empty, NONE);
    90 val clear_node = map_node (fn (header, _, _, _) => (header, no_perspective, Entries.empty, NONE));
    91 
    92 
    93 (* basic components *)
    94 
    95 fun get_header (Node {header, ...}) = header;
    96 fun set_header header =
    97   map_node (fn (_, perspective, entries, result) => (header, perspective, entries, result));
    98 
    99 fun get_perspective (Node {perspective, ...}) = perspective;
   100 fun set_perspective ids =
   101   map_node (fn (header, _, entries, result) => (header, make_perspective ids, entries, result));
   102 
   103 val visible_command = #1 o get_perspective;
   104 val visible_last = #2 o get_perspective;
   105 val visible_node = is_some o visible_last
   106 
   107 fun map_entries f =
   108   map_node (fn (header, perspective, entries, result) => (header, perspective, f entries, result));
   109 fun get_entries (Node {entries, ...}) = entries;
   110 
   111 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   112 fun iterate_entries_after start f (Node {entries, ...}) =
   113   (case Entries.get_after entries start of
   114     NONE => I
   115   | SOME id => Entries.iterate (SOME id) f entries);
   116 
   117 fun get_result (Node {result, ...}) = result;
   118 fun set_result result =
   119   map_node (fn (header, perspective, entries, _) => (header, perspective, entries, result));
   120 
   121 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   122 fun default_node name = Graph.default_node (name, empty_node);
   123 fun update_node name f = default_node name #> Graph.map_node name f;
   124 
   125 
   126 (* node edits and associated executions *)
   127 
   128 datatype node_edit =
   129   Clear |
   130   Edits of (command_id option * command_id option) list |
   131   Header of node_header |
   132   Perspective of command_id list;
   133 
   134 type edit = string * node_edit;
   135 
   136 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   137 
   138 fun lookup_entry (Node {entries, ...}) id =
   139   (case Entries.lookup entries id of
   140     NONE => NONE
   141   | SOME (exec, _) => exec);
   142 
   143 fun the_entry (Node {entries, ...}) id =
   144   (case Entries.lookup entries id of
   145     NONE => err_undef "command entry" id
   146   | SOME (exec, _) => exec);
   147 
   148 fun the_default_entry node (SOME id) = (id, the_default (no_id, no_exec) (the_entry node id))
   149   | the_default_entry _ NONE = (no_id, (no_id, no_exec));
   150 
   151 fun update_entry id exec =
   152   map_entries (Entries.update (id, exec));
   153 
   154 fun reset_entry id node =
   155   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   156 
   157 fun reset_after id entries =
   158   (case Entries.get_after entries id of
   159     NONE => entries
   160   | SOME next => Entries.update (next, NONE) entries);
   161 
   162 val edit_node = map_entries o fold
   163   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   164     | (id, NONE) => Entries.delete_after id #> reset_after id);
   165 
   166 
   167 (* version operations *)
   168 
   169 val empty_version = Version Graph.empty;
   170 
   171 fun nodes_of (Version nodes) = nodes;
   172 val node_of = get_node o nodes_of;
   173 
   174 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   175 
   176 fun edit_nodes (name, node_edit) (Version nodes) =
   177   Version
   178     (case node_edit of
   179       Clear => update_node name clear_node nodes
   180     | Edits edits => update_node name (edit_node edits) nodes
   181     | Header header =>
   182         let
   183           val imports = (case header of Exn.Res (_, {imports, ...}) => imports | _ => []);
   184           val header' =
   185             ((case header of Exn.Res (_, h) => Thy_Header.define_keywords h | _ => ()); header)
   186               handle exn as ERROR _ => Exn.Exn exn;
   187           val nodes1 = nodes
   188             |> default_node name
   189             |> fold default_node imports;
   190           val nodes2 = nodes1
   191             |> Graph.Keys.fold
   192                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   193           val (header'', nodes3) =
   194             (header', Graph.add_deps_acyclic (name, imports) nodes2)
   195               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   196         in Graph.map_node name (set_header header'') nodes3 end
   197     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   198 
   199 fun put_node (name, node) (Version nodes) =
   200   Version (update_node name (K node) nodes);
   201 
   202 end;
   203 
   204 
   205 
   206 (** main state -- document structure and execution process **)
   207 
   208 abstype state = State of
   209  {versions: version Inttab.table,  (*version_id -> document content*)
   210   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> named span*)
   211   execution: version_id * Future.group * bool Unsynchronized.ref}  (*current execution process*)
   212 with
   213 
   214 fun make_state (versions, commands, execution) =
   215   State {versions = versions, commands = commands, execution = execution};
   216 
   217 fun map_state f (State {versions, commands, execution}) =
   218   make_state (f (versions, commands, execution));
   219 
   220 val init_state =
   221   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty,
   222     (no_id, Future.new_group NONE, Unsynchronized.ref false));
   223 
   224 fun execution_of (State {execution, ...}) = execution;
   225 
   226 
   227 (* document versions *)
   228 
   229 fun define_version (id: version_id) version =
   230   map_state (fn (versions, commands, _) =>
   231     let
   232       val versions' = Inttab.update_new (id, version) versions
   233         handle Inttab.DUP dup => err_dup "document version" dup;
   234       val execution' = (id, Future.new_group NONE, Unsynchronized.ref true);
   235     in (versions', commands, execution') end);
   236 
   237 fun the_version (State {versions, ...}) (id: version_id) =
   238   (case Inttab.lookup versions id of
   239     NONE => err_undef "document version" id
   240   | SOME version => version);
   241 
   242 fun delete_version (id: version_id) versions = Inttab.delete id versions
   243   handle Inttab.UNDEF _ => err_undef "document version" id;
   244 
   245 
   246 (* commands *)
   247 
   248 fun define_command (id: command_id) name text =
   249   map_state (fn (versions, commands, execution) =>
   250     let
   251       val id_string = print_id id;
   252       val span = Lazy.lazy (fn () =>
   253         Position.setmp_thread_data (Position.id_only id_string)
   254           (fn () =>
   255             Thy_Syntax.parse_tokens
   256               (#1 (Outer_Syntax.get_syntax ())) (Position.id id_string) text) ());
   257       val _ =
   258         Position.setmp_thread_data (Position.id_only id_string)
   259           (fn () => Output.status (Markup.markup_only Isabelle_Markup.accepted)) ();
   260       val commands' =
   261         Inttab.update_new (id, (name, span)) commands
   262           handle Inttab.DUP dup => err_dup "command" dup;
   263     in (versions, commands', execution) end);
   264 
   265 fun the_command (State {commands, ...}) (id: command_id) =
   266   (case Inttab.lookup commands id of
   267     NONE => err_undef "command" id
   268   | SOME command => command);
   269 
   270 end;
   271 
   272 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   273   let
   274     val _ = member (op =) ids (#1 execution) andalso
   275       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   276 
   277     val versions' = fold delete_version ids versions;
   278     val commands' =
   279       (versions', Inttab.empty) |->
   280         Inttab.fold (fn (_, version) => nodes_of version |>
   281           Graph.fold (fn (_, (node, _)) => node |>
   282             iterate_entries (fn ((_, id), _) =>
   283               SOME o Inttab.insert (K true) (id, the_command state id))));
   284   in (versions', commands', execution) end);
   285 
   286 
   287 
   288 (** document execution **)
   289 
   290 val discontinue_execution = execution_of #> (fn (_, _, running) => running := false);
   291 
   292 val cancel_execution = execution_of #> (fn (_, group, _) => Future.cancel_group group);
   293 
   294 fun terminate_execution state =
   295   let
   296     val (_, group, _) = execution_of state;
   297     val _ = Future.cancel_group group;
   298   in Future.join_tasks (Future.group_tasks group) end;
   299 
   300 fun start_execution state =
   301   let
   302     fun finished_theory node =
   303       (case Exn.capture (Command.memo_result o the) (get_result node) of
   304         Exn.Res (st, _) => can (Toplevel.end_theory Position.none) st
   305       | _ => false);
   306 
   307     fun run node command_id exec =
   308       let
   309         val (_, print) = Command.memo_eval exec;
   310         val _ =
   311           if visible_command node command_id
   312           then ignore (Lazy.future Future.default_params print)
   313           else ();
   314       in () end;
   315 
   316     val (version_id, group, running) = execution_of state;
   317 
   318     val _ =
   319       (singleton o Future.forks)
   320         {name = "execution", group = SOME group, deps = [], pri = ~2, interrupts = true}
   321         (fn () =>
   322          (OS.Process.sleep (seconds 0.02);
   323           nodes_of (the_version state version_id) |> Graph.schedule
   324             (fn deps => fn (name, node) =>
   325               if not (visible_node node) andalso finished_theory node then
   326                 Future.value ()
   327               else
   328                 (singleton o Future.forks)
   329                   {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   330                     deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   331                   (fn () =>
   332                     iterate_entries (fn ((_, id), opt_exec) => fn () =>
   333                       (case opt_exec of
   334                         SOME (_, exec) => if ! running then SOME (run node id exec) else NONE
   335                       | NONE => NONE)) node ()))));
   336   in () end;
   337 
   338 
   339 
   340 (** document update **)
   341 
   342 val timing = Unsynchronized.ref false;
   343 fun timeit msg e = cond_timeit (! timing) msg e;
   344 
   345 local
   346 
   347 fun stable_finished_theory node =
   348   is_some (Exn.get_res (Exn.capture (fn () =>
   349     fst (Command.memo_result (the (get_result node)))
   350     |> Toplevel.end_theory Position.none
   351     |> Global_Theory.join_proofs) ()));
   352 
   353 fun stable_command exec =
   354   (case Exn.capture Command.memo_result exec of
   355     Exn.Exn exn => not (Exn.is_interrupt exn)
   356   | Exn.Res (st, _) =>
   357       (case try Toplevel.theory_of st of
   358         NONE => true
   359       | SOME thy => is_some (Exn.get_res (Exn.capture Global_Theory.join_recent_proofs thy))));
   360 
   361 fun make_required nodes =
   362   let
   363     val all_visible =
   364       Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   365       |> Graph.all_preds nodes
   366       |> map (rpair ()) |> Symtab.make;
   367 
   368     val required =
   369       Symtab.fold (fn (a, ()) =>
   370         exists (Symtab.defined all_visible) (Graph.immediate_succs nodes a) ?
   371           Symtab.update (a, ())) all_visible Symtab.empty;
   372   in Symtab.defined required end;
   373 
   374 fun init_theory imports node =
   375   let
   376     (* FIXME provide files via Scala layer, not master_dir *)
   377     val (dir, header) = Exn.release (get_header node);
   378     val master_dir =
   379       (case Url.explode dir of
   380         Url.File path => path
   381       | _ => Path.current);
   382     val parents =
   383       #imports header |> map (fn import =>
   384         (case Thy_Info.lookup_theory import of
   385           SOME thy => thy
   386         | NONE =>
   387             Toplevel.end_theory (Position.file_only import)
   388               (fst
   389                 (Command.memo_result
   390                   (the_default no_exec
   391                     (get_result (snd (the (AList.lookup (op =) imports import)))))))));
   392   in Thy_Load.begin_theory master_dir header parents end;
   393 
   394 fun check_theory full name node =
   395   is_some (Thy_Info.lookup_theory name) orelse
   396   is_some (Exn.get_res (get_header node)) andalso (not full orelse is_some (get_result node));
   397 
   398 fun last_common state last_visible node0 node =
   399   let
   400     fun update_flags prev (visible, initial) =
   401       let
   402         val visible' = visible andalso prev <> last_visible;
   403         val initial' = initial andalso
   404           (case prev of
   405             NONE => true
   406           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   407       in (visible', initial') end;
   408     fun get_common ((prev, id), opt_exec) (same, (_, flags)) =
   409       if same then
   410         let
   411           val flags' = update_flags prev flags;
   412           val same' =
   413             (case opt_exec of
   414               NONE => false
   415             | SOME (exec_id, exec) =>
   416                 (case lookup_entry node0 id of
   417                   NONE => false
   418                 | SOME (exec_id0, _) => exec_id = exec_id0 andalso stable_command exec));
   419         in SOME (same', (prev, flags')) end
   420       else NONE;
   421     val (same, (common, flags)) =
   422       iterate_entries get_common node (true, (NONE, (true, true)));
   423   in
   424     if same then
   425       let val last = Entries.get_after (get_entries node) common
   426       in (last, update_flags last flags) end
   427     else (common, flags)
   428   end;
   429 
   430 fun illegal_init () = error "Illegal theory header after end of theory";
   431 
   432 fun new_exec state proper_init command_id' (execs, command_exec, init) =
   433   if not proper_init andalso is_none init then NONE
   434   else
   435     let
   436       val (name, span) = the_command state command_id' ||> Lazy.force;
   437       val (modify_init, init') =
   438         if Keyword.is_theory_begin name then
   439           (Toplevel.modify_init (the_default illegal_init init), NONE)
   440         else (I, init);
   441       val exec_id' = new_id ();
   442       val exec_id'_string = print_id exec_id';
   443       val tr =
   444         Position.setmp_thread_data (Position.id_only exec_id'_string)
   445           (fn () =>
   446             #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   447             |> modify_init
   448             |> Toplevel.put_id exec_id'_string);
   449       val exec' =
   450         Command.memo (fn () =>
   451           Command.run_command (tr ()) (fst (Command.memo_result (snd (snd command_exec)))));
   452       val command_exec' = (command_id', (exec_id', exec'));
   453     in SOME (command_exec' :: execs, command_exec', init') end;
   454 
   455 in
   456 
   457 fun update (old_id: version_id) (new_id: version_id) edits state =
   458   let
   459     val old_version = the_version state old_id;
   460     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   461     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   462 
   463     val nodes = nodes_of new_version;
   464     val is_required = make_required nodes;
   465 
   466     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   467     val updated = timeit "Document.update" (fn () =>
   468       nodes |> Graph.schedule
   469         (fn deps => fn (name, node) =>
   470           (singleton o Future.forks)
   471             {name = "Document.update", group = NONE,
   472               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   473             (fn () =>
   474               let
   475                 val imports = map (apsnd Future.join) deps;
   476                 val updated_imports = exists (is_some o #3 o #1 o #2) imports;
   477                 val required = is_required name;
   478               in
   479                 if updated_imports orelse AList.defined (op =) edits name orelse
   480                   not (stable_finished_theory node)
   481                 then
   482                   let
   483                     val node0 = node_of old_version name;
   484                     fun init () = init_theory imports node;
   485                     val proper_init =
   486                       check_theory false name node andalso
   487                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   488 
   489                     val last_visible = visible_last node;
   490                     val (common, (visible, initial)) =
   491                       if updated_imports then (NONE, (true, true))
   492                       else last_common state last_visible node0 node;
   493                     val common_command_exec = the_default_entry node common;
   494 
   495                     val (new_execs, (command_id', (_, exec')), _) =
   496                       ([], common_command_exec, if initial then SOME init else NONE) |>
   497                       (visible orelse required) ?
   498                         iterate_entries_after common
   499                           (fn ((prev, id), _) => fn res =>
   500                             if not required andalso prev = last_visible then NONE
   501                             else new_exec state proper_init id res) node;
   502 
   503                     val no_execs =
   504                       iterate_entries_after common
   505                         (fn ((_, id0), exec0) => fn res =>
   506                           if is_none exec0 then NONE
   507                           else if exists (fn (_, (id, _)) => id0 = id) new_execs then SOME res
   508                           else SOME (id0 :: res)) node0 [];
   509 
   510                     val last_exec = if command_id' = no_id then NONE else SOME command_id';
   511                     val result =
   512                       if is_some (after_entry node last_exec) then NONE
   513                       else SOME exec';
   514 
   515                     val node' = node
   516                       |> fold reset_entry no_execs
   517                       |> fold (fn (id, exec) => update_entry id (SOME exec)) new_execs
   518                       |> set_result result;
   519                     val updated_node =
   520                       if null no_execs andalso null new_execs then NONE
   521                       else SOME (name, node');
   522                   in ((no_execs, new_execs, updated_node), node') end
   523                 else (([], [], NONE), node)
   524               end))
   525       |> Future.joins |> map #1);
   526 
   527     val command_execs =
   528       map (rpair NONE) (maps #1 updated) @
   529       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   530     val updated_nodes = map_filter #3 updated;
   531 
   532     val state' = state
   533       |> define_version new_id (fold put_node updated_nodes new_version);
   534   in (command_execs, state') end;
   535 
   536 end;
   537 
   538 
   539 
   540 (** global state **)
   541 
   542 val global_state = Synchronized.var "Document" init_state;
   543 
   544 fun state () = Synchronized.value global_state;
   545 val change_state = Synchronized.change global_state;
   546 
   547 end;
   548