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