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