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