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