src/Pure/PIDE/document.ML
author wenzelm
Fri Jul 05 15:38:03 2013 +0200 (2013-07-05)
changeset 52530 99dd8b4ef3fe
parent 52527 dbac84eab3bc
child 52532 c81d76f7f63d
permissions -rw-r--r--
explicit module Document_ID as source of globally unique identifiers across ML/Scala;
     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, with asynchronous read/eval/print processes.
     6 *)
     7 
     8 signature DOCUMENT =
     9 sig
    10   type node_header = string * Thy_Header.header * string list
    11   datatype node_edit =
    12     Clear |    (* FIXME unused !? *)
    13     Edits of (Document_ID.command option * Document_ID.command option) list |
    14     Deps of node_header |
    15     Perspective of Document_ID.command list
    16   type edit = string * node_edit
    17   type state
    18   val init_state: state
    19   val define_command: Document_ID.command -> string -> string -> state -> state
    20   val remove_versions: Document_ID.version list -> state -> state
    21   val discontinue_execution: state -> unit
    22   val cancel_execution: state -> unit
    23   val start_execution: state -> unit
    24   val timing: bool Unsynchronized.ref
    25   val update: Document_ID.version -> Document_ID.version -> edit list -> state ->
    26     (Document_ID.command * Document_ID.exec list) list * state
    27   val state: unit -> state
    28   val change_state: (state -> state) -> unit
    29 end;
    30 
    31 structure Document: DOCUMENT =
    32 struct
    33 
    34 (* command execution *)
    35 
    36 type exec = Document_ID.exec * (Command.eval * Command.print list);  (*eval/print process*)
    37 val no_exec: exec = (Document_ID.none, (Command.no_eval, []));
    38 
    39 fun exec_ids_of ((exec_id, (_, prints)): exec) = exec_id :: map #exec_id prints;
    40 
    41 fun exec_result ((_, (eval, _)): exec) = Command.memo_result eval;
    42 
    43 fun exec_run ((_, (eval, prints)): exec) =
    44  (Command.memo_eval eval;
    45   prints |> List.app (fn {name, pri, print, ...} =>
    46     Command.memo_fork {name = name, group = NONE, deps = [], pri = pri, interrupts = true} print));
    47 
    48 
    49 
    50 (** document structure **)
    51 
    52 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ Document_ID.print id);
    53 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ Document_ID.print id);
    54 
    55 type node_header = string * Thy_Header.header * string list;
    56 type perspective = Inttab.set * Document_ID.command option;
    57 structure Entries = Linear_Set(type key = Document_ID.command val ord = int_ord);
    58 
    59 abstype node = Node of
    60  {header: node_header,  (*master directory, theory header, errors*)
    61   perspective: perspective,  (*visible commands, last visible command*)
    62   entries: exec option Entries.T * bool,  (*command entries with excecutions, stable*)
    63   result: Command.eval option}  (*result of last execution*)
    64 and version = Version of node String_Graph.T  (*development graph wrt. static imports*)
    65 with
    66 
    67 fun make_node (header, perspective, entries, result) =
    68   Node {header = header, perspective = perspective, entries = entries, result = result};
    69 
    70 fun map_node f (Node {header, perspective, entries, result}) =
    71   make_node (f (header, perspective, entries, result));
    72 
    73 fun make_perspective command_ids : perspective =
    74   (Inttab.make_set command_ids, try List.last command_ids);
    75 
    76 val no_header = ("", Thy_Header.make ("", Position.none) [] [], ["Bad theory header"]);
    77 val no_perspective = make_perspective [];
    78 
    79 val empty_node = make_node (no_header, no_perspective, (Entries.empty, true), NONE);
    80 val clear_node =
    81   map_node (fn (header, _, _, _) => (header, no_perspective, (Entries.empty, true), NONE));
    82 
    83 
    84 (* basic components *)
    85 
    86 fun set_header header =
    87   map_node (fn (_, perspective, entries, result) => (header, perspective, entries, result));
    88 
    89 fun get_header (Node {header = (master, header, errors), ...}) =
    90   if null errors then (master, header)
    91   else error (cat_lines errors);
    92 
    93 fun read_header node span =
    94   let
    95     val (dir, {name = (name, _), imports, keywords}) = get_header node;
    96     val {name = (_, pos), imports = imports', ...} = Thy_Header.read_tokens span;
    97   in (dir, Thy_Header.make (name, pos) (map #1 imports ~~ map #2 imports') keywords) end;
    98 
    99 fun get_perspective (Node {perspective, ...}) = perspective;
   100 fun set_perspective ids =
   101   map_node (fn (header, _, entries, result) => (header, make_perspective ids, entries, result));
   102 
   103 val visible_commands = #1 o get_perspective;
   104 val visible_last = #2 o get_perspective;
   105 val visible_node = is_some o visible_last
   106 
   107 fun map_entries f =
   108   map_node (fn (header, perspective, (entries, stable), result) =>
   109     (header, perspective, (f entries, stable), result));
   110 fun get_entries (Node {entries = (entries, _), ...}) = entries;
   111 
   112 fun entries_stable stable =
   113   map_node (fn (header, perspective, (entries, _), result) =>
   114     (header, perspective, (entries, stable), result));
   115 fun stable_entries (Node {entries = (_, stable), ...}) = stable;
   116 
   117 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   118 fun iterate_entries_after start f (Node {entries = (entries, _), ...}) =
   119   (case Entries.get_after entries start of
   120     NONE => I
   121   | SOME id => Entries.iterate (SOME id) f entries);
   122 
   123 fun get_result (Node {result, ...}) = result;
   124 fun set_result result =
   125   map_node (fn (header, perspective, entries, _) => (header, perspective, entries, result));
   126 
   127 fun get_node nodes name = String_Graph.get_node nodes name
   128   handle String_Graph.UNDEF _ => empty_node;
   129 fun default_node name = String_Graph.default_node (name, empty_node);
   130 fun update_node name f = default_node name #> String_Graph.map_node name f;
   131 
   132 
   133 (* node edits and associated executions *)
   134 
   135 datatype node_edit =
   136   Clear |
   137   Edits of (Document_ID.command option * Document_ID.command option) list |
   138   Deps of node_header |
   139   Perspective of Document_ID.command list;
   140 
   141 type edit = string * node_edit;
   142 
   143 val after_entry = Entries.get_after o get_entries;
   144 
   145 fun lookup_entry node id =
   146   (case Entries.lookup (get_entries node) id of
   147     NONE => NONE
   148   | SOME (exec, _) => exec);
   149 
   150 fun the_entry node id =
   151   (case Entries.lookup (get_entries node) id of
   152     NONE => err_undef "command entry" id
   153   | SOME (exec, _) => exec);
   154 
   155 fun the_default_entry node (SOME id) = (id, the_default no_exec (the_entry node id))
   156   | the_default_entry _ NONE = (Document_ID.none, no_exec);
   157 
   158 fun update_entry id exec =
   159   map_entries (Entries.update (id, exec));
   160 
   161 fun reset_entry id node =
   162   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   163 
   164 fun reset_after id entries =
   165   (case Entries.get_after entries id of
   166     NONE => entries
   167   | SOME next => Entries.update (next, NONE) entries);
   168 
   169 val edit_node = map_entries o fold
   170   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   171     | (id, NONE) => Entries.delete_after id #> reset_after id);
   172 
   173 
   174 (* version operations *)
   175 
   176 val empty_version = Version String_Graph.empty;
   177 
   178 fun nodes_of (Version nodes) = nodes;
   179 val node_of = get_node o nodes_of;
   180 
   181 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   182 
   183 fun edit_nodes (name, node_edit) (Version nodes) =
   184   Version
   185     (case node_edit of
   186       Clear => update_node name clear_node nodes
   187     | Edits edits => update_node name (edit_node edits) nodes
   188     | Deps (master, header, errors) =>
   189         let
   190           val imports = map fst (#imports header);
   191           val errors1 =
   192             (Thy_Header.define_keywords header; errors)
   193               handle ERROR msg => errors @ [msg];
   194           val nodes1 = nodes
   195             |> default_node name
   196             |> fold default_node imports;
   197           val nodes2 = nodes1
   198             |> String_Graph.Keys.fold
   199                 (fn dep => String_Graph.del_edge (dep, name)) (String_Graph.imm_preds nodes1 name);
   200           val (nodes3, errors2) =
   201             (String_Graph.add_deps_acyclic (name, imports) nodes2, errors1)
   202               handle String_Graph.CYCLES cs => (nodes2, errors1 @ map cycle_msg cs);
   203         in String_Graph.map_node name (set_header (master, header, errors2)) nodes3 end
   204     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   205 
   206 fun put_node (name, node) (Version nodes) =
   207   Version (update_node name (K node) nodes);
   208 
   209 end;
   210 
   211 
   212 
   213 (** main state -- document structure and execution process **)
   214 
   215 abstype state = State of
   216  {versions: version Inttab.table,  (*version_id -> document content*)
   217   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> named span*)
   218   execution:
   219     Document_ID.version * Future.group * bool Unsynchronized.ref}  (*current execution process*)
   220 with
   221 
   222 fun make_state (versions, commands, execution) =
   223   State {versions = versions, commands = commands, execution = execution};
   224 
   225 fun map_state f (State {versions, commands, execution}) =
   226   make_state (f (versions, commands, execution));
   227 
   228 val init_state =
   229   make_state (Inttab.make [(Document_ID.none, empty_version)], Inttab.empty,
   230     (Document_ID.none, Future.new_group NONE, Unsynchronized.ref false));
   231 
   232 fun execution_of (State {execution, ...}) = execution;
   233 
   234 
   235 (* document versions *)
   236 
   237 fun define_version (id: Document_ID.version) version =
   238   map_state (fn (versions, commands, _) =>
   239     let
   240       val versions' = Inttab.update_new (id, version) versions
   241         handle Inttab.DUP dup => err_dup "document version" dup;
   242       val execution' = (id, Future.new_group NONE, Unsynchronized.ref true);
   243     in (versions', commands, execution') end);
   244 
   245 fun the_version (State {versions, ...}) (id: Document_ID.version) =
   246   (case Inttab.lookup versions id of
   247     NONE => err_undef "document version" id
   248   | SOME version => version);
   249 
   250 fun delete_version (id: Document_ID.version) versions = Inttab.delete id versions
   251   handle Inttab.UNDEF _ => err_undef "document version" id;
   252 
   253 
   254 (* commands *)
   255 
   256 fun define_command (id: Document_ID.command) name text =
   257   map_state (fn (versions, commands, execution) =>
   258     let
   259       val id_string = Document_ID.print id;
   260       val span = Lazy.lazy (fn () =>
   261         Position.setmp_thread_data (Position.id_only id_string)
   262           (fn () => Thy_Syntax.parse_tokens (Keyword.get_lexicons ()) (Position.id id_string) text)
   263             ());
   264       val _ =
   265         Position.setmp_thread_data (Position.id_only id_string)
   266           (fn () => Output.status (Markup.markup_only Markup.accepted)) ();
   267       val commands' =
   268         Inttab.update_new (id, (name, span)) commands
   269           handle Inttab.DUP dup => err_dup "command" dup;
   270     in (versions, commands', execution) end);
   271 
   272 fun the_command (State {commands, ...}) (id: Document_ID.command) =
   273   (case Inttab.lookup commands id of
   274     NONE => err_undef "command" id
   275   | SOME command => command);
   276 
   277 end;
   278 
   279 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   280   let
   281     val _ = member (op =) ids (#1 execution) andalso
   282       error ("Attempt to remove execution version " ^ Document_ID.print (#1 execution));
   283 
   284     val versions' = fold delete_version ids versions;
   285     val commands' =
   286       (versions', Inttab.empty) |->
   287         Inttab.fold (fn (_, version) => nodes_of version |>
   288           String_Graph.fold (fn (_, (node, _)) => node |>
   289             iterate_entries (fn ((_, id), _) =>
   290               SOME o Inttab.insert (K true) (id, the_command state id))));
   291   in (versions', commands', execution) end);
   292 
   293 
   294 (* consolidated states *)
   295 
   296 fun stable_goals exec_id =
   297   not (Par_Exn.is_interrupted (Future.join_results (Goal.peek_futures exec_id)));
   298 
   299 fun stable_eval ((exec_id, (eval, _)): exec) =
   300   stable_goals exec_id andalso Command.memo_stable eval;
   301 
   302 fun stable_print ({exec_id, print, ...}: Command.print) =
   303   stable_goals exec_id andalso Command.memo_stable print;
   304 
   305 fun finished_theory node =
   306   (case Exn.capture (Command.memo_result o the) (get_result node) of
   307     Exn.Res {state = st, ...} => can (Toplevel.end_theory Position.none) st
   308   | _ => false);
   309 
   310 
   311 
   312 (** document execution **)
   313 
   314 val discontinue_execution = execution_of #> (fn (_, _, running) => running := false);
   315 val cancel_execution = execution_of #> (fn (_, group, _) => Future.cancel_group group);
   316 val terminate_execution = execution_of #> (fn (_, group, _) => Future.terminate group);
   317 
   318 fun start_execution state =
   319   let
   320     val (version_id, group, running) = execution_of state;
   321     val _ =
   322       (singleton o Future.forks)
   323         {name = "Document.execution", group = SOME group, deps = [], pri = ~2, interrupts = true}
   324         (fn () =>
   325          (OS.Process.sleep (seconds 0.02);
   326           nodes_of (the_version state version_id) |> String_Graph.schedule
   327             (fn deps => fn (name, node) =>
   328               if not (visible_node node) andalso finished_theory node then
   329                 Future.value ()
   330               else
   331                 (singleton o Future.forks)
   332                   {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   333                     deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   334                   (fn () =>
   335                     iterate_entries (fn (_, opt_exec) => fn () =>
   336                       (case opt_exec of
   337                         SOME exec => if ! running then SOME (exec_run exec) else NONE
   338                       | NONE => NONE)) node ()))));
   339   in () end;
   340 
   341 
   342 
   343 (** document update **)
   344 
   345 val timing = Unsynchronized.ref false;
   346 fun timeit msg e = cond_timeit (! timing) msg e;
   347 
   348 local
   349 
   350 fun make_required nodes =
   351   let
   352     val all_visible =
   353       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   354       |> String_Graph.all_preds nodes
   355       |> map (rpair ()) |> Symtab.make;
   356 
   357     val required =
   358       Symtab.fold (fn (a, ()) =>
   359         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   360           Symtab.update (a, ())) all_visible Symtab.empty;
   361   in Symtab.defined required end;
   362 
   363 fun init_theory deps node span =
   364   let
   365     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   366     val (dir, header) = read_header node span;
   367     val master_dir =
   368       (case try Url.explode dir of
   369         SOME (Url.File path) => path
   370       | _ => Path.current);
   371     val imports = #imports header;
   372     val parents =
   373       imports |> map (fn (import, _) =>
   374         (case Thy_Info.lookup_theory import of
   375           SOME thy => thy
   376         | NONE =>
   377             Toplevel.end_theory (Position.file_only import)
   378               (#state
   379                 (Command.memo_result
   380                   (the_default Command.no_eval
   381                     (get_result (snd (the (AList.lookup (op =) deps import)))))))));
   382     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   383   in Thy_Load.begin_theory master_dir header parents end;
   384 
   385 fun check_theory full name node =
   386   is_some (Thy_Info.lookup_theory name) orelse
   387   can get_header node andalso (not full orelse is_some (get_result node));
   388 
   389 fun last_common state last_visible node0 node =
   390   let
   391     fun update_flags prev (visible, initial) =
   392       let
   393         val visible' = visible andalso prev <> last_visible;
   394         val initial' = initial andalso
   395           (case prev of
   396             NONE => true
   397           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   398       in (visible', initial') end;
   399     fun get_common ((prev, id), opt_exec) (same, (_, flags)) =
   400       if same then
   401         let
   402           val flags' = update_flags prev flags;
   403           val same' =
   404             (case opt_exec of
   405               NONE => false
   406             | SOME (exec_id, exec) =>
   407                 (case lookup_entry node0 id of
   408                   NONE => false
   409                 | SOME (exec_id0, _) => exec_id = exec_id0 andalso stable_eval (exec_id, exec)));
   410         in SOME (same', (prev, flags')) end
   411       else NONE;
   412     val (same, (common, flags)) =
   413       iterate_entries get_common node (true, (NONE, (true, true)));
   414   in
   415     if same then
   416       let val last = Entries.get_after (get_entries node) common
   417       in (last, update_flags last flags) end
   418     else (common, flags)
   419   end;
   420 
   421 fun new_exec state proper_init command_visible command_id' (execs, command_exec, init) =
   422   if not proper_init andalso is_none init then NONE
   423   else
   424     let
   425       val (command_name, span) = the_command state command_id' ||> Lazy.force;
   426 
   427       fun illegal_init _ = error "Illegal theory header after end of theory";
   428       val (modify_init, init') =
   429         if Keyword.is_theory_begin command_name then
   430           (Toplevel.modify_init (fn () => the_default illegal_init init span), NONE)
   431         else (I, init);
   432 
   433       val exec_id' = Document_ID.make ();
   434       val eval' =
   435         Command.memo (fn () =>
   436           let
   437             val eval_state = exec_result (snd command_exec);
   438             val tr =
   439               Position.setmp_thread_data (Position.id_only (Document_ID.print exec_id'))
   440                 (fn () =>
   441                   Command.read span
   442                   |> modify_init
   443                   |> Toplevel.put_id exec_id') ();
   444           in Command.eval span tr eval_state end);
   445       val prints' = if command_visible then Command.print command_name eval' else [];
   446       val command_exec' = (command_id', (exec_id', (eval', prints')));
   447     in SOME (command_exec' :: execs, command_exec', init') end;
   448 
   449 fun update_prints state node command_id =
   450   (case the_entry node command_id of
   451     SOME (exec_id, (eval, prints)) =>
   452       let
   453         val (command_name, _) = the_command state command_id;
   454         val new_prints = Command.print command_name eval;
   455         val prints' =
   456           new_prints |> map (fn new_print =>
   457             (case find_first (fn {name, ...} => name = #name new_print) prints of
   458               SOME print => if stable_print print then print else new_print
   459             | NONE => new_print));
   460       in
   461         if eq_list (op = o pairself #exec_id) (prints, prints') then NONE
   462         else SOME (command_id, (exec_id, (eval, prints')))
   463       end
   464   | NONE => NONE);
   465 
   466 in
   467 
   468 fun update (old_id: Document_ID.version) (new_id: Document_ID.version) edits state =
   469   let
   470     val old_version = the_version state old_id;
   471     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   472 
   473     val nodes = nodes_of new_version;
   474     val is_required = make_required nodes;
   475 
   476     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   477     val updated = timeit "Document.update" (fn () =>
   478       nodes |> String_Graph.schedule
   479         (fn deps => fn (name, node) =>
   480           (singleton o Future.forks)
   481             {name = "Document.update", group = NONE,
   482               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   483             (fn () =>
   484               let
   485                 val imports = map (apsnd Future.join) deps;
   486                 val changed_imports = exists (#4 o #1 o #2) imports;
   487                 val node_required = is_required name;
   488               in
   489                 if changed_imports orelse AList.defined (op =) edits name orelse
   490                   not (stable_entries node) orelse not (finished_theory node)
   491                 then
   492                   let
   493                     val node0 = node_of old_version name;
   494                     val init = init_theory imports node;
   495                     val proper_init =
   496                       check_theory false name node andalso
   497                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   498 
   499                     val visible_commands = visible_commands node;
   500                     val visible_command = Inttab.defined visible_commands;
   501                     val last_visible = visible_last node;
   502 
   503                     val (common, (still_visible, initial)) =
   504                       if changed_imports then (NONE, (true, true))
   505                       else last_common state last_visible node0 node;
   506                     val common_command_exec = the_default_entry node common;
   507 
   508                     val (new_execs, (command_id', (_, (eval', _))), _) =
   509                       ([], common_command_exec, if initial then SOME init else NONE) |>
   510                       (still_visible orelse node_required) ?
   511                         iterate_entries_after common
   512                           (fn ((prev, id), _) => fn res =>
   513                             if not node_required andalso prev = last_visible then NONE
   514                             else new_exec state proper_init (visible_command id) id res) node;
   515 
   516                     val updated_execs =
   517                       (visible_commands, new_execs) |-> Inttab.fold (fn (id, ()) =>
   518                         if exists (fn (_, (id', _)) => id = id') new_execs then I
   519                         else append (the_list (update_prints state node id)));
   520 
   521                     val no_execs =
   522                       iterate_entries_after common
   523                         (fn ((_, id0), exec0) => fn res =>
   524                           if is_none exec0 then NONE
   525                           else if exists (fn (_, (id, _)) => id0 = id) updated_execs
   526                           then SOME res
   527                           else SOME (id0 :: res)) node0 [];
   528 
   529                     val last_exec =
   530                       if command_id' = Document_ID.none then NONE else SOME command_id';
   531                     val result =
   532                       if is_some (after_entry node last_exec) then NONE
   533                       else SOME eval';
   534 
   535                     val node' = node
   536                       |> fold reset_entry no_execs
   537                       |> fold (fn (id, exec) => update_entry id (SOME exec)) updated_execs
   538                       |> entries_stable (null updated_execs)
   539                       |> set_result result;
   540                     val updated_node =
   541                       if null no_execs andalso null updated_execs then NONE
   542                       else SOME (name, node');
   543                     val changed_result = not (null no_execs) orelse not (null new_execs);
   544                   in ((no_execs, updated_execs, updated_node, changed_result), node') end
   545                 else (([], [], NONE, false), node)
   546               end))
   547       |> Future.joins |> map #1);
   548 
   549     val command_execs =
   550       map (rpair []) (maps #1 updated) @
   551       map (fn (command_id, exec) => (command_id, exec_ids_of exec)) (maps #2 updated);
   552     val updated_nodes = map_filter #3 updated;
   553 
   554     val state' = state
   555       |> define_version new_id (fold put_node updated_nodes new_version);
   556   in (command_execs, state') end;
   557 
   558 end;
   559 
   560 
   561 
   562 (** global state **)
   563 
   564 val global_state = Synchronized.var "Document.global_state" init_state;
   565 
   566 fun state () = Synchronized.value global_state;
   567 val change_state = Synchronized.change global_state;
   568 
   569 end;
   570