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