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