src/Pure/PIDE/document.ML
author wenzelm
Sun Sep 02 14:02:05 2012 +0200 (2012-09-02 ago)
changeset 49064 bd6cc0b911a1
parent 49061 7449b804073b
child 49173 fa01a202399c
permissions -rw-r--r--
maintain stable state of node entries from last round -- bypass slightly different Thm.join_theory_proofs;
     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 * string list
    19   datatype node_edit =
    20     Clear |    (* FIXME unused !? *)
    21     Edits of (command_id option * command_id option) list |
    22     Deps 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 remove_versions: version_id list -> state -> state
    29   val discontinue_execution: state -> unit
    30   val cancel_execution: state -> unit
    31   val start_execution: state -> unit
    32   val timing: bool Unsynchronized.ref
    33   val update: version_id -> version_id -> edit list -> state ->
    34     (command_id * exec_id option) list * state
    35   val state: unit -> state
    36   val change_state: (state -> state) -> unit
    37 end;
    38 
    39 structure Document: DOCUMENT =
    40 struct
    41 
    42 (* unique identifiers *)
    43 
    44 type id = int;
    45 type version_id = id;
    46 type command_id = id;
    47 type exec_id = id;
    48 
    49 val no_id = 0;
    50 val new_id = Synchronized.counter ();
    51 
    52 val parse_id = Markup.parse_int;
    53 val print_id = Markup.print_int;
    54 
    55 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    56 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    57 
    58 
    59 
    60 (** document structure **)
    61 
    62 type node_header = string * Thy_Header.header * string list;
    63 type perspective = (command_id -> bool) * command_id option;
    64 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    65 
    66 type exec = ((Toplevel.state * bool) * unit lazy) Command.memo;  (*eval/print process*)
    67 val no_exec = Command.memo_value ((Toplevel.toplevel, false), Lazy.value ());
    68 
    69 abstype node = Node of
    70  {header: node_header,  (*master directory, theory header, errors*)
    71   perspective: perspective,  (*visible commands, last*)
    72   entries: (exec_id * exec) option Entries.T * bool,  (*command entries with excecutions, stable*)
    73   result: exec option}  (*result of last execution*)
    74 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    75 with
    76 
    77 fun make_node (header, perspective, entries, result) =
    78   Node {header = header, perspective = perspective, entries = entries, result = result};
    79 
    80 fun map_node f (Node {header, perspective, entries, result}) =
    81   make_node (f (header, perspective, entries, result));
    82 
    83 fun make_perspective command_ids : perspective =
    84   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    85 
    86 val no_header = ("", Thy_Header.make ("", Position.none) [] [] [], ["Bad theory header"]);
    87 val no_perspective = make_perspective [];
    88 
    89 val empty_node = make_node (no_header, no_perspective, (Entries.empty, true), NONE);
    90 val clear_node =
    91   map_node (fn (header, _, _, _) => (header, no_perspective, (Entries.empty, true), NONE));
    92 
    93 
    94 (* basic components *)
    95 
    96 fun set_header header =
    97   map_node (fn (_, perspective, entries, result) => (header, perspective, entries, result));
    98 
    99 fun get_header (Node {header = (master, header, errors), ...}) =
   100   if null errors then (master, header)
   101   else error (cat_lines errors);
   102 
   103 fun read_header node span =
   104   let
   105     val (dir, {name = (name, _), imports, keywords, uses}) = get_header node;
   106     val {name = (_, pos), imports = imports', ...} = Thy_Header.read_tokens span;
   107   in (dir, Thy_Header.make (name, pos) (map #1 imports ~~ map #2 imports') keywords uses) end;
   108 
   109 fun get_perspective (Node {perspective, ...}) = perspective;
   110 fun set_perspective ids =
   111   map_node (fn (header, _, entries, result) => (header, make_perspective ids, entries, result));
   112 
   113 val visible_command = #1 o get_perspective;
   114 val visible_last = #2 o get_perspective;
   115 val visible_node = is_some o visible_last
   116 
   117 fun map_entries f =
   118   map_node (fn (header, perspective, (entries, stable), result) =>
   119     (header, perspective, (f entries, stable), result));
   120 fun get_entries (Node {entries = (entries, _), ...}) = entries;
   121 
   122 fun entries_stable stable =
   123   map_node (fn (header, perspective, (entries, _), result) =>
   124     (header, perspective, (entries, stable), result));
   125 fun stable_entries (Node {entries = (_, stable), ...}) = stable;
   126 
   127 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   128 fun iterate_entries_after start f (Node {entries = (entries, _), ...}) =
   129   (case Entries.get_after entries start of
   130     NONE => I
   131   | SOME id => Entries.iterate (SOME id) f entries);
   132 
   133 fun get_result (Node {result, ...}) = result;
   134 fun set_result result =
   135   map_node (fn (header, perspective, entries, _) => (header, perspective, entries, result));
   136 
   137 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   138 fun default_node name = Graph.default_node (name, empty_node);
   139 fun update_node name f = default_node name #> Graph.map_node name f;
   140 
   141 
   142 (* node edits and associated executions *)
   143 
   144 datatype node_edit =
   145   Clear |
   146   Edits of (command_id option * command_id option) list |
   147   Deps of node_header |
   148   Perspective of command_id list;
   149 
   150 type edit = string * node_edit;
   151 
   152 val after_entry = Entries.get_after o get_entries;
   153 
   154 fun lookup_entry node id =
   155   (case Entries.lookup (get_entries node) id of
   156     NONE => NONE
   157   | SOME (exec, _) => exec);
   158 
   159 fun the_entry node id =
   160   (case Entries.lookup (get_entries node) id of
   161     NONE => err_undef "command entry" id
   162   | SOME (exec, _) => exec);
   163 
   164 fun the_default_entry node (SOME id) = (id, the_default (no_id, no_exec) (the_entry node id))
   165   | the_default_entry _ NONE = (no_id, (no_id, no_exec));
   166 
   167 fun update_entry id exec =
   168   map_entries (Entries.update (id, exec));
   169 
   170 fun reset_entry id node =
   171   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   172 
   173 fun reset_after id entries =
   174   (case Entries.get_after entries id of
   175     NONE => entries
   176   | SOME next => Entries.update (next, NONE) entries);
   177 
   178 val edit_node = map_entries o fold
   179   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   180     | (id, NONE) => Entries.delete_after id #> reset_after id);
   181 
   182 
   183 (* version operations *)
   184 
   185 val empty_version = Version Graph.empty;
   186 
   187 fun nodes_of (Version nodes) = nodes;
   188 val node_of = get_node o nodes_of;
   189 
   190 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   191 
   192 fun edit_nodes (name, node_edit) (Version nodes) =
   193   Version
   194     (case node_edit of
   195       Clear => update_node name clear_node nodes
   196     | Edits edits => update_node name (edit_node edits) nodes
   197     | Deps (master, header, errors) =>
   198         let
   199           val imports = map fst (#imports header);
   200           val errors1 =
   201             (Thy_Header.define_keywords header; errors)
   202               handle ERROR msg => errors @ [msg];
   203           val nodes1 = nodes
   204             |> default_node name
   205             |> fold default_node imports;
   206           val nodes2 = nodes1
   207             |> Graph.Keys.fold
   208                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   209           val (nodes3, errors2) =
   210             (Graph.add_deps_acyclic (name, imports) nodes2, errors1)
   211               handle Graph.CYCLES cs => (nodes2, errors1 @ map cycle_msg cs);
   212         in Graph.map_node name (set_header (master, header, errors2)) nodes3 end
   213     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   214 
   215 fun put_node (name, node) (Version nodes) =
   216   Version (update_node name (K node) nodes);
   217 
   218 end;
   219 
   220 
   221 
   222 (** main state -- document structure and execution process **)
   223 
   224 abstype state = State of
   225  {versions: version Inttab.table,  (*version_id -> document content*)
   226   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> named span*)
   227   execution: version_id * Future.group * bool Unsynchronized.ref}  (*current execution process*)
   228 with
   229 
   230 fun make_state (versions, commands, execution) =
   231   State {versions = versions, commands = commands, execution = execution};
   232 
   233 fun map_state f (State {versions, commands, execution}) =
   234   make_state (f (versions, commands, execution));
   235 
   236 val init_state =
   237   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty,
   238     (no_id, Future.new_group NONE, Unsynchronized.ref false));
   239 
   240 fun execution_of (State {execution, ...}) = execution;
   241 
   242 
   243 (* document versions *)
   244 
   245 fun define_version (id: version_id) version =
   246   map_state (fn (versions, commands, _) =>
   247     let
   248       val versions' = Inttab.update_new (id, version) versions
   249         handle Inttab.DUP dup => err_dup "document version" dup;
   250       val execution' = (id, Future.new_group NONE, Unsynchronized.ref true);
   251     in (versions', commands, execution') end);
   252 
   253 fun the_version (State {versions, ...}) (id: version_id) =
   254   (case Inttab.lookup versions id of
   255     NONE => err_undef "document version" id
   256   | SOME version => version);
   257 
   258 fun delete_version (id: version_id) versions = Inttab.delete id versions
   259   handle Inttab.UNDEF _ => err_undef "document version" id;
   260 
   261 
   262 (* commands *)
   263 
   264 fun define_command (id: command_id) name text =
   265   map_state (fn (versions, commands, execution) =>
   266     let
   267       val id_string = print_id id;
   268       val span = Lazy.lazy (fn () =>
   269         Position.setmp_thread_data (Position.id_only id_string)
   270           (fn () =>
   271             Thy_Syntax.parse_tokens
   272               (#1 (Outer_Syntax.get_syntax ())) (Position.id id_string) text) ());
   273       val _ =
   274         Position.setmp_thread_data (Position.id_only id_string)
   275           (fn () => Output.status (Markup.markup_only Isabelle_Markup.accepted)) ();
   276       val commands' =
   277         Inttab.update_new (id, (name, span)) commands
   278           handle Inttab.DUP dup => err_dup "command" dup;
   279     in (versions, commands', execution) end);
   280 
   281 fun the_command (State {commands, ...}) (id: command_id) =
   282   (case Inttab.lookup commands id of
   283     NONE => err_undef "command" id
   284   | SOME command => command);
   285 
   286 end;
   287 
   288 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   289   let
   290     val _ = member (op =) ids (#1 execution) andalso
   291       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   292 
   293     val versions' = fold delete_version ids versions;
   294     val commands' =
   295       (versions', Inttab.empty) |->
   296         Inttab.fold (fn (_, version) => nodes_of version |>
   297           Graph.fold (fn (_, (node, _)) => node |>
   298             iterate_entries (fn ((_, id), _) =>
   299               SOME o Inttab.insert (K true) (id, the_command state id))));
   300   in (versions', commands', execution) end);
   301 
   302 
   303 (* consolidated states *)
   304 
   305 fun stable_command (exec_id, exec) =
   306   not (Par_Exn.is_interrupted (Future.join_results (Goal.peek_futures exec_id))) andalso
   307     (case Exn.capture Command.memo_result exec of
   308       Exn.Exn exn => not (Exn.is_interrupt exn)
   309     | Exn.Res _ => true);
   310 
   311 fun finished_theory node =
   312   (case Exn.capture (Command.memo_result o the) (get_result node) of
   313     Exn.Res ((st, _), _) => can (Toplevel.end_theory Position.none) st
   314   | _ => false);
   315 
   316 
   317 
   318 (** document execution **)
   319 
   320 val discontinue_execution = execution_of #> (fn (_, _, running) => running := false);
   321 
   322 val cancel_execution = execution_of #> (fn (_, group, _) => Future.cancel_group group);
   323 
   324 fun terminate_execution state =
   325   let
   326     val (_, group, _) = execution_of state;
   327     val _ = Future.cancel_group group;
   328   in Future.join_tasks (Future.group_tasks group) end;
   329 
   330 fun start_execution state =
   331   let
   332     fun run node command_id exec =
   333       let
   334         val (_, print) = Command.memo_eval exec;
   335         val _ =
   336           if visible_command node command_id
   337           then ignore (Lazy.future Future.default_params print)
   338           else ();
   339       in () end;
   340 
   341     val (version_id, group, running) = execution_of state;
   342 
   343     val _ =
   344       (singleton o Future.forks)
   345         {name = "execution", group = SOME group, deps = [], pri = ~2, interrupts = true}
   346         (fn () =>
   347          (OS.Process.sleep (seconds 0.02);
   348           nodes_of (the_version state version_id) |> Graph.schedule
   349             (fn deps => fn (name, node) =>
   350               if not (visible_node node) andalso finished_theory node then
   351                 Future.value ()
   352               else
   353                 (singleton o Future.forks)
   354                   {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   355                     deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   356                   (fn () =>
   357                     iterate_entries (fn ((_, id), opt_exec) => fn () =>
   358                       (case opt_exec of
   359                         SOME (_, exec) => if ! running then SOME (run node id exec) else NONE
   360                       | NONE => NONE)) node ()))));
   361   in () end;
   362 
   363 
   364 
   365 (** document update **)
   366 
   367 val timing = Unsynchronized.ref false;
   368 fun timeit msg e = cond_timeit (! timing) msg e;
   369 
   370 local
   371 
   372 fun make_required nodes =
   373   let
   374     val all_visible =
   375       Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   376       |> Graph.all_preds nodes
   377       |> map (rpair ()) |> Symtab.make;
   378 
   379     val required =
   380       Symtab.fold (fn (a, ()) =>
   381         exists (Symtab.defined all_visible) (Graph.immediate_succs nodes a) ?
   382           Symtab.update (a, ())) all_visible Symtab.empty;
   383   in Symtab.defined required end;
   384 
   385 fun init_theory deps node span =
   386   let
   387     (* FIXME provide files via Scala layer, not master_dir *)
   388     val (dir, header) = read_header node span;
   389     val master_dir =
   390       (case try Url.explode dir of
   391         SOME (Url.File path) => path
   392       | _ => Path.current);
   393     val imports = #imports header;
   394     val parents =
   395       imports |> map (fn (import, _) =>
   396         (case Thy_Info.lookup_theory import of
   397           SOME thy => thy
   398         | NONE =>
   399             Toplevel.end_theory (Position.file_only import)
   400               (fst (fst
   401                 (Command.memo_result
   402                   (the_default no_exec
   403                     (get_result (snd (the (AList.lookup (op =) deps import))))))))));
   404     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   405   in Thy_Load.begin_theory master_dir header parents end;
   406 
   407 fun check_theory full name node =
   408   is_some (Thy_Info.lookup_theory name) orelse
   409   can get_header node andalso (not full orelse is_some (get_result node));
   410 
   411 fun last_common state last_visible node0 node =
   412   let
   413     fun update_flags prev (visible, initial) =
   414       let
   415         val visible' = visible andalso prev <> last_visible;
   416         val initial' = initial andalso
   417           (case prev of
   418             NONE => true
   419           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   420       in (visible', initial') end;
   421     fun get_common ((prev, id), opt_exec) (same, (_, flags)) =
   422       if same then
   423         let
   424           val flags' = update_flags prev flags;
   425           val same' =
   426             (case opt_exec of
   427               NONE => false
   428             | SOME (exec_id, exec) =>
   429                 (case lookup_entry node0 id of
   430                   NONE => false
   431                 | SOME (exec_id0, _) => exec_id = exec_id0 andalso stable_command (exec_id, exec)));
   432         in SOME (same', (prev, flags')) end
   433       else NONE;
   434     val (same, (common, flags)) =
   435       iterate_entries get_common node (true, (NONE, (true, true)));
   436   in
   437     if same then
   438       let val last = Entries.get_after (get_entries node) common
   439       in (last, update_flags last flags) end
   440     else (common, flags)
   441   end;
   442 
   443 fun illegal_init _ = error "Illegal theory header after end of theory";
   444 
   445 fun new_exec state proper_init command_id' (execs, command_exec, init) =
   446   if not proper_init andalso is_none init then NONE
   447   else
   448     let
   449       val (name, span) = the_command state command_id' ||> Lazy.force;
   450       val (modify_init, init') =
   451         if Keyword.is_theory_begin name then
   452           (Toplevel.modify_init (fn () => the_default illegal_init init span), NONE)
   453         else (I, init);
   454       val exec_id' = new_id ();
   455       val exec_id'_string = print_id exec_id';
   456       val cmd =
   457         Position.setmp_thread_data (Position.id_only exec_id'_string)
   458           (fn () =>
   459             let
   460               val tr =
   461                 #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   462                 |> modify_init
   463                 |> Toplevel.put_id exec_id'_string;
   464               val cmts = Outer_Syntax.span_cmts span;
   465             in (tr, cmts) end);
   466       val exec' =
   467         Command.memo (fn () =>
   468           Command.run_command (cmd ()) (fst (Command.memo_result (snd (snd command_exec)))));
   469       val command_exec' = (command_id', (exec_id', exec'));
   470     in SOME (command_exec' :: execs, command_exec', init') end;
   471 
   472 in
   473 
   474 fun update (old_id: version_id) (new_id: version_id) edits state =
   475   let
   476     val old_version = the_version state old_id;
   477     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   478     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   479 
   480     val nodes = nodes_of new_version;
   481     val is_required = make_required nodes;
   482 
   483     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   484     val updated = timeit "Document.update" (fn () =>
   485       nodes |> Graph.schedule
   486         (fn deps => fn (name, node) =>
   487           (singleton o Future.forks)
   488             {name = "Document.update", group = NONE,
   489               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   490             (fn () =>
   491               let
   492                 val imports = map (apsnd Future.join) deps;
   493                 val updated_imports = exists (is_some o #3 o #1 o #2) imports;
   494                 val required = is_required name;
   495               in
   496                 if updated_imports orelse AList.defined (op =) edits name orelse
   497                   not (stable_entries node) orelse not (finished_theory node)
   498                 then
   499                   let
   500                     val node0 = node_of old_version name;
   501                     val init = init_theory imports node;
   502                     val proper_init =
   503                       check_theory false name node andalso
   504                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   505 
   506                     val last_visible = visible_last node;
   507                     val (common, (visible, initial)) =
   508                       if updated_imports then (NONE, (true, true))
   509                       else last_common state last_visible node0 node;
   510                     val common_command_exec = the_default_entry node common;
   511 
   512                     val (new_execs, (command_id', (_, exec')), _) =
   513                       ([], common_command_exec, if initial then SOME init else NONE) |>
   514                       (visible orelse required) ?
   515                         iterate_entries_after common
   516                           (fn ((prev, id), _) => fn res =>
   517                             if not required andalso prev = last_visible then NONE
   518                             else new_exec state proper_init id res) node;
   519 
   520                     val no_execs =
   521                       iterate_entries_after common
   522                         (fn ((_, id0), exec0) => fn res =>
   523                           if is_none exec0 then NONE
   524                           else if exists (fn (_, (id, _)) => id0 = id) new_execs then SOME res
   525                           else SOME (id0 :: res)) node0 [];
   526 
   527                     val last_exec = if command_id' = no_id then NONE else SOME command_id';
   528                     val result =
   529                       if is_some (after_entry node last_exec) then NONE
   530                       else SOME exec';
   531 
   532                     val node' = node
   533                       |> fold reset_entry no_execs
   534                       |> fold (fn (id, exec) => update_entry id (SOME exec)) new_execs
   535                       |> entries_stable (null new_execs)
   536                       |> set_result result;
   537                     val updated_node =
   538                       if null no_execs andalso null new_execs then NONE
   539                       else SOME (name, node');
   540                   in ((no_execs, new_execs, updated_node), node') end
   541                 else (([], [], NONE), node)
   542               end))
   543       |> Future.joins |> map #1);
   544 
   545     val command_execs =
   546       map (rpair NONE) (maps #1 updated) @
   547       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   548     val updated_nodes = map_filter #3 updated;
   549 
   550     val state' = state
   551       |> define_version new_id (fold put_node updated_nodes new_version);
   552   in (command_execs, state') end;
   553 
   554 end;
   555 
   556 
   557 
   558 (** global state **)
   559 
   560 val global_state = Synchronized.var "Document" init_state;
   561 
   562 fun state () = Synchronized.value global_state;
   563 val change_state = Synchronized.change global_state;
   564 
   565 end;
   566