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