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