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