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