src/Pure/PIDE/document.ML
author wenzelm
Sat Sep 03 18:08:09 2011 +0200 (2011-09-03)
changeset 44673 2fa51ac191bc
parent 44660 90bab3febb6c
child 44674 bad4f9158c80
permissions -rw-r--r--
Document.remove_versions on ML side;
     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 * string list * (string * bool) list) 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 * string list * (string * bool) list) 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 abstype node = Node of
    66  {touched: bool,
    67   header: node_header,
    68   perspective: perspective,
    69   entries: exec_id option Entries.T,  (*command entries with excecutions*)
    70   last_exec: command_id option,  (*last command with exec state assignment*)
    71   result: Toplevel.state lazy}
    72 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    73 with
    74 
    75 fun make_node (touched, header, perspective, entries, last_exec, result) =
    76   Node {touched = touched, header = header, perspective = perspective,
    77     entries = entries, last_exec = last_exec, result = result};
    78 
    79 fun map_node f (Node {touched, header, perspective, entries, last_exec, result}) =
    80   make_node (f (touched, header, perspective, entries, last_exec, result));
    81 
    82 fun make_perspective command_ids : perspective =
    83   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    84 
    85 val no_header = Exn.Exn (ERROR "Bad theory header");
    86 val no_perspective = make_perspective [];
    87 val no_print = Lazy.value ();
    88 val no_result = Lazy.value Toplevel.toplevel;
    89 
    90 val empty_node = make_node (false, no_header, no_perspective, Entries.empty, NONE, no_result);
    91 val clear_node = map_node (fn (_, header, _, _, _, _) =>
    92   (false, header, no_perspective, Entries.empty, NONE, no_result));
    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, last_exec, result) =>
   100     (touched, header, perspective, entries, last_exec, result));
   101 
   102 fun get_header (Node {header, ...}) = header;
   103 fun set_header header =
   104   map_node (fn (touched, _, perspective, entries, last_exec, result) =>
   105     (touched, header, perspective, entries, last_exec, result));
   106 
   107 fun get_perspective (Node {perspective, ...}) = perspective;
   108 fun set_perspective ids =
   109   map_node (fn (touched, header, _, entries, last_exec, result) =>
   110     (touched, header, make_perspective ids, entries, last_exec, result));
   111 
   112 fun map_entries f =
   113   map_node (fn (touched, header, perspective, entries, last_exec, result) =>
   114     (touched, header, perspective, f entries, last_exec, result));
   115 fun get_entries (Node {entries, ...}) = entries;
   116 
   117 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   118 fun iterate_entries_after start f (Node {entries, ...}) =
   119   (case Entries.get_after entries start of
   120     NONE => I
   121   | SOME id => Entries.iterate (SOME id) f entries);
   122 
   123 fun get_last_exec (Node {last_exec, ...}) = last_exec;
   124 fun set_last_exec last_exec =
   125   map_node (fn (touched, header, perspective, entries, _, result) =>
   126     (touched, header, perspective, entries, last_exec, result));
   127 
   128 fun get_theory pos (Node {result, ...}) = Toplevel.end_theory pos (Lazy.force result);
   129 fun set_result result =
   130   map_node (fn (touched, header, perspective, entries, last_exec, _) =>
   131     (touched, header, perspective, entries, last_exec, result));
   132 
   133 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   134 fun default_node name = Graph.default_node (name, empty_node);
   135 fun update_node name f = default_node name #> Graph.map_node name f;
   136 
   137 
   138 (* node edits and associated executions *)
   139 
   140 datatype node_edit =
   141   Clear |
   142   Edits of (command_id option * command_id option) list |
   143   Header of node_header |
   144   Perspective of command_id list;
   145 
   146 type edit = string * node_edit;
   147 
   148 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   149 
   150 fun lookup_entry (Node {entries, ...}) id =
   151   (case Entries.lookup entries id of
   152     NONE => NONE
   153   | SOME (exec, _) => exec);
   154 
   155 fun the_entry (Node {entries, ...}) id =
   156   (case Entries.lookup entries id of
   157     NONE => err_undef "command entry" id
   158   | SOME (exec, _) => exec);
   159 
   160 fun the_default_entry node (SOME id) = the_default no_id (the_entry node id)
   161   | the_default_entry _ NONE = no_id;
   162 
   163 fun update_entry id exec =
   164   map_entries (Entries.update (id, exec));
   165 
   166 fun reset_entry id node =
   167   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   168 
   169 fun reset_after id entries =
   170   (case Entries.get_after entries id of
   171     NONE => entries
   172   | SOME next => Entries.update (next, NONE) entries);
   173 
   174 val edit_node = map_entries o fold
   175   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   176     | (id, NONE) => Entries.delete_after id #> reset_after id);
   177 
   178 
   179 (* version operations *)
   180 
   181 val empty_version = Version Graph.empty;
   182 
   183 fun nodes_of (Version nodes) = nodes;
   184 val node_of = get_node o nodes_of;
   185 
   186 local
   187 
   188 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   189 
   190 fun touch_node name nodes =
   191   fold (fn desc =>
   192       update_node desc
   193         (set_touched true #>
   194           desc <> name ? (map_entries (reset_after NONE) #> set_result no_result)))
   195     (Graph.all_succs nodes [name]) nodes;
   196 
   197 in
   198 
   199 fun edit_nodes (name, node_edit) (Version nodes) =
   200   Version
   201     (case node_edit of
   202       Clear =>
   203         nodes
   204         |> update_node name clear_node
   205         |> touch_node name
   206     | Edits edits =>
   207         nodes
   208         |> update_node name (edit_node edits)
   209         |> touch_node name
   210     | Header header =>
   211         let
   212           val parents = (case header of Exn.Res (_, parents, _) => parents | _ => []);
   213           val nodes1 = nodes
   214             |> default_node name
   215             |> fold default_node parents;
   216           val nodes2 = nodes1
   217             |> Graph.Keys.fold
   218                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   219           val (header', nodes3) =
   220             (header, Graph.add_deps_acyclic (name, parents) nodes2)
   221               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   222         in Graph.map_node name (set_header header') nodes3 end
   223         |> touch_node name
   224     | Perspective perspective =>
   225         update_node name (set_perspective perspective) nodes);
   226 
   227 end;
   228 
   229 fun put_node (name, node) (Version nodes) =
   230   Version (update_node name (K node) nodes);
   231 
   232 end;
   233 
   234 
   235 
   236 (** global state -- document structure and execution process **)
   237 
   238 abstype state = State of
   239  {versions: version Inttab.table,  (*version_id -> document content*)
   240   commands: (string * Toplevel.transition future) Inttab.table,  (*command_id -> name * transition*)
   241   execs: (command_id * (Toplevel.state * unit lazy) lazy) Inttab.table,
   242     (*exec_id -> command_id with eval/print process*)
   243   execution: version_id * Future.group}  (*current execution process*)
   244 with
   245 
   246 fun make_state (versions, commands, execs, execution) =
   247   State {versions = versions, commands = commands, execs = execs, execution = execution};
   248 
   249 fun map_state f (State {versions, commands, execs, execution}) =
   250   make_state (f (versions, commands, execs, execution));
   251 
   252 val empty_commands =
   253   Inttab.make [(no_id, (Toplevel.name_of Toplevel.empty, Future.value Toplevel.empty))];
   254 val empty_execs = Inttab.make [(no_id, (no_id, Lazy.value (Toplevel.toplevel, no_print)))];
   255 val empty_execution = (no_id, Future.new_group NONE);
   256 
   257 val init_state =
   258   make_state (Inttab.make [(no_id, empty_version)], empty_commands, empty_execs, empty_execution);
   259 
   260 
   261 (* document versions *)
   262 
   263 fun define_version (id: version_id) version =
   264   map_state (fn (versions, commands, execs, execution) =>
   265     let val versions' = Inttab.update_new (id, version) versions
   266       handle Inttab.DUP dup => err_dup "document version" dup
   267     in (versions', commands, execs, execution) end);
   268 
   269 fun the_version (State {versions, ...}) (id: version_id) =
   270   (case Inttab.lookup versions id of
   271     NONE => err_undef "document version" id
   272   | SOME version => version);
   273 
   274 fun delete_version (id: version_id) versions = Inttab.delete id versions
   275   handle Inttab.UNDEF _ => err_undef "document version" id;
   276 
   277 
   278 (* commands *)
   279 
   280 fun define_command (id: command_id) name text =
   281   map_state (fn (versions, commands, execs, execution) =>
   282     let
   283       val id_string = print_id id;
   284       val future =
   285         (singleton o Future.forks)
   286           {name = "Document.define_command", group = SOME (Future.new_group NONE),
   287             deps = [], pri = ~1, interrupts = false}
   288           (fn () =>
   289             Position.setmp_thread_data (Position.id_only id_string)
   290               (fn () => Outer_Syntax.read_command (Position.id id_string) text) ());
   291       val commands' =
   292         Inttab.update_new (id, (name, future)) commands
   293           handle Inttab.DUP dup => err_dup "command" dup;
   294     in (versions, commands', execs, execution) end);
   295 
   296 fun the_command (State {commands, ...}) (id: command_id) =
   297   (case Inttab.lookup commands id of
   298     NONE => err_undef "command" id
   299   | SOME command => command);
   300 
   301 
   302 (* command executions *)
   303 
   304 fun define_exec (exec_id, exec) =
   305   map_state (fn (versions, commands, execs, execution) =>
   306     let val execs' = Inttab.update_new (exec_id, exec) execs
   307       handle Inttab.DUP dup => err_dup "command execution" dup
   308     in (versions, commands, execs', execution) end);
   309 
   310 fun the_exec (State {execs, ...}) exec_id =
   311   (case Inttab.lookup execs exec_id of
   312     NONE => err_undef "command execution" exec_id
   313   | SOME exec => exec);
   314 
   315 
   316 (* document execution *)
   317 
   318 fun cancel_execution (State {execution, ...}) = Future.cancel_group (#2 execution);
   319 
   320 end;
   321 
   322 
   323 
   324 (* toplevel transactions *)
   325 
   326 local
   327 
   328 fun timing tr t =
   329   if Timing.is_relevant t then Toplevel.status tr (Markup.timing t) else ();
   330 
   331 fun proof_status tr st =
   332   (case try Toplevel.proof_of st of
   333     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   334   | NONE => ());
   335 
   336 fun print_state tr st =
   337   (Lazy.lazy o Toplevel.setmp_thread_position tr)
   338     (fn () => Toplevel.print_state false st);
   339 
   340 fun run int tr st =
   341   (case Toplevel.transition int tr st of
   342     SOME (st', NONE) => ([], SOME st')
   343   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages exn, NONE)
   344   | NONE => ([(serial (), ML_Compiler.exn_message Runtime.TERMINATE)], NONE));
   345 
   346 in
   347 
   348 fun run_command tr st =
   349   let
   350     val is_init = Toplevel.is_init tr;
   351     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   352     val do_print = not is_init andalso (Toplevel.print_of tr orelse is_proof);
   353 
   354     val _ = Multithreading.interrupted ();
   355     val _ = Toplevel.status tr Markup.forked;
   356     val start = Timing.start ();
   357     val (errs, result) = run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   358     val _ = timing tr (Timing.result start);
   359     val _ = Toplevel.status tr Markup.joined;
   360     val _ = List.app (Toplevel.error_msg tr) errs;
   361   in
   362     (case result of
   363       NONE =>
   364        (if null errs then Exn.interrupt () else ();
   365         Toplevel.status tr Markup.failed;
   366         (st, no_print))
   367     | SOME st' =>
   368        (Toplevel.status tr Markup.finished;
   369         proof_status tr st';
   370         (st', if do_print then print_state tr st' else no_print)))
   371   end;
   372 
   373 end;
   374 
   375 
   376 
   377 
   378 (** update **)
   379 
   380 (* perspective *)
   381 
   382 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   383   let
   384     val old_version = the_version state old_id;
   385     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   386     val new_version = edit_nodes (name, Perspective perspective) old_version;
   387   in define_version new_id new_version state end;
   388 
   389 
   390 (* edits *)
   391 
   392 local
   393 
   394 fun last_common state last_visible node0 node =
   395   let
   396     fun update_flags prev (visible, initial) =
   397       let
   398         val visible' = visible andalso prev <> last_visible;
   399         val initial' = initial andalso
   400           (case prev of
   401             NONE => true
   402           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   403       in (visible', initial') end;
   404     fun get_common ((prev, id), exec) (found, (_, flags)) =
   405       if found then NONE
   406       else
   407         let val found' = is_none exec orelse exec <> lookup_entry node0 id
   408         in SOME (found', (prev, update_flags prev flags)) end;
   409     val (found, (common, flags)) =
   410       iterate_entries get_common node (false, (NONE, (true, true)));
   411   in
   412     if found then (common, flags)
   413     else
   414       let val last = Entries.get_after (get_entries node) common
   415       in (last, update_flags last flags) end
   416   end;
   417 
   418 fun illegal_init () = error "Illegal theory header after end of theory";
   419 
   420 fun new_exec state bad_init command_id' (execs, exec, init) =
   421   if bad_init andalso is_none init then NONE
   422   else
   423     let
   424       val (name, tr0) = the_command state command_id' ||> Future.join;
   425       val (modify_init, init') =
   426         if Keyword.is_theory_begin name then
   427           (Toplevel.modify_init (the_default illegal_init init), NONE)
   428         else (I, init);
   429       val exec_id' = new_id ();
   430       val tr = tr0
   431         |> modify_init
   432         |> Toplevel.put_id (print_id exec_id');
   433       val exec' = (command_id', Lazy.map (fn (st, _) => run_command tr st) (snd exec));
   434     in SOME ((exec_id', exec') :: execs, exec', init') end;
   435 
   436 fun make_required nodes =
   437   let
   438     val all_visible =
   439       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   440       |> Graph.all_preds nodes;
   441     val required =
   442       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   443         all_visible Symtab.empty;
   444   in Symtab.defined required end;
   445 
   446 fun check_theory nodes name =
   447   is_some (Thy_Info.lookup_theory name) orelse  (* FIXME more robust!? *)
   448   is_some (Exn.get_res (get_header (get_node nodes name)));
   449 
   450 fun init_theory deps name node =
   451   let
   452     val (thy_name, imports, uses) = Exn.release (get_header node);
   453     (* FIXME provide files via Scala layer *)
   454     val (dir, files) =
   455       if ML_System.platform_is_cygwin then (Path.current, [])
   456       else (Path.dir (Path.explode name), map (apfst Path.explode) uses);
   457 
   458     val parents =
   459       imports |> map (fn import =>
   460         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   461           SOME thy => thy
   462         | NONE =>
   463             get_theory (Position.file_only import)
   464               (snd (Future.join (the (AList.lookup (op =) deps import))))));
   465   in Thy_Load.begin_theory dir thy_name imports files parents end;
   466 
   467 in
   468 
   469 fun update (old_id: version_id) (new_id: version_id) edits state =
   470   let
   471     val old_version = the_version state old_id;
   472     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   473     val new_version = fold edit_nodes edits old_version;
   474 
   475     val nodes = nodes_of new_version;
   476     val is_required = make_required nodes;
   477 
   478     val updated =
   479       nodes |> Graph.schedule
   480         (fn deps => fn (name, node) =>
   481           if not (is_touched node orelse is_required name)
   482           then Future.value (([], [], []), node)
   483           else
   484             let
   485               val node0 = node_of old_version name;
   486               fun init () = init_theory deps name node;
   487               val bad_init =
   488                 not (check_theory nodes name andalso forall (check_theory nodes o #1) deps);
   489             in
   490               (singleton o Future.forks)
   491                 {name = "Document.update", group = NONE,
   492                   deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   493                 (fn () =>
   494                   let
   495                     val required = is_required name;
   496                     val last_visible = #2 (get_perspective node);
   497                     val (common, (visible, initial)) = last_common state last_visible node0 node;
   498                     val common_exec = the_exec state (the_default_entry node common);
   499 
   500                     val (execs, exec, _) =
   501                       ([], common_exec, if initial then SOME init else NONE) |>
   502                       (visible orelse required) ?
   503                         iterate_entries_after common
   504                           (fn ((prev, id), _) => fn res =>
   505                             if not required andalso prev = last_visible then NONE
   506                             else new_exec state bad_init id res) node;
   507 
   508                     val no_execs =
   509                       iterate_entries_after common
   510                         (fn ((_, id0), exec0) => fn res =>
   511                           if is_none exec0 then NONE
   512                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   513                           else SOME (id0 :: res)) node0 [];
   514 
   515                     val last_exec = if #1 exec = no_id then NONE else SOME (#1 exec);
   516                     val result =
   517                       if is_some (after_entry node last_exec) then no_result
   518                       else Lazy.map #1 (#2 exec);
   519 
   520                     val node' = node
   521                       |> fold reset_entry no_execs
   522                       |> fold (fn (exec_id, (id, _)) => update_entry id (SOME exec_id)) execs
   523                       |> set_last_exec last_exec
   524                       |> set_result result
   525                       |> set_touched false;
   526                   in ((no_execs, execs, [(name, node')]), node') end)
   527             end)
   528       |> Future.joins |> map #1;
   529 
   530     val command_execs =
   531       map (rpair NONE) (maps #1 updated) @
   532       map (fn (exec_id, (command_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   533     val updated_nodes = maps #3 updated;
   534     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   535 
   536     val state' = state
   537       |> fold (fold define_exec o #2) updated
   538       |> define_version new_id (fold put_node updated_nodes new_version);
   539   in ((command_execs, last_execs), state') end;
   540 
   541 end;
   542 
   543 
   544 (* execute *)
   545 
   546 fun execute version_id state =
   547   state |> map_state (fn (versions, commands, execs, _) =>
   548     let
   549       val version = the_version state version_id;
   550 
   551       fun force_exec _ NONE = ()
   552         | force_exec node (SOME exec_id) =
   553             let
   554               val (command_id, exec) = the_exec state exec_id;
   555               val (_, print) = Lazy.force exec;
   556               val _ =
   557                 if #1 (get_perspective node) command_id
   558                 then ignore (Lazy.future Future.default_params print)
   559                 else ();
   560             in () end;
   561 
   562       val group = Future.new_group NONE;
   563       val _ =
   564         nodes_of version |> Graph.schedule
   565           (fn deps => fn (name, node) =>
   566             (singleton o Future.forks)
   567               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   568                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   569               (iterate_entries (fn (_, exec) => fn () => SOME (force_exec node exec)) node));
   570 
   571     in (versions, commands, execs, (version_id, group)) end);
   572 
   573 
   574 (* remove versions *)
   575 
   576 fun remove_versions ids state = state |> map_state (fn (versions, _, _, execution) =>
   577   let
   578     val _ = member (op =) ids (#1 execution) andalso
   579       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   580 
   581     val versions' = fold delete_version ids versions;
   582     val (commands', execs') =
   583       (versions', (empty_commands, empty_execs)) |->
   584         Inttab.fold (fn (_, version) => nodes_of version |>
   585           Graph.fold (fn (_, (node, _)) => node |>
   586             iterate_entries (fn ((_, id), exec) => fn (commands, execs) =>
   587               let
   588                 val commands' = Inttab.insert (K true) (id, the_command state id) commands;
   589                 val execs' =
   590                   (case exec of
   591                     NONE => execs
   592                   | SOME exec_id => Inttab.insert (K true) (exec_id, the_exec state exec_id) execs);
   593               in SOME (commands', execs') end)));
   594   in (versions', commands', execs', execution) end);
   595 
   596 
   597 
   598 (** global state **)
   599 
   600 val global_state = Synchronized.var "Document" init_state;
   601 
   602 fun state () = Synchronized.value global_state;
   603 val change_state = Synchronized.change global_state;
   604 
   605 end;
   606