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