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