src/Pure/PIDE/document.ML
author wenzelm
Thu Sep 01 23:08:42 2011 +0200 (2011-09-01)
changeset 44643 9987ae55e17b
parent 44614 466ea227e00d
child 44644 317e4962dd0f
permissions -rw-r--r--
amended last_common, if that happens to the very last entry (important to load HOL/Auth, for example);
clarified touch_node: reset result explicitly;
     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 -> state -> state
    28   val join_commands: state -> state
    29   val cancel_execution: state -> Future.task list
    30   val update_perspective: version_id -> version_id -> string -> command_id list -> 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 execute: version_id -> 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 fun iterate_entries start f = Entries.iterate start f o get_entries;
   117 
   118 fun get_last_exec (Node {last_exec, ...}) = last_exec;
   119 fun set_last_exec last_exec =
   120   map_node (fn (touched, header, perspective, entries, _, result) =>
   121     (touched, header, perspective, entries, last_exec, result));
   122 
   123 fun get_theory pos (Node {result, ...}) = Toplevel.end_theory pos (Lazy.force result);
   124 fun set_result result =
   125   map_node (fn (touched, header, perspective, entries, last_exec, _) =>
   126     (touched, header, perspective, entries, last_exec, result));
   127 
   128 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   129 fun default_node name = Graph.default_node (name, empty_node);
   130 fun update_node name f = default_node name #> Graph.map_node name f;
   131 
   132 
   133 (* node edits and associated executions *)
   134 
   135 datatype node_edit =
   136   Clear |
   137   Edits of (command_id option * command_id option) list |
   138   Header of node_header |
   139   Perspective of command_id list;
   140 
   141 type edit = string * node_edit;
   142 
   143 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   144 
   145 fun lookup_entry (Node {entries, ...}) id =
   146   (case Entries.lookup entries id of
   147     NONE => NONE
   148   | SOME (exec, _) => exec);
   149 
   150 fun the_entry (Node {entries, ...}) id =
   151   (case Entries.lookup entries id of
   152     NONE => err_undef "command entry" id
   153   | SOME (exec, _) => exec);
   154 
   155 fun the_default_entry node (SOME id) = the_default no_id (the_entry node id)
   156   | the_default_entry _ NONE = no_id;
   157 
   158 fun update_entry id exec =
   159   map_entries (Entries.update (id, exec));
   160 
   161 fun reset_entry id node =
   162   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   163 
   164 fun reset_after id entries =
   165   (case Entries.get_after entries id of
   166     NONE => entries
   167   | SOME next => Entries.update (next, NONE) entries);
   168 
   169 val edit_node = map_entries o fold
   170   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   171     | (id, NONE) => Entries.delete_after id #> reset_after id);
   172 
   173 
   174 (* version operations *)
   175 
   176 val empty_version = Version Graph.empty;
   177 
   178 fun nodes_of (Version nodes) = nodes;
   179 val node_of = get_node o nodes_of;
   180 
   181 local
   182 
   183 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   184 
   185 fun touch_node name nodes =
   186   fold (fn desc =>
   187       update_node desc
   188         (set_touched true #>
   189           desc <> name ? (map_entries (reset_after NONE) #> set_result no_result)))
   190     (Graph.all_succs nodes [name]) nodes;
   191 
   192 in
   193 
   194 fun edit_nodes (name, node_edit) (Version nodes) =
   195   Version
   196     (case node_edit of
   197       Clear =>
   198         nodes
   199         |> update_node name clear_node
   200         |> touch_node name
   201     | Edits edits =>
   202         nodes
   203         |> update_node name (edit_node edits)
   204         |> touch_node name
   205     | Header header =>
   206         let
   207           val parents = (case header of Exn.Res (_, parents, _) => parents | _ => []);
   208           val nodes1 = nodes
   209             |> default_node name
   210             |> fold default_node parents;
   211           val nodes2 = nodes1
   212             |> Graph.Keys.fold
   213                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   214           val (header', nodes3) =
   215             (header, Graph.add_deps_acyclic (name, parents) nodes2)
   216               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   217         in Graph.map_node name (set_header header') nodes3 end
   218         |> touch_node name
   219     | Perspective perspective =>
   220         update_node name (set_perspective perspective) nodes);
   221 
   222 end;
   223 
   224 fun put_node (name, node) (Version nodes) =
   225   Version (update_node name (K node) nodes);
   226 
   227 end;
   228 
   229 
   230 
   231 (** global state -- document structure and execution process **)
   232 
   233 abstype state = State of
   234  {versions: version Inttab.table,  (*version_id -> document content*)
   235   commands:
   236     Toplevel.transition future Inttab.table *  (*command_id -> transition (future parsing)*)
   237     Toplevel.transition future list,  (*recent commands to be joined*)
   238   execs: (command_id * (Toplevel.state * unit lazy) lazy) Inttab.table,
   239     (*exec_id -> command_id with eval/print process*)
   240   execution: Future.group}  (*global execution process*)
   241 with
   242 
   243 fun make_state (versions, commands, execs, execution) =
   244   State {versions = versions, commands = commands, execs = execs, execution = execution};
   245 
   246 fun map_state f (State {versions, commands, execs, execution}) =
   247   make_state (f (versions, commands, execs, execution));
   248 
   249 val init_state =
   250   make_state (Inttab.make [(no_id, empty_version)],
   251     (Inttab.make [(no_id, Future.value Toplevel.empty)], []),
   252     Inttab.make [(no_id, (no_id, Lazy.value (Toplevel.toplevel, no_print)))],
   253     Future.new_group NONE);
   254 
   255 
   256 (* document versions *)
   257 
   258 fun define_version (id: version_id) version =
   259   map_state (fn (versions, commands, execs, execution) =>
   260     let val versions' = Inttab.update_new (id, version) versions
   261       handle Inttab.DUP dup => err_dup "document version" dup
   262     in (versions', commands, execs, execution) end);
   263 
   264 fun the_version (State {versions, ...}) (id: version_id) =
   265   (case Inttab.lookup versions id of
   266     NONE => err_undef "document version" id
   267   | SOME version => version);
   268 
   269 
   270 (* commands *)
   271 
   272 fun define_command (id: command_id) text =
   273   map_state (fn (versions, (commands, recent), execs, execution) =>
   274     let
   275       val id_string = print_id id;
   276       val tr =
   277         Future.fork_pri 2 (fn () =>
   278           Position.setmp_thread_data (Position.id_only id_string)
   279             (fn () => Outer_Syntax.read_command (Position.id id_string) text) ());
   280       val commands' =
   281         Inttab.update_new (id, tr) commands
   282           handle Inttab.DUP dup => err_dup "command" dup;
   283     in (versions, (commands', tr :: recent), execs, execution) end);
   284 
   285 fun the_command (State {commands, ...}) (id: command_id) =
   286   (case Inttab.lookup (#1 commands) id of
   287     NONE => err_undef "command" id
   288   | SOME tr => tr);
   289 
   290 val join_commands =
   291     map_state (fn (versions, (commands, recent), execs, execution) =>
   292       (Future.join_results recent; (versions, (commands, []), execs, execution)));
   293 
   294 
   295 (* command executions *)
   296 
   297 fun define_exec (exec_id, exec) =
   298   map_state (fn (versions, commands, execs, execution) =>
   299     let val execs' = Inttab.update_new (exec_id, exec) execs
   300       handle Inttab.DUP dup => err_dup "command execution" dup
   301     in (versions, commands, execs', execution) end);
   302 
   303 fun the_exec (State {execs, ...}) exec_id =
   304   (case Inttab.lookup execs exec_id of
   305     NONE => err_undef "command execution" exec_id
   306   | SOME exec => exec);
   307 
   308 
   309 (* document execution *)
   310 
   311 fun cancel_execution (State {execution, ...}) = Future.cancel_group execution;
   312 
   313 end;
   314 
   315 
   316 
   317 (* toplevel transactions *)
   318 
   319 local
   320 
   321 fun timing tr t =
   322   if Timing.is_relevant t then Toplevel.status tr (Markup.timing t) else ();
   323 
   324 fun proof_status tr st =
   325   (case try Toplevel.proof_of st of
   326     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   327   | NONE => ());
   328 
   329 fun print_state tr st =
   330   (Lazy.lazy o Toplevel.setmp_thread_position tr)
   331     (fn () => Toplevel.print_state false st);
   332 
   333 fun run int tr st =
   334   (case Toplevel.transition int tr st of
   335     SOME (st', NONE) => ([], SOME st')
   336   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages exn, NONE)
   337   | NONE => ([(serial (), ML_Compiler.exn_message Runtime.TERMINATE)], NONE));
   338 
   339 in
   340 
   341 fun run_command tr st =
   342   let
   343     val is_init = Toplevel.is_init tr;
   344     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   345     val do_print = not is_init andalso (Toplevel.print_of tr orelse is_proof);
   346 
   347     val _ = Multithreading.interrupted ();
   348     val _ = Toplevel.status tr Markup.forked;
   349     val start = Timing.start ();
   350     val (errs, result) =
   351       if Toplevel.is_toplevel st andalso not is_init then ([], SOME st)
   352       else run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   353     val _ = timing tr (Timing.result start);
   354     val _ = Toplevel.status tr Markup.joined;
   355     val _ = List.app (Toplevel.error_msg tr) errs;
   356   in
   357     (case result of
   358       NONE =>
   359        (if null errs then Exn.interrupt () else ();
   360         Toplevel.status tr Markup.failed;
   361         (st, no_print))
   362     | SOME st' =>
   363        (Toplevel.status tr Markup.finished;
   364         proof_status tr st';
   365         (st', if do_print then print_state tr st' else no_print)))
   366   end;
   367 
   368 end;
   369 
   370 
   371 
   372 
   373 (** update **)
   374 
   375 (* perspective *)
   376 
   377 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   378   let
   379     val old_version = the_version state old_id;
   380     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   381     val new_version = edit_nodes (name, Perspective perspective) old_version;
   382   in define_version new_id new_version state end;
   383 
   384 
   385 (* edits *)
   386 
   387 local
   388 
   389 fun last_common last_visible node0 node =
   390   let
   391     fun get_common ((prev, id), exec) (found, (_, visible)) =
   392       if found then NONE
   393       else
   394         let val found' = is_none exec orelse exec <> lookup_entry node0 id
   395         in SOME (found', (prev, visible andalso prev <> last_visible)) end;
   396     val (found, (common, visible)) = iterate_entries NONE get_common node (false, (NONE, true));
   397     val common' = if found then common else Entries.get_after (get_entries node) common;
   398     val visible' = visible andalso common' <> last_visible;
   399   in (common', visible') end;
   400 
   401 fun new_exec state init command_id' (execs, exec) =
   402   let
   403     val command' = the_command state command_id';
   404     val exec_id' = new_id ();
   405     val exec' =
   406       snd exec |> Lazy.map (fn (st, _) =>
   407         let val tr =
   408           Future.join command'
   409           |> Toplevel.modify_init init
   410           |> Toplevel.put_id (print_id exec_id');
   411         in run_command tr st end)
   412       |> pair command_id';
   413   in ((exec_id', exec') :: execs, exec') end;
   414 
   415 fun make_required nodes =
   416   let
   417     val all_visible =
   418       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   419       |> Graph.all_preds nodes;
   420     val required =
   421       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   422         all_visible Symtab.empty;
   423   in Symtab.defined required end;
   424 
   425 fun init_theory deps name node =
   426   let
   427     val (thy_name, imports, uses) = Exn.release (get_header node);
   428     (* FIXME provide files via Scala layer *)
   429     val (dir, files) =
   430       if ML_System.platform_is_cygwin then (Path.current, [])
   431       else (Path.dir (Path.explode name), map (apfst Path.explode) uses);
   432 
   433     val parents =
   434       imports |> map (fn import =>
   435         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   436           SOME thy => thy
   437         | NONE =>
   438             get_theory (Position.file_only import)
   439               (snd (Future.join (the (AList.lookup (op =) deps import))))));
   440   in Thy_Load.begin_theory dir thy_name imports files parents 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 not (is_touched node orelse is_required name)
   457           then Future.value (([], [], []), node)
   458           else
   459             let
   460               val node0 = node_of old_version name;
   461               fun init () = init_theory deps name node;
   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 = #2 (get_perspective node);
   470                     val (common, visible) = last_common last_visible node0 node;
   471                     val common_exec = the_exec state (the_default_entry node common);
   472 
   473                     val (execs, exec) = ([], common_exec) |>
   474                       (visible orelse required) ?
   475                         iterate_entries (after_entry node common)
   476                           (fn ((prev, id), _) => fn res =>
   477                             if not required andalso prev = last_visible then NONE
   478                             else SOME (new_exec state init id res)) node;
   479 
   480                     val no_execs =
   481                       iterate_entries (after_entry node0 common)
   482                         (fn ((_, id0), exec0) => fn res =>
   483                           if is_none exec0 then NONE
   484                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   485                           else SOME (id0 :: res)) node0 [];
   486 
   487                     val last_exec = if #1 exec = no_id then NONE else SOME (#1 exec);
   488                     val result =
   489                       if is_some (after_entry node last_exec) then no_result
   490                       else Lazy.map #1 (#2 exec);
   491 
   492                     val node' = node
   493                       |> fold reset_entry no_execs
   494                       |> fold (fn (exec_id, (id, _)) => update_entry id (SOME exec_id)) execs
   495                       |> set_last_exec last_exec
   496                       |> set_result result
   497                       |> set_touched false;
   498                   in ((no_execs, execs, [(name, node')]), node') end)
   499             end)
   500       |> Future.joins |> map #1;
   501 
   502     val command_execs =
   503       map (rpair NONE) (maps #1 updated) @
   504       map (fn (exec_id, (command_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   505     val updated_nodes = maps #3 updated;
   506     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   507 
   508     val state' = state
   509       |> fold (fold define_exec o #2) updated
   510       |> define_version new_id (fold put_node updated_nodes new_version);
   511   in ((command_execs, last_execs), state') end;
   512 
   513 end;
   514 
   515 
   516 (* execute *)
   517 
   518 fun execute version_id state =
   519   state |> map_state (fn (versions, commands, execs, _) =>
   520     let
   521       val version = the_version state version_id;
   522 
   523       fun force_exec _ NONE = ()
   524         | force_exec node (SOME exec_id) =
   525             let
   526               val (command_id, exec) = the_exec state exec_id;
   527               val (_, print) = Lazy.force exec;
   528               val _ =
   529                 if #1 (get_perspective node) command_id
   530                 then ignore (Lazy.future Future.default_params print)
   531                 else ();
   532             in () end;
   533 
   534       val execution = Future.new_group NONE;
   535       val _ =
   536         nodes_of version |> Graph.schedule
   537           (fn deps => fn (name, node) =>
   538             (singleton o Future.forks)
   539               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME execution)),
   540                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   541               (iterate_entries NONE (fn (_, exec) => fn () => SOME (force_exec node exec)) node));
   542 
   543     in (versions, commands, execs, execution) end);
   544 
   545 
   546 
   547 (** global state **)
   548 
   549 val global_state = Synchronized.var "Document" init_state;
   550 
   551 fun state () = Synchronized.value global_state;
   552 val change_state = Synchronized.change global_state;
   553 
   554 end;
   555