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