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