src/Pure/PIDE/document.ML
author wenzelm
Thu Jul 11 14:42:11 2013 +0200 (2013-07-11 ago)
changeset 52596 40298d383463
parent 52595 76883c1e1c53
child 52599 d7871f38ffb4
permissions -rw-r--r--
global management of command execution fragments;
tuned;
     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') => #exec_id eval <> #exec_id 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 val terminate_execution = execution_of #> (fn {group, ...} => Future.terminate group);
   318 
   319 fun start_execution state =
   320   let
   321     val {version_id, group, continue} = execution_of state;
   322     fun running () = Synchronized.guarded_access continue (fn x => SOME (x, x));
   323     val _ =
   324       if not (running ()) orelse Task_Queue.is_canceled group then []
   325       else
   326         nodes_of (the_version state version_id) |> String_Graph.schedule
   327           (fn deps => fn (name, node) =>
   328             if not (visible_node node) andalso finished_theory node then
   329               Future.value ()
   330             else
   331               (singleton o Future.forks)
   332                 {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   333                   deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   334                 (fn () =>
   335                   iterate_entries (fn (_, opt_exec) => fn () =>
   336                     (case opt_exec of
   337                       SOME exec => if running () then SOME (Command.execute exec) else NONE
   338                     | NONE => NONE)) node ()));
   339   in () end;
   340 
   341 
   342 
   343 (** document update **)
   344 
   345 (* exec state assignment *)
   346 
   347 type assign_update = Command.exec option Inttab.table;  (*command id -> exec*)
   348 
   349 val assign_update_empty: assign_update = Inttab.empty;
   350 fun assign_update_null (tab: assign_update) = Inttab.is_empty tab;
   351 fun assign_update_defined (tab: assign_update) command_id = Inttab.defined tab command_id;
   352 fun assign_update_apply (tab: assign_update) node = Inttab.fold assign_entry tab node;
   353 
   354 fun assign_update_new upd (tab: assign_update) =
   355   Inttab.update_new upd tab
   356     handle Inttab.DUP dup => err_dup "exec state assignment" dup;
   357 
   358 fun assign_update_result (tab: assign_update) =
   359   Inttab.fold (fn (command_id, exec) => cons (command_id, Command.exec_ids exec)) tab [];
   360 
   361 
   362 (* update *)
   363 
   364 val timing = Unsynchronized.ref false;
   365 fun timeit msg e = cond_timeit (! timing) msg e;
   366 
   367 local
   368 
   369 fun make_required nodes =
   370   let
   371     val all_visible =
   372       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   373       |> String_Graph.all_preds nodes
   374       |> map (rpair ()) |> Symtab.make;
   375 
   376     val required =
   377       Symtab.fold (fn (a, ()) =>
   378         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   379           Symtab.update (a, ())) all_visible Symtab.empty;
   380   in Symtab.defined required end;
   381 
   382 fun init_theory deps node span =
   383   let
   384     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   385     val (dir, header) = read_header node span;
   386     val master_dir =
   387       (case try Url.explode dir of
   388         SOME (Url.File path) => path
   389       | _ => Path.current);
   390     val imports = #imports header;
   391     val parents =
   392       imports |> map (fn (import, _) =>
   393         (case Thy_Info.lookup_theory import of
   394           SOME thy => thy
   395         | NONE =>
   396             Toplevel.end_theory (Position.file_only import)
   397               (case get_result (snd (the (AList.lookup (op =) deps import))) of
   398                 NONE => Toplevel.toplevel
   399               | SOME eval => Command.eval_result_state eval)));
   400     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   401   in Thy_Load.begin_theory master_dir header parents end;
   402 
   403 fun check_theory full name node =
   404   is_some (Thy_Info.lookup_theory name) orelse
   405   can get_header node andalso (not full orelse is_some (get_result node));
   406 
   407 fun last_common state node0 node =
   408   let
   409     fun update_flags prev (visible, initial) =
   410       let
   411         val visible' = visible andalso prev <> visible_last node;
   412         val initial' = initial andalso
   413           (case prev of
   414             NONE => true
   415           | SOME command_id => not (Keyword.is_theory_begin (the_command_name state command_id)));
   416       in (visible', initial') end;
   417 
   418     fun get_common ((prev, command_id), opt_exec) (_, same, flags, assign_update) =
   419       if same then
   420         let
   421           val flags' = update_flags prev flags;
   422           val same' =
   423             (case (lookup_entry node0 command_id, opt_exec) of
   424               (SOME (eval0, _), SOME (eval, _)) => Command.eval_same (eval0, eval)
   425             | _ => false);
   426           val assign_update' = assign_update |> same' ?
   427             (case opt_exec of
   428               SOME (eval, prints) =>
   429                 let
   430                   val command_visible = visible_command node command_id;
   431                   val command_name = the_command_name state command_id;
   432                 in
   433                   (case Command.print command_visible command_name eval prints of
   434                     SOME prints' => assign_update_new (command_id, SOME (eval, prints'))
   435                   | NONE => I)
   436                 end
   437             | NONE => I);
   438         in SOME (prev, same', flags', assign_update') end
   439       else NONE;
   440     val (common, same, flags, assign_update') =
   441       iterate_entries get_common node (NONE, true, (true, true), assign_update_empty);
   442     val (common', flags') =
   443       if same then
   444         let val last = Entries.get_after (get_entries node) common
   445         in (last, update_flags last flags) end
   446       else (common, flags);
   447   in (assign_update', common', flags') end;
   448 
   449 fun illegal_init _ = error "Illegal theory header after end of theory";
   450 
   451 fun new_exec state proper_init command_visible command_id' (assign_update, command_exec, init) =
   452   if not proper_init andalso is_none init then NONE
   453   else
   454     let
   455       val (_, (eval, _)) = command_exec;
   456       val (command_name, span) = the_command state command_id' ||> Lazy.force;
   457 
   458       val eval' = Command.eval (fn () => the_default illegal_init init span) span eval;
   459       val prints' = perhaps (Command.print command_visible command_name eval') [];
   460       val exec' = (eval', prints');
   461 
   462       val assign_update' = assign_update_new (command_id', SOME exec') assign_update;
   463       val init' = if Keyword.is_theory_begin command_name then NONE else init;
   464     in SOME (assign_update', (command_id', (eval', prints')), init') end;
   465 in
   466 
   467 fun update old_version_id new_version_id edits state =
   468   let
   469     val old_version = the_version state old_version_id;
   470     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   471 
   472     val nodes = nodes_of new_version;
   473     val is_required = make_required nodes;
   474 
   475     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   476     val updated = timeit "Document.update" (fn () =>
   477       nodes |> String_Graph.schedule
   478         (fn deps => fn (name, node) =>
   479           (singleton o Future.forks)
   480             {name = "Document.update", group = NONE,
   481               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   482             (fn () =>
   483               let
   484                 val imports = map (apsnd Future.join) deps;
   485                 val imports_changed = exists (#3 o #1 o #2) imports;
   486                 val node_required = is_required name;
   487               in
   488                 if imports_changed orelse AList.defined (op =) edits name orelse
   489                   not (stable_entries node) orelse not (finished_theory node)
   490                 then
   491                   let
   492                     val node0 = node_of old_version name;
   493                     val init = init_theory imports node;
   494                     val proper_init =
   495                       check_theory false name node andalso
   496                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   497 
   498                     val (print_execs, common, (still_visible, initial)) =
   499                       if imports_changed then (assign_update_empty, NONE, (true, true))
   500                       else last_common state node0 node;
   501                     val common_command_exec = the_default_entry node common;
   502 
   503                     val (updated_execs, (command_id', (eval', _)), _) =
   504                       (print_execs, common_command_exec, if initial then SOME init else NONE)
   505                       |> (still_visible orelse node_required) ?
   506                         iterate_entries_after common
   507                           (fn ((prev, id), _) => fn res =>
   508                             if not node_required andalso prev = visible_last node then NONE
   509                             else new_exec state proper_init (visible_command node id) id res) node;
   510 
   511                     val assigned_execs =
   512                       (node0, updated_execs) |-> iterate_entries_after common
   513                         (fn ((_, command_id0), exec0) => fn res =>
   514                           if is_none exec0 then NONE
   515                           else if assign_update_defined updated_execs command_id0 then SOME res
   516                           else SOME (assign_update_new (command_id0, NONE) res));
   517 
   518                     val last_exec =
   519                       if command_id' = Document_ID.none then NONE else SOME command_id';
   520                     val result =
   521                       if is_none last_exec orelse is_some (after_entry node last_exec) then NONE
   522                       else SOME eval';
   523 
   524                     val node' = node
   525                       |> assign_update_apply assigned_execs
   526                       |> entries_stable (assign_update_null updated_execs)
   527                       |> set_result result;
   528                     val assigned_node = SOME (name, node');
   529                     val result_changed = changed_result node0 node';
   530                   in
   531                     ((assign_update_result assigned_execs, assigned_node, result_changed), node')
   532                   end
   533                 else (([], NONE, false), node)
   534               end))
   535       |> Future.joins |> map #1);
   536 
   537     val state' = state
   538       |> define_version new_version_id (fold put_node (map_filter #2 updated) new_version);
   539   in (maps #1 updated, state') end;
   540 
   541 end;
   542 
   543 
   544 
   545 (** global state **)
   546 
   547 val global_state = Synchronized.var "Document.global_state" init_state;
   548 
   549 fun state () = Synchronized.value global_state;
   550 val change_state = Synchronized.change global_state;
   551 
   552 end;
   553