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