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