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