src/Pure/PIDE/document.ML
author wenzelm
Thu Apr 05 11:58:46 2012 +0200 (2012-04-05)
changeset 47341 00f6279bb67a
parent 47340 9bbf7fd96bcd
child 47342 7828c7b3c143
permissions -rw-r--r--
Command.memo including physical interrupts (unlike Lazy.lazy);
re-assign unstable exec, i.e. reset interrupted transaction;
node result as direct exec -- avoid potential interrupt instability of Lazy.map;
     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 cancel_execution: state -> Future.task list
    29   val update_perspective: version_id -> version_id -> string -> command_id list -> state -> state
    30   val update: version_id -> version_id -> edit list -> state ->
    31     ((command_id * exec_id option) list * (string * command_id option) list) * state
    32   val execute: version_id -> state -> 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 fun map_entries f =
   114   map_node (fn (touched, header, perspective, entries, last_exec, result) =>
   115     (touched, header, perspective, f entries, last_exec, result));
   116 fun get_entries (Node {entries, ...}) = entries;
   117 
   118 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   119 fun iterate_entries_after start f (Node {entries, ...}) =
   120   (case Entries.get_after entries start of
   121     NONE => I
   122   | SOME id => Entries.iterate (SOME id) f entries);
   123 
   124 fun get_last_exec (Node {last_exec, ...}) = last_exec;
   125 fun set_last_exec last_exec =
   126   map_node (fn (touched, header, perspective, entries, _, result) =>
   127     (touched, header, perspective, entries, last_exec, result));
   128 
   129 fun get_result (Node {result, ...}) = result;
   130 fun set_result result =
   131   map_node (fn (touched, header, perspective, entries, last_exec, _) =>
   132     (touched, header, perspective, entries, last_exec, result));
   133 
   134 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   135 fun default_node name = Graph.default_node (name, empty_node);
   136 fun update_node name f = default_node name #> Graph.map_node name f;
   137 
   138 
   139 (* node edits and associated executions *)
   140 
   141 datatype node_edit =
   142   Clear |
   143   Edits of (command_id option * command_id option) list |
   144   Header of node_header |
   145   Perspective of command_id list;
   146 
   147 type edit = string * node_edit;
   148 
   149 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   150 
   151 fun lookup_entry (Node {entries, ...}) id =
   152   (case Entries.lookup entries id of
   153     NONE => NONE
   154   | SOME (exec, _) => exec);
   155 
   156 fun the_entry (Node {entries, ...}) id =
   157   (case Entries.lookup entries id of
   158     NONE => err_undef "command entry" id
   159   | SOME (exec, _) => exec);
   160 
   161 fun the_default_entry node (SOME id) = (id, (the_default (no_id, no_exec) (the_entry node id)))
   162   | the_default_entry _ NONE = (no_id, (no_id, no_exec));
   163 
   164 fun update_entry id exec =
   165   map_entries (Entries.update (id, exec));
   166 
   167 fun reset_entry id node =
   168   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   169 
   170 fun reset_after id entries =
   171   (case Entries.get_after entries id of
   172     NONE => entries
   173   | SOME next => Entries.update (next, NONE) entries);
   174 
   175 val edit_node = map_entries o fold
   176   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   177     | (id, NONE) => Entries.delete_after id #> reset_after id);
   178 
   179 
   180 (* version operations *)
   181 
   182 val empty_version = Version Graph.empty;
   183 
   184 fun nodes_of (Version nodes) = nodes;
   185 val node_of = get_node o nodes_of;
   186 
   187 local
   188 
   189 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   190 
   191 fun touch_node name nodes =
   192   fold (fn desc =>
   193       update_node desc
   194         (set_touched true #>
   195           desc <> name ? (map_entries (reset_after NONE) #> set_result no_exec)))
   196     (Graph.all_succs nodes [name]) nodes;
   197 
   198 in
   199 
   200 fun edit_nodes (name, node_edit) (Version nodes) =
   201   Version
   202     (case node_edit of
   203       Clear =>
   204         nodes
   205         |> update_node name clear_node
   206         |> touch_node name
   207     | Edits edits =>
   208         nodes
   209         |> update_node name (edit_node edits)
   210         |> touch_node name
   211     | Header header =>
   212         let
   213           val imports = (case header of Exn.Res (_, {imports, ...}) => imports | _ => []);
   214           val header' =
   215             ((case header of Exn.Res (_, h) => Thy_Header.define_keywords h | _ => ()); header)
   216               handle exn as ERROR _ => Exn.Exn exn;
   217           val nodes1 = nodes
   218             |> default_node name
   219             |> fold default_node imports;
   220           val nodes2 = nodes1
   221             |> Graph.Keys.fold
   222                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   223           val (header'', nodes3) =
   224             (header', Graph.add_deps_acyclic (name, imports) nodes2)
   225               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   226         in Graph.map_node name (set_header header'') nodes3 end
   227         |> touch_node name
   228     | Perspective perspective =>
   229         update_node name (set_perspective perspective) nodes);
   230 
   231 end;
   232 
   233 fun put_node (name, node) (Version nodes) =
   234   Version (update_node name (K node) nodes);
   235 
   236 end;
   237 
   238 
   239 
   240 (** global state -- document structure and execution process **)
   241 
   242 abstype state = State of
   243  {versions: version Inttab.table,  (*version_id -> document content*)
   244   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> named span*)
   245   execution: version_id * Future.group}  (*current execution process*)
   246 with
   247 
   248 fun make_state (versions, commands, execution) =
   249   State {versions = versions, commands = commands, execution = execution};
   250 
   251 fun map_state f (State {versions, commands, execution}) =
   252   make_state (f (versions, commands, execution));
   253 
   254 val init_state =
   255   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty, (no_id, Future.new_group NONE));
   256 
   257 
   258 (* document versions *)
   259 
   260 fun define_version (id: version_id) version =
   261   map_state (fn (versions, commands, execution) =>
   262     let val versions' = Inttab.update_new (id, version) versions
   263       handle Inttab.DUP dup => err_dup "document version" dup
   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 span = Lazy.lazy (fn () => Command.parse_command (print_id id) text);
   281       val commands' =
   282         Inttab.update_new (id, (name, span)) commands
   283           handle Inttab.DUP dup => err_dup "command" dup;
   284     in (versions, commands', execution) end);
   285 
   286 fun the_command (State {commands, ...}) (id: command_id) =
   287   (case Inttab.lookup commands id of
   288     NONE => err_undef "command" id
   289   | SOME command => command);
   290 
   291 
   292 (* document execution *)
   293 
   294 fun cancel_execution (State {execution, ...}) = Future.cancel_group (#2 execution);
   295 
   296 end;
   297 
   298 
   299 
   300 (** update **)
   301 
   302 (* perspective *)
   303 
   304 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   305   let
   306     val old_version = the_version state old_id;
   307     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   308     val new_version = edit_nodes (name, Perspective perspective) old_version;
   309   in define_version new_id new_version state end;
   310 
   311 
   312 (* edits *)
   313 
   314 local
   315 
   316 fun make_required nodes =
   317   let
   318     val all_visible =
   319       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   320       |> Graph.all_preds nodes;
   321     val required =
   322       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   323         all_visible Symtab.empty;
   324   in Symtab.defined required end;
   325 
   326 fun init_theory deps node =
   327   let
   328     (* FIXME provide files via Scala layer, not master_dir *)
   329     val (dir, header) = Exn.release (get_header node);
   330     val master_dir =
   331       (case Url.explode dir of
   332         Url.File path => path
   333       | _ => Path.current);
   334     val parents =
   335       #imports header |> map (fn import =>
   336         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   337           SOME thy => thy
   338         | NONE =>
   339             Toplevel.end_theory (Position.file_only import)
   340               (fst (Exn.release (Command.memo_result
   341                 (get_result (snd (Future.join (the (AList.lookup (op =) deps import))))))))));
   342   in Thy_Load.begin_theory master_dir header parents end;
   343 
   344 fun check_theory nodes name =
   345   is_some (Thy_Info.lookup_theory name) orelse  (* FIXME more robust!? *)
   346   is_some (Exn.get_res (get_header (get_node nodes name)));
   347 
   348 fun last_common state last_visible node0 node =
   349   let
   350     fun update_flags prev (visible, initial) =
   351       let
   352         val visible' = visible andalso prev <> last_visible;
   353         val initial' = initial andalso
   354           (case prev of
   355             NONE => true
   356           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   357       in (visible', initial') end;
   358     fun get_common ((prev, id), opt_exec) (found, (_, flags)) =
   359       if found then NONE
   360       else
   361         let val found' =
   362           (case opt_exec of
   363             NONE => true
   364           | SOME (exec_id, exec) =>
   365               not (Command.memo_stable exec) orelse
   366               (case lookup_entry node0 id of
   367                 NONE => true
   368               | SOME (exec_id0, _) => exec_id <> exec_id0));
   369         in SOME (found', (prev, update_flags prev flags)) end;
   370     val (found, (common, flags)) =
   371       iterate_entries get_common node (false, (NONE, (true, true)));
   372   in
   373     if found then (common, flags)
   374     else
   375       let val last = Entries.get_after (get_entries node) common
   376       in (last, update_flags last flags) end
   377   end;
   378 
   379 fun illegal_init () = error "Illegal theory header after end of theory";
   380 
   381 fun new_exec state bad_init command_id' (execs, command_exec, init) =
   382   if bad_init andalso is_none init then NONE
   383   else
   384     let
   385       val (name, span) = the_command state command_id' ||> Lazy.force;
   386       val (modify_init, init') =
   387         if Keyword.is_theory_begin name then
   388           (Toplevel.modify_init (the_default illegal_init init), NONE)
   389         else (I, init);
   390       val exec_id' = new_id ();
   391       val exec_id'_string = print_id exec_id';
   392       val tr =
   393         Position.setmp_thread_data (Position.id_only exec_id'_string)
   394           (fn () =>
   395             #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   396             |> modify_init
   397             |> Toplevel.put_id exec_id'_string);
   398       val exec' = Command.memo (fn () =>
   399         let val (st, _) = Exn.release (Command.memo_result (snd (snd command_exec)));
   400         in Command.run_command (tr ()) st end);
   401       val command_exec' = (command_id', (exec_id', exec'));
   402     in SOME (command_exec' :: execs, command_exec', init') end;
   403 
   404 in
   405 
   406 fun update (old_id: version_id) (new_id: version_id) edits state =
   407   let
   408     val old_version = the_version state old_id;
   409     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   410     val new_version = fold edit_nodes edits old_version;
   411 
   412     val nodes = nodes_of new_version;
   413     val is_required = make_required nodes;
   414 
   415     val updated =
   416       nodes |> Graph.schedule
   417         (fn deps => fn (name, node) =>
   418           if is_touched node orelse is_required name then
   419             let
   420               val node0 = node_of old_version name;
   421               fun init () = init_theory deps node;
   422               val bad_init =
   423                 not (check_theory nodes name andalso forall (check_theory nodes o #1) deps);
   424             in
   425               (singleton o Future.forks)
   426                 {name = "Document.update", group = NONE,
   427                   deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   428                 (fn () =>
   429                   let
   430                     val required = is_required name;
   431                     val last_visible = #2 (get_perspective node);
   432                     val (common, (visible, initial)) = last_common state last_visible node0 node;
   433                     val common_command_exec = the_default_entry node common;
   434 
   435                     val (execs, (command_id, (_, exec)), _) =
   436                       ([], common_command_exec, if initial then SOME init else NONE) |>
   437                       (visible orelse required) ?
   438                         iterate_entries_after common
   439                           (fn ((prev, id), _) => fn res =>
   440                             if not required andalso prev = last_visible then NONE
   441                             else new_exec state bad_init id res) node;
   442 
   443                     val no_execs =
   444                       iterate_entries_after common
   445                         (fn ((_, id0), exec0) => fn res =>
   446                           if is_none exec0 then NONE
   447                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   448                           else SOME (id0 :: res)) node0 [];
   449 
   450                     val last_exec = if command_id = no_id then NONE else SOME command_id;
   451                     val result =
   452                       if is_some (after_entry node last_exec) then no_exec
   453                       else exec;
   454 
   455                     val node' = node
   456                       |> fold reset_entry no_execs
   457                       |> fold (fn (id, exec) => update_entry id (SOME exec)) execs
   458                       |> set_last_exec last_exec
   459                       |> set_result result
   460                       |> set_touched false;
   461                   in ((no_execs, execs, [(name, node')]), node') end)
   462             end
   463           else Future.value (([], [], []), node))
   464       |> Future.joins |> map #1;
   465 
   466     val command_execs =
   467       map (rpair NONE) (maps #1 updated) @
   468       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   469     val updated_nodes = maps #3 updated;
   470     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   471 
   472     val state' = state
   473       |> define_version new_id (fold put_node updated_nodes new_version);
   474   in ((command_execs, last_execs), state') end;
   475 
   476 end;
   477 
   478 
   479 (* execute *)
   480 
   481 fun execute version_id state =
   482   state |> map_state (fn (versions, commands, _) =>
   483     let
   484       val version = the_version state version_id;
   485 
   486       fun force_exec _ _ NONE = ()
   487         | force_exec node command_id (SOME (_, exec)) =
   488             let
   489               val (_, print) = Exn.release (Command.memo_result exec);
   490               val _ =
   491                 if #1 (get_perspective node) command_id
   492                 then ignore (Lazy.future Future.default_params print)
   493                 else ();
   494             in () end;
   495 
   496       val group = Future.new_group NONE;
   497       val _ =
   498         nodes_of version |> Graph.schedule
   499           (fn deps => fn (name, node) =>
   500             (singleton o Future.forks)
   501               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   502                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   503               (iterate_entries (fn ((_, id), exec) => fn () =>
   504                 SOME (force_exec node id exec)) node));
   505 
   506     in (versions, commands, (version_id, group)) end);
   507 
   508 
   509 (* remove versions *)
   510 
   511 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   512   let
   513     val _ = member (op =) ids (#1 execution) andalso
   514       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   515 
   516     val versions' = fold delete_version ids versions;
   517     val commands' =
   518       (versions', Inttab.empty) |->
   519         Inttab.fold (fn (_, version) => nodes_of version |>
   520           Graph.fold (fn (_, (node, _)) => node |>
   521             iterate_entries (fn ((_, id), _) =>
   522               SOME o Inttab.insert (K true) (id, the_command state id))));
   523   in (versions', commands', execution) end);
   524 
   525 
   526 
   527 (** global state **)
   528 
   529 val global_state = Synchronized.var "Document" init_state;
   530 
   531 fun state () = Synchronized.value global_state;
   532 val change_state = Synchronized.change global_state;
   533 
   534 end;
   535