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