src/Pure/PIDE/document.ML
author wenzelm
Fri Mar 13 11:47:42 2015 +0100 (2015-03-13)
changeset 59687 3baf9b3a24c7
parent 59685 c043306d2598
child 59689 7968c57ea240
permissions -rw-r--r--
tuned;
     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   val timing: bool Unsynchronized.ref
    11   type node_header = string * Thy_Header.header * string list
    12   type overlay = Document_ID.command * (string * string list)
    13   datatype node_edit =
    14     Edits of (Document_ID.command option * Document_ID.command option) list |
    15     Deps of node_header |
    16     Perspective of bool * Document_ID.command list * overlay list
    17   type edit = string * node_edit
    18   type state
    19   val init_state: state
    20   val define_blob: string -> string -> state -> state
    21   type blob_digest = (string * string option) Exn.result
    22   val define_command: Document_ID.command -> string -> blob_digest list -> int ->
    23     ((int * int) * string) list -> state -> state
    24   val remove_versions: Document_ID.version list -> state -> state
    25   val start_execution: state -> state
    26   val update: Document_ID.version -> Document_ID.version -> edit list -> state ->
    27     Document_ID.exec list * (Document_ID.command * Document_ID.exec list) list * state
    28   val state: unit -> state
    29   val change_state: (state -> state) -> unit
    30 end;
    31 
    32 structure Document: DOCUMENT =
    33 struct
    34 
    35 val timing = Unsynchronized.ref false;
    36 fun timeit msg e = cond_timeit (! timing) msg e;
    37 
    38 
    39 
    40 (** document structure **)
    41 
    42 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ Document_ID.print id);
    43 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ Document_ID.print id);
    44 
    45 type node_header = string * Thy_Header.header * string list;
    46 
    47 type perspective =
    48  {required: bool,  (*required node*)
    49   visible: Inttab.set,  (*visible commands*)
    50   visible_last: Document_ID.command option,  (*last visible command*)
    51   overlays: (string * string list) list Inttab.table};  (*command id -> print functions with args*)
    52 
    53 structure Entries = Linear_Set(type key = Document_ID.command val ord = int_ord);
    54 
    55 abstype node = Node of
    56  {header: node_header,  (*master directory, theory header, errors*)
    57   keywords: Keyword.keywords option,  (*outer syntax keywords*)
    58   perspective: perspective,  (*command perspective*)
    59   entries: Command.exec option Entries.T,  (*command entries with excecutions*)
    60   result: Command.eval option}  (*result of last execution*)
    61 and version = Version of node String_Graph.T  (*development graph wrt. static imports*)
    62 with
    63 
    64 fun make_node (header, keywords, perspective, entries, result) =
    65   Node {header = header, keywords = keywords, perspective = perspective,
    66     entries = entries, result = result};
    67 
    68 fun map_node f (Node {header, keywords, perspective, entries, result}) =
    69   make_node (f (header, keywords, perspective, entries, result));
    70 
    71 fun make_perspective (required, command_ids, overlays) : perspective =
    72  {required = required,
    73   visible = Inttab.make_set command_ids,
    74   visible_last = try List.last command_ids,
    75   overlays = Inttab.make_list overlays};
    76 
    77 val no_header: node_header = ("", Thy_Header.make ("", Position.none) [] [], []);
    78 val no_perspective = make_perspective (false, [], []);
    79 
    80 val empty_node = make_node (no_header, NONE, no_perspective, Entries.empty, NONE);
    81 
    82 fun is_no_perspective ({required, visible, visible_last, overlays}: perspective) =
    83   not required andalso
    84   Inttab.is_empty visible andalso
    85   is_none visible_last andalso
    86   Inttab.is_empty overlays;
    87 
    88 fun is_empty_node (Node {header, keywords, perspective, entries, result}) =
    89   header = no_header andalso
    90   is_none keywords andalso
    91   is_no_perspective perspective andalso
    92   Entries.is_empty entries andalso
    93   is_none result;
    94 
    95 
    96 (* basic components *)
    97 
    98 fun master_directory (Node {header = (master, _, _), ...}) =
    99   (case try Url.explode master of
   100     SOME (Url.File path) => path
   101   | _ => Path.current);
   102 
   103 fun set_header header =
   104   map_node (fn (_, keywords, perspective, entries, result) =>
   105     (header, keywords, perspective, entries, result));
   106 
   107 fun get_header_raw (Node {header, ...}) = header;
   108 
   109 fun get_header (Node {header = (master, header, errors), ...}) =
   110   if null errors then (master, header)
   111   else error (cat_lines errors);
   112 
   113 fun set_keywords keywords =
   114   map_node (fn (header, _, perspective, entries, result) =>
   115     (header, keywords, perspective, entries, result));
   116 
   117 fun get_keywords (Node {keywords, ...}) = keywords;
   118 
   119 fun read_header node span =
   120   let
   121     val {name = (name, _), imports, keywords} = #2 (get_header node);
   122     val {name = (_, pos), imports = imports', ...} = Thy_Header.read_tokens span;
   123   in Thy_Header.make (name, pos) (map #1 imports ~~ map #2 imports') keywords end;
   124 
   125 fun get_perspective (Node {perspective, ...}) = perspective;
   126 
   127 fun set_perspective args =
   128   map_node (fn (header, keywords, _, entries, result) =>
   129     (header, keywords, make_perspective args, entries, result));
   130 
   131 val required_node = #required o get_perspective;
   132 val visible_command = Inttab.defined o #visible o get_perspective;
   133 val visible_last = #visible_last o get_perspective;
   134 val visible_node = is_some o visible_last
   135 val overlays = Inttab.lookup_list o #overlays o get_perspective;
   136 
   137 fun map_entries f =
   138   map_node (fn (header, keywords, perspective, entries, result) =>
   139     (header, keywords, perspective, f entries, result));
   140 
   141 fun get_entries (Node {entries, ...}) = entries;
   142 
   143 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   144 fun iterate_entries_after start f (Node {entries, ...}) =
   145   (case Entries.get_after entries start of
   146     NONE => I
   147   | SOME id => Entries.iterate (SOME id) f entries);
   148 
   149 fun get_result (Node {result, ...}) = result;
   150 
   151 fun set_result result =
   152   map_node (fn (header, keywords, perspective, entries, _) =>
   153     (header, keywords, perspective, entries, result));
   154 
   155 fun changed_result node node' =
   156   (case (get_result node, get_result node') of
   157     (SOME eval, SOME eval') => not (Command.eval_eq (eval, eval'))
   158   | (NONE, NONE) => false
   159   | _ => true);
   160 
   161 fun pending_result node =
   162   (case get_result node of
   163     SOME eval => not (Command.eval_finished eval)
   164   | NONE => false);
   165 
   166 fun finished_result node =
   167   (case get_result node of
   168     SOME eval => Command.eval_finished eval
   169   | NONE => false);
   170 
   171 fun loaded_theory name =
   172   (case try (unsuffix ".thy") name of
   173     SOME a => get_first Thy_Info.lookup_theory [a, Long_Name.base_name a]
   174   | NONE => NONE);
   175 
   176 fun get_node nodes name = String_Graph.get_node nodes name
   177   handle String_Graph.UNDEF _ => empty_node;
   178 fun default_node name = String_Graph.default_node (name, empty_node);
   179 fun update_node name f = default_node name #> String_Graph.map_node name f;
   180 
   181 
   182 (* node edits and associated executions *)
   183 
   184 type overlay = Document_ID.command * (string * string list);
   185 
   186 datatype node_edit =
   187   Edits of (Document_ID.command option * Document_ID.command option) list |
   188   Deps of node_header |
   189   Perspective of bool * Document_ID.command list * overlay list;
   190 
   191 type edit = string * node_edit;
   192 
   193 val after_entry = Entries.get_after o get_entries;
   194 
   195 fun lookup_entry node id =
   196   (case Entries.lookup (get_entries node) id of
   197     NONE => NONE
   198   | SOME (exec, _) => exec);
   199 
   200 fun the_entry node id =
   201   (case Entries.lookup (get_entries node) id of
   202     NONE => err_undef "command entry" id
   203   | SOME (exec, _) => exec);
   204 
   205 fun the_default_entry node (SOME id) = (id, the_default Command.no_exec (the_entry node id))
   206   | the_default_entry _ NONE = (Document_ID.none, Command.no_exec);
   207 
   208 fun assign_entry (command_id, exec) node =
   209   if is_none (Entries.lookup (get_entries node) command_id) then node
   210   else map_entries (Entries.update (command_id, exec)) node;
   211 
   212 fun reset_after id entries =
   213   (case Entries.get_after entries id of
   214     NONE => entries
   215   | SOME next => Entries.update (next, NONE) entries);
   216 
   217 val edit_node = map_entries o fold
   218   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   219     | (id, NONE) => Entries.delete_after id #> reset_after id);
   220 
   221 
   222 (* version operations *)
   223 
   224 val empty_version = Version String_Graph.empty;
   225 
   226 fun nodes_of (Version nodes) = nodes;
   227 val node_of = get_node o nodes_of;
   228 
   229 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   230 
   231 fun edit_nodes (name, node_edit) (Version nodes) =
   232   Version
   233     (case node_edit of
   234       Edits edits => update_node name (edit_node edits) nodes
   235     | Deps (master, header, errors) =>
   236         let
   237           val imports = map fst (#imports header);
   238           val nodes1 = nodes
   239             |> default_node name
   240             |> fold default_node imports;
   241           val nodes2 = nodes1
   242             |> String_Graph.Keys.fold
   243                 (fn dep => String_Graph.del_edge (dep, name)) (String_Graph.imm_preds nodes1 name);
   244           val (nodes3, errors1) =
   245             (String_Graph.add_deps_acyclic (name, imports) nodes2, errors)
   246               handle String_Graph.CYCLES cs => (nodes2, errors @ map cycle_msg cs);
   247         in String_Graph.map_node name (set_header (master, header, errors1)) nodes3 end
   248     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   249 
   250 fun update_keywords name nodes =
   251   nodes |> String_Graph.map_node name (fn node =>
   252     if is_empty_node node then node
   253     else
   254       let
   255         val (master, header, errors) = get_header_raw node;
   256         val imports_keywords = map_filter (get_keywords o get_node nodes o #1) (#imports header);
   257         val keywords =
   258           Library.foldl Keyword.merge_keywords (Session.get_keywords (), imports_keywords);
   259         val (keywords', errors') =
   260           (Keyword.add_keywords (#keywords header) keywords, errors)
   261             handle ERROR msg =>
   262               (keywords, if member (op =) errors msg then errors else errors @ [msg]);
   263       in
   264         node
   265         |> set_header (master, header, errors')
   266         |> set_keywords (SOME keywords')
   267       end);
   268 
   269 fun edit_keywords edits (Version nodes) =
   270   Version
   271     (fold update_keywords
   272       (String_Graph.all_succs nodes (map_filter (fn (a, Deps _) => SOME a | _ => NONE) edits))
   273       nodes);
   274 
   275 fun put_node (name, node) (Version nodes) =
   276   let
   277     val nodes1 = update_node name (K node) nodes;
   278     val nodes2 =
   279       if String_Graph.is_maximal nodes1 name andalso is_empty_node node
   280       then String_Graph.del_node name nodes1
   281       else nodes1;
   282   in Version nodes2 end;
   283 
   284 end;
   285 
   286 
   287 
   288 (** main state -- document structure and execution process **)
   289 
   290 type blob_digest = (string * string option) Exn.result;  (*file node name, raw digest*)
   291 
   292 type execution =
   293  {version_id: Document_ID.version,  (*static version id*)
   294   execution_id: Document_ID.execution,  (*dynamic execution id*)
   295   delay_request: unit future};  (*pending event timer request*)
   296 
   297 val no_execution: execution =
   298   {version_id = Document_ID.none,
   299    execution_id = Document_ID.none,
   300    delay_request = Future.value ()};
   301 
   302 fun new_execution version_id delay_request : execution =
   303   {version_id = version_id,
   304    execution_id = Execution.start (),
   305    delay_request = delay_request};
   306 
   307 abstype state = State of
   308  {versions: version Inttab.table,  (*version id -> document content*)
   309   blobs: (SHA1.digest * string list) Symtab.table,  (*raw digest -> digest, lines*)
   310   commands: (string * blob_digest list * Token.T list lazy) Inttab.table,
   311     (*command id -> name, inlined files, command span*)
   312   execution: execution}  (*current execution process*)
   313 with
   314 
   315 fun make_state (versions, blobs, commands, execution) =
   316   State {versions = versions, blobs = blobs, commands = commands, execution = execution};
   317 
   318 fun map_state f (State {versions, blobs, commands, execution}) =
   319   make_state (f (versions, blobs, commands, execution));
   320 
   321 val init_state =
   322   make_state (Inttab.make [(Document_ID.none, empty_version)],
   323     Symtab.empty, Inttab.empty, no_execution);
   324 
   325 
   326 (* document versions *)
   327 
   328 fun define_version version_id version =
   329   map_state (fn (versions, blobs, commands, {delay_request, ...}) =>
   330     let
   331       val versions' = Inttab.update_new (version_id, version) versions
   332         handle Inttab.DUP dup => err_dup "document version" dup;
   333       val execution' = new_execution version_id delay_request;
   334     in (versions', blobs, commands, execution') end);
   335 
   336 fun the_version (State {versions, ...}) version_id =
   337   (case Inttab.lookup versions version_id of
   338     NONE => err_undef "document version" version_id
   339   | SOME version => version);
   340 
   341 fun delete_version version_id versions =
   342   Inttab.delete version_id versions
   343     handle Inttab.UNDEF _ => err_undef "document version" version_id;
   344 
   345 
   346 (* inlined files *)
   347 
   348 fun define_blob digest text =
   349   map_state (fn (versions, blobs, commands, execution) =>
   350     let val blobs' = Symtab.update (digest, (SHA1.fake digest, split_lines text)) blobs
   351     in (versions, blobs', commands, execution) end);
   352 
   353 fun the_blob (State {blobs, ...}) digest =
   354   (case Symtab.lookup blobs digest of
   355     NONE => error ("Undefined blob: " ^ digest)
   356   | SOME content => content);
   357 
   358 fun resolve_blob state (blob_digest: blob_digest) =
   359   blob_digest |> Exn.map_result (fn (file_node, raw_digest) =>
   360     (file_node, Option.map (the_blob state) raw_digest));
   361 
   362 fun blob_reports pos (blob_digest: blob_digest) =
   363   (case blob_digest of Exn.Res (file_node, _) => [(pos, Markup.path file_node)] | _ => []);
   364 
   365 
   366 (* commands *)
   367 
   368 fun define_command command_id name command_blobs blobs_index toks =
   369   map_state (fn (versions, blobs, commands, execution) =>
   370     let
   371       val id = Document_ID.print command_id;
   372       val span =
   373         Lazy.lazy (fn () =>
   374           Position.setmp_thread_data (Position.id_only id)
   375             (fn () =>
   376               let
   377                 val (tokens, _) = fold_map Token.make toks (Position.id id);
   378                 val pos =
   379                   Token.pos_of (nth tokens blobs_index)
   380                     handle General.Subscript => Position.none;
   381                 val _ =
   382                   if Position.is_reported pos then
   383                     Position.reports
   384                       ((pos, Markup.language_path) :: maps (blob_reports pos) command_blobs)
   385                   else ();
   386               in tokens end) ());
   387       val commands' =
   388         Inttab.update_new (command_id, (name, command_blobs, span)) commands
   389           handle Inttab.DUP dup => err_dup "command" dup;
   390       val _ =
   391         Position.setmp_thread_data (Position.id_only id)
   392           (fn () => Output.status (Markup.markup_only Markup.accepted)) ();
   393     in (versions, blobs, commands', execution) end);
   394 
   395 fun the_command (State {commands, ...}) command_id =
   396   (case Inttab.lookup commands command_id of
   397     NONE => err_undef "command" command_id
   398   | SOME command => command);
   399 
   400 val the_command_name = #1 oo the_command;
   401 
   402 end;
   403 
   404 
   405 (* remove_versions *)
   406 
   407 fun remove_versions version_ids state = state |> map_state (fn (versions, _, _, execution) =>
   408   let
   409     val _ =
   410       member (op =) version_ids (#version_id execution) andalso
   411         error ("Attempt to remove execution version " ^ Document_ID.print (#version_id execution));
   412 
   413     val versions' = fold delete_version version_ids versions;
   414     val commands' =
   415       (versions', Inttab.empty) |->
   416         Inttab.fold (fn (_, version) => nodes_of version |>
   417           String_Graph.fold (fn (_, (node, _)) => node |>
   418             iterate_entries (fn ((_, command_id), _) =>
   419               SOME o Inttab.insert (K true) (command_id, the_command state command_id))));
   420     val blobs' =
   421       (commands', Symtab.empty) |->
   422         Inttab.fold (fn (_, (_, blobs, _)) => blobs |>
   423           fold (fn Exn.Res (_, SOME b) => Symtab.update (b, the_blob state b) | _ => I));
   424 
   425   in (versions', blobs', commands', execution) end);
   426 
   427 
   428 (* document execution *)
   429 
   430 fun start_execution state = state |> map_state (fn (versions, blobs, commands, execution) =>
   431   timeit "Document.start_execution" (fn () =>
   432     let
   433       val {version_id, execution_id, delay_request} = execution;
   434 
   435       val delay = seconds (Options.default_real "editor_execution_delay");
   436 
   437       val _ = Future.cancel delay_request;
   438       val delay_request' = Event_Timer.future (Time.+ (Time.now (), delay));
   439 
   440       fun finished_import (name, (node, _)) =
   441         finished_result node orelse is_some (loaded_theory name);
   442       val _ =
   443         nodes_of (the_version state version_id) |> String_Graph.schedule
   444           (fn deps => fn (name, node) =>
   445             if visible_node node orelse pending_result node then
   446               let
   447                 fun body () =
   448                   (if forall finished_import deps then
   449                     iterate_entries (fn (_, opt_exec) => fn () =>
   450                       (case opt_exec of
   451                         SOME exec =>
   452                           if Execution.is_running execution_id
   453                           then SOME (Command.exec execution_id exec)
   454                           else NONE
   455                       | NONE => NONE)) node ()
   456                    else ())
   457                    handle exn => (Output.system_message (Runtime.exn_message exn); reraise exn);
   458                 val future =
   459                   (singleton o Future.forks)
   460                    {name = "theory:" ^ name,
   461                     group = SOME (Future.new_group NONE),
   462                     deps = Future.task_of delay_request' :: maps (the_list o #2 o #2) deps,
   463                     pri = 0, interrupts = false} body;
   464               in (node, SOME (Future.task_of future)) end
   465             else (node, NONE));
   466       val execution' =
   467         {version_id = version_id, execution_id = execution_id, delay_request = delay_request'};
   468     in (versions, blobs, commands, execution') end));
   469 
   470 
   471 
   472 (** document update **)
   473 
   474 (* exec state assignment *)
   475 
   476 type assign_update = Command.exec option Inttab.table;  (*command id -> exec*)
   477 
   478 val assign_update_empty: assign_update = Inttab.empty;
   479 fun assign_update_defined (tab: assign_update) command_id = Inttab.defined tab command_id;
   480 fun assign_update_apply (tab: assign_update) node = Inttab.fold assign_entry tab node;
   481 
   482 fun assign_update_new upd (tab: assign_update) =
   483   Inttab.update_new upd tab
   484     handle Inttab.DUP dup => err_dup "exec state assignment" dup;
   485 
   486 fun assign_update_result (tab: assign_update) =
   487   Inttab.fold (fn (command_id, exec) => cons (command_id, Command.exec_ids exec)) tab [];
   488 
   489 
   490 (* update *)
   491 
   492 local
   493 
   494 fun make_required nodes =
   495   let
   496     fun all_preds P =
   497       String_Graph.fold (fn (a, (node, _)) => P node ? cons a) nodes []
   498       |> String_Graph.all_preds nodes
   499       |> Symtab.make_set;
   500 
   501     val all_visible = all_preds visible_node;
   502     val all_required = all_preds required_node;
   503   in
   504     Symtab.fold (fn (a, ()) =>
   505       exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   506         Symtab.update (a, ())) all_visible all_required
   507   end;
   508 
   509 fun init_theory deps node span =
   510   let
   511     val master_dir = master_directory node;
   512     val header = read_header node span;
   513     val imports = #imports header;
   514     val parents =
   515       imports |> map (fn (import, _) =>
   516         (case loaded_theory import of
   517           SOME thy => thy
   518         | NONE =>
   519             Toplevel.end_theory (Position.file_only import)
   520               (case get_result (snd (the (AList.lookup (op =) deps import))) of
   521                 NONE => Toplevel.toplevel
   522               | SOME eval => Command.eval_result_state eval)));
   523     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   524   in Resources.begin_theory master_dir header parents end;
   525 
   526 fun check_theory full name node =
   527   is_some (loaded_theory name) orelse
   528   can get_header node andalso (not full orelse is_some (get_result node));
   529 
   530 fun last_common keywords state node_required node0 node =
   531   let
   532     fun update_flags prev (visible, initial) =
   533       let
   534         val visible' = visible andalso prev <> visible_last node;
   535         val initial' = initial andalso
   536           (case prev of
   537             NONE => true
   538           | SOME command_id =>
   539               not (Keyword.is_theory_begin keywords (the_command_name state command_id)));
   540       in (visible', initial') end;
   541 
   542     fun get_common ((prev, command_id), opt_exec) (_, ok, flags, assign_update) =
   543       if ok then
   544         let
   545           val flags' as (visible', _) = update_flags prev flags;
   546           val ok' =
   547             (case (lookup_entry node0 command_id, opt_exec) of
   548               (SOME (eval0, _), SOME (eval, _)) =>
   549                 Command.eval_eq (eval0, eval) andalso
   550                   (visible' orelse node_required orelse Command.eval_running eval)
   551             | _ => false);
   552           val assign_update' = assign_update |> ok' ?
   553             (case opt_exec of
   554               SOME (eval, prints) =>
   555                 let
   556                   val command_visible = visible_command node command_id;
   557                   val command_overlays = overlays node command_id;
   558                   val command_name = the_command_name state command_id;
   559                 in
   560                   (case
   561                     Command.print command_visible command_overlays keywords command_name eval prints
   562                    of
   563                     SOME prints' => assign_update_new (command_id, SOME (eval, prints'))
   564                   | NONE => I)
   565                 end
   566             | NONE => I);
   567         in SOME (prev, ok', flags', assign_update') end
   568       else NONE;
   569     val (common, ok, flags, assign_update') =
   570       iterate_entries get_common node (NONE, true, (true, true), assign_update_empty);
   571     val (common', flags') =
   572       if ok then
   573         let val last = Entries.get_after (get_entries node) common
   574         in (last, update_flags last flags) end
   575       else (common, flags);
   576   in (assign_update', common', flags') end;
   577 
   578 fun illegal_init _ = error "Illegal theory header after end of theory";
   579 
   580 fun new_exec keywords state node proper_init command_id' (assign_update, command_exec, init) =
   581   if not proper_init andalso is_none init then NONE
   582   else
   583     let
   584       val (_, (eval, _)) = command_exec;
   585 
   586       val command_visible = visible_command node command_id';
   587       val command_overlays = overlays node command_id';
   588       val (command_name, blob_digests, span0) = the_command state command_id';
   589       val blobs = map (resolve_blob state) blob_digests;
   590       val span = Lazy.force span0;
   591 
   592       val eval' =
   593         Command.eval keywords (master_directory node)
   594           (fn () => the_default illegal_init init span) blobs span eval;
   595       val prints' =
   596         perhaps (Command.print command_visible command_overlays keywords command_name eval') [];
   597       val exec' = (eval', prints');
   598 
   599       val assign_update' = assign_update_new (command_id', SOME exec') assign_update;
   600       val init' = if Keyword.is_theory_begin keywords command_name then NONE else init;
   601     in SOME (assign_update', (command_id', (eval', prints')), init') end;
   602 
   603 fun removed_execs node0 (command_id, exec_ids) =
   604   subtract (op =) exec_ids (Command.exec_ids (lookup_entry node0 command_id));
   605 
   606 in
   607 
   608 fun update old_version_id new_version_id edits state = Runtime.exn_trace_system (fn () =>
   609   let
   610     val old_version = the_version state old_version_id;
   611     val new_version =
   612       timeit "Document.edit_nodes"
   613         (fn () => old_version |> fold edit_nodes edits |> edit_keywords edits);
   614 
   615     val nodes = nodes_of new_version;
   616     val required = make_required nodes;
   617     val required0 = make_required (nodes_of old_version);
   618     val edited = fold (fn (name, _) => Symtab.update (name, ())) edits Symtab.empty;
   619 
   620     val updated = timeit "Document.update" (fn () =>
   621       nodes |> String_Graph.schedule
   622         (fn deps => fn (name, node) =>
   623           (singleton o Future.forks)
   624             {name = "Document.update", group = NONE,
   625               deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   626             (fn () =>
   627               timeit ("Document.update " ^ name) (fn () =>
   628                 Runtime.exn_trace_system (fn () =>
   629                   let
   630                     val keywords = the_default (Session.get_keywords ()) (get_keywords node);
   631                     val imports = map (apsnd Future.join) deps;
   632                     val imports_result_changed = exists (#4 o #1 o #2) imports;
   633                     val node_required = Symtab.defined required name;
   634                   in
   635                     if Symtab.defined edited name orelse visible_node node orelse
   636                       imports_result_changed orelse Symtab.defined required0 name <> node_required
   637                     then
   638                       let
   639                         val node0 = node_of old_version name;
   640                         val init = init_theory imports node;
   641                         val proper_init =
   642                           check_theory false name node andalso
   643                           forall (fn (name, (_, node)) => check_theory true name node) imports;
   644 
   645                         val (print_execs, common, (still_visible, initial)) =
   646                           if imports_result_changed then (assign_update_empty, NONE, (true, true))
   647                           else last_common keywords state node_required node0 node;
   648                         val common_command_exec = the_default_entry node common;
   649 
   650                         val (updated_execs, (command_id', (eval', _)), _) =
   651                           (print_execs, common_command_exec, if initial then SOME init else NONE)
   652                           |> (still_visible orelse node_required) ?
   653                             iterate_entries_after common
   654                               (fn ((prev, id), _) => fn res =>
   655                                 if not node_required andalso prev = visible_last node then NONE
   656                                 else new_exec keywords state node proper_init id res) node;
   657 
   658                         val assigned_execs =
   659                           (node0, updated_execs) |-> iterate_entries_after common
   660                             (fn ((_, command_id0), exec0) => fn res =>
   661                               if is_none exec0 then NONE
   662                               else if assign_update_defined updated_execs command_id0 then SOME res
   663                               else SOME (assign_update_new (command_id0, NONE) res));
   664 
   665                         val last_exec =
   666                           if command_id' = Document_ID.none then NONE else SOME command_id';
   667                         val result =
   668                           if is_none last_exec orelse is_some (after_entry node last_exec) then NONE
   669                           else SOME eval';
   670 
   671                         val assign_update = assign_update_result assigned_execs;
   672                         val removed = maps (removed_execs node0) assign_update;
   673                         val _ = List.app Execution.cancel removed;
   674 
   675                         val node' = node
   676                           |> assign_update_apply assigned_execs
   677                           |> set_result result;
   678                         val assigned_node = SOME (name, node');
   679                         val result_changed = changed_result node0 node';
   680                       in ((removed, assign_update, assigned_node, result_changed), node') end
   681                     else (([], [], NONE, false), node)
   682                   end))))
   683       |> Future.joins |> map #1);
   684 
   685     val removed = maps #1 updated;
   686     val assign_update = maps #2 updated;
   687     val assigned_nodes = map_filter #3 updated;
   688 
   689     val state' = state
   690       |> define_version new_version_id (fold put_node assigned_nodes new_version);
   691 
   692   in (removed, assign_update, state') end);
   693 
   694 end;
   695 
   696 
   697 
   698 (** global state **)
   699 
   700 val global_state = Synchronized.var "Document.global_state" init_state;
   701 
   702 fun state () = Synchronized.value global_state;
   703 val change_state = Synchronized.change global_state;
   704 
   705 end;
   706