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