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