src/Pure/PIDE/document.ML
author wenzelm
Fri Jul 05 22:58:24 2013 +0200 (2013-07-05)
changeset 52536 3a35ce87a55c
parent 52534 341ae9cd4743
child 52566 52a0eacf04d1
permissions -rw-r--r--
tuned signature;
tuned comments;
     1 (*  Title:      Pure/PIDE/document.ML
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 *)
     7 
     8 signature DOCUMENT =
     9 sig
    10   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 type execution =
   205  {version_id: Document_ID.version,
   206   group: Future.group,
   207   running: bool Unsynchronized.ref};
   208 
   209 val no_execution =
   210  {version_id = Document_ID.none,
   211   group = Future.new_group NONE,
   212   running = Unsynchronized.ref false};
   213 
   214 abstype state = State of
   215  {versions: version Inttab.table,  (*version id -> document content*)
   216   commands: (string * Token.T list lazy) Inttab.table,  (*command id -> named span*)
   217   execution: execution}  (*current execution process*)
   218 with
   219 
   220 fun make_state (versions, commands, execution) =
   221   State {versions = versions, commands = commands, execution = execution};
   222 
   223 fun map_state f (State {versions, commands, execution}) =
   224   make_state (f (versions, commands, execution));
   225 
   226 val init_state =
   227   make_state (Inttab.make [(Document_ID.none, empty_version)], Inttab.empty, no_execution);
   228 
   229 fun execution_of (State {execution, ...}) = execution;
   230 
   231 
   232 (* document versions *)
   233 
   234 fun define_version version_id version =
   235   map_state (fn (versions, commands, _) =>
   236     let
   237       val versions' = Inttab.update_new (version_id, version) versions
   238         handle Inttab.DUP dup => err_dup "document version" dup;
   239       val execution' =
   240        {version_id = version_id,
   241         group = Future.new_group NONE,
   242         running = Unsynchronized.ref true};
   243     in (versions', commands, execution') end);
   244 
   245 fun the_version (State {versions, ...}) version_id =
   246   (case Inttab.lookup versions version_id of
   247     NONE => err_undef "document version" version_id
   248   | SOME version => version);
   249 
   250 fun delete_version version_id versions =
   251   Inttab.delete version_id versions
   252     handle Inttab.UNDEF _ => err_undef "document version" version_id;
   253 
   254 
   255 (* commands *)
   256 
   257 fun define_command command_id name text =
   258   map_state (fn (versions, commands, execution) =>
   259     let
   260       val id = Document_ID.print command_id;
   261       val span =
   262         Lazy.lazy (fn () =>
   263           Position.setmp_thread_data (Position.id_only id)
   264             (fn () => Thy_Syntax.parse_tokens (Keyword.get_lexicons ()) (Position.id id) text) ());
   265       val _ =
   266         Position.setmp_thread_data (Position.id_only id)
   267           (fn () => Output.status (Markup.markup_only Markup.accepted)) ();
   268       val commands' =
   269         Inttab.update_new (command_id, (name, span)) commands
   270           handle Inttab.DUP dup => err_dup "command" dup;
   271     in (versions, commands', execution) end);
   272 
   273 fun the_command (State {commands, ...}) command_id =
   274   (case Inttab.lookup commands command_id of
   275     NONE => err_undef "command" command_id
   276   | SOME command => command);
   277 
   278 end;
   279 
   280 fun remove_versions version_ids state = state |> map_state (fn (versions, _, execution) =>
   281   let
   282     val _ =
   283       member (op =) version_ids (#version_id execution) andalso
   284         error ("Attempt to remove execution version " ^ Document_ID.print (#version_id execution));
   285 
   286     val versions' = fold delete_version version_ids versions;
   287     val commands' =
   288       (versions', Inttab.empty) |->
   289         Inttab.fold (fn (_, version) => nodes_of version |>
   290           String_Graph.fold (fn (_, (node, _)) => node |>
   291             iterate_entries (fn ((_, command_id), _) =>
   292               SOME o Inttab.insert (K true) (command_id, the_command state command_id))));
   293   in (versions', commands', execution) end);
   294 
   295 
   296 
   297 (** document execution **)
   298 
   299 val discontinue_execution = execution_of #> (fn {running, ...} => running := false);
   300 val cancel_execution = execution_of #> (fn {group, ...} => Future.cancel_group group);
   301 val terminate_execution = execution_of #> (fn {group, ...} => Future.terminate group);
   302 
   303 fun start_execution state =
   304   let
   305     val {version_id, group, running} = execution_of state;
   306     val _ =
   307       (singleton o Future.forks)
   308         {name = "Document.execution", group = SOME group, deps = [], pri = ~2, interrupts = true}
   309         (fn () =>
   310          (OS.Process.sleep (seconds 0.02);
   311           nodes_of (the_version state version_id) |> String_Graph.schedule
   312             (fn deps => fn (name, node) =>
   313               if not (visible_node node) andalso finished_theory node then
   314                 Future.value ()
   315               else
   316                 (singleton o Future.forks)
   317                   {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   318                     deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   319                   (fn () =>
   320                     iterate_entries (fn (_, opt_exec) => fn () =>
   321                       (case opt_exec of
   322                         SOME exec => if ! running then SOME (Command.execute exec) else NONE
   323                       | NONE => NONE)) node ()))));
   324   in () end;
   325 
   326 
   327 
   328 (** document update **)
   329 
   330 val timing = Unsynchronized.ref false;
   331 fun timeit msg e = cond_timeit (! timing) msg e;
   332 
   333 local
   334 
   335 fun make_required nodes =
   336   let
   337     val all_visible =
   338       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   339       |> String_Graph.all_preds nodes
   340       |> map (rpair ()) |> Symtab.make;
   341 
   342     val required =
   343       Symtab.fold (fn (a, ()) =>
   344         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   345           Symtab.update (a, ())) all_visible Symtab.empty;
   346   in Symtab.defined required end;
   347 
   348 fun init_theory deps node span =
   349   let
   350     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   351     val (dir, header) = read_header node span;
   352     val master_dir =
   353       (case try Url.explode dir of
   354         SOME (Url.File path) => path
   355       | _ => Path.current);
   356     val imports = #imports header;
   357     val parents =
   358       imports |> map (fn (import, _) =>
   359         (case Thy_Info.lookup_theory import of
   360           SOME thy => thy
   361         | NONE =>
   362             Toplevel.end_theory (Position.file_only import)
   363               (case get_result (snd (the (AList.lookup (op =) deps import))) of
   364                 NONE => Toplevel.toplevel
   365               | SOME eval => Command.eval_result_state eval)));
   366     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   367   in Thy_Load.begin_theory master_dir header parents end;
   368 
   369 fun check_theory full name node =
   370   is_some (Thy_Info.lookup_theory name) orelse
   371   can get_header node andalso (not full orelse is_some (get_result node));
   372 
   373 fun last_common state last_visible node0 node =
   374   let
   375     fun update_flags prev (visible, initial) =
   376       let
   377         val visible' = visible andalso prev <> last_visible;
   378         val initial' = initial andalso
   379           (case prev of
   380             NONE => true
   381           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   382       in (visible', initial') end;
   383     fun get_common ((prev, id), opt_exec) (same, (_, flags)) =
   384       if same then
   385         let
   386           val flags' = update_flags prev flags;
   387           val same' =
   388             (case opt_exec of
   389               NONE => false
   390             | SOME (eval, _) =>
   391                 (case lookup_entry node0 id of
   392                   NONE => false
   393                 | SOME (eval0, _) =>
   394                     #exec_id eval = #exec_id eval0 andalso Command.stable_eval eval));
   395         in SOME (same', (prev, flags')) end
   396       else NONE;
   397     val (same, (common, flags)) =
   398       iterate_entries get_common node (true, (NONE, (true, true)));
   399   in
   400     if same then
   401       let val last = Entries.get_after (get_entries node) common
   402       in (last, update_flags last flags) end
   403     else (common, flags)
   404   end;
   405 
   406 fun illegal_init _ = error "Illegal theory header after end of theory";
   407 
   408 fun new_exec state proper_init command_visible command_id' (execs, command_exec, init) =
   409   if not proper_init andalso is_none init then NONE
   410   else
   411     let
   412       val (_, (eval, _)) = command_exec;
   413       val (command_name, span) = the_command state command_id' ||> Lazy.force;
   414       val init' = if Keyword.is_theory_begin command_name then NONE else init;
   415       val eval' = Command.eval (fn () => the_default illegal_init init span) span eval;
   416       val prints' = if command_visible then Command.print command_name eval' else [];
   417       val command_exec' = (command_id', (eval', prints'));
   418     in SOME (command_exec' :: execs, command_exec', init') end;
   419 
   420 fun update_prints state node command_id =
   421   (case the_entry node command_id of
   422     SOME (eval, prints) =>
   423       let
   424         val (command_name, _) = the_command state command_id;
   425         val new_prints = Command.print command_name eval;
   426         val prints' =
   427           new_prints |> map (fn new_print =>
   428             (case find_first (fn {name, ...} => name = #name new_print) prints of
   429               SOME print => if Command.stable_print print then print else new_print
   430             | NONE => new_print));
   431       in
   432         if eq_list (op = o pairself #exec_id) (prints, prints') then NONE
   433         else SOME (command_id, (eval, prints'))
   434       end
   435   | NONE => NONE);
   436 
   437 in
   438 
   439 fun update old_version_id new_version_id edits state =
   440   let
   441     val old_version = the_version state old_version_id;
   442     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   443 
   444     val nodes = nodes_of new_version;
   445     val is_required = make_required nodes;
   446 
   447     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   448     val updated = timeit "Document.update" (fn () =>
   449       nodes |> String_Graph.schedule
   450         (fn deps => fn (name, node) =>
   451           (singleton o Future.forks)
   452             {name = "Document.update", group = NONE,
   453               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   454             (fn () =>
   455               let
   456                 val imports = map (apsnd Future.join) deps;
   457                 val changed_imports = exists (#4 o #1 o #2) imports;
   458                 val node_required = is_required name;
   459               in
   460                 if changed_imports orelse AList.defined (op =) edits name orelse
   461                   not (stable_entries node) orelse not (finished_theory node)
   462                 then
   463                   let
   464                     val node0 = node_of old_version name;
   465                     val init = init_theory imports node;
   466                     val proper_init =
   467                       check_theory false name node andalso
   468                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   469 
   470                     val visible_commands = visible_commands node;
   471                     val visible_command = Inttab.defined visible_commands;
   472                     val last_visible = visible_last node;
   473 
   474                     val (common, (still_visible, initial)) =
   475                       if changed_imports then (NONE, (true, true))
   476                       else last_common state last_visible node0 node;
   477                     val common_command_exec = the_default_entry node common;
   478 
   479                     val (new_execs, (command_id', (eval', _)), _) =
   480                       ([], common_command_exec, if initial then SOME init else NONE) |>
   481                       (still_visible orelse node_required) ?
   482                         iterate_entries_after common
   483                           (fn ((prev, id), _) => fn res =>
   484                             if not node_required andalso prev = last_visible then NONE
   485                             else new_exec state proper_init (visible_command id) id res) node;
   486 
   487                     val updated_execs =
   488                       (visible_commands, new_execs) |-> Inttab.fold (fn (id, ()) =>
   489                         if exists (fn (_, ({exec_id = id', ...}, _)) => id = id') new_execs then I
   490                         else append (the_list (update_prints state node id)));
   491 
   492                     val no_execs =
   493                       iterate_entries_after common
   494                         (fn ((_, id0), exec0) => fn res =>
   495                           if is_none exec0 then NONE
   496                           else if exists (fn (_, ({exec_id = id, ...}, _)) => id0 = id) updated_execs
   497                           then SOME res
   498                           else SOME (id0 :: res)) node0 [];
   499 
   500                     val last_exec =
   501                       if command_id' = Document_ID.none then NONE else SOME command_id';
   502                     val result =
   503                       if is_some (after_entry node last_exec) then NONE
   504                       else SOME eval';
   505 
   506                     val node' = node
   507                       |> fold reset_entry no_execs
   508                       |> fold (fn (id, exec) => update_entry id (SOME exec)) updated_execs
   509                       |> entries_stable (null updated_execs)
   510                       |> set_result result;
   511                     val updated_node =
   512                       if null no_execs andalso null updated_execs then NONE
   513                       else SOME (name, node');
   514                     val changed_result = not (null no_execs) orelse not (null new_execs);
   515                   in ((no_execs, updated_execs, updated_node, changed_result), node') end
   516                 else (([], [], NONE, false), node)
   517               end))
   518       |> Future.joins |> map #1);
   519 
   520     val command_execs =
   521       map (rpair []) (maps #1 updated) @
   522       map (fn (command_id, exec) => (command_id, Command.exec_ids exec)) (maps #2 updated);
   523     val updated_nodes = map_filter #3 updated;
   524 
   525     val state' = state
   526       |> define_version new_version_id (fold put_node updated_nodes new_version);
   527   in (command_execs, state') end;
   528 
   529 end;
   530 
   531 
   532 
   533 (** global state **)
   534 
   535 val global_state = Synchronized.var "Document.global_state" init_state;
   536 
   537 fun state () = Synchronized.value global_state;
   538 val change_state = Synchronized.change global_state;
   539 
   540 end;
   541