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