src/Pure/PIDE/document.ML
author wenzelm
Tue Jul 30 16:22:07 2013 +0200 (2013-07-30)
changeset 52797 0d6f2a87d1a5
parent 52796 ad64ed8e6147
child 52798 9d3c9862d1dd
permissions -rw-r--r--
more timing;
     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   frontier: Future.task Symtab.table};  (*node name -> running execution task*)
   208 
   209 val no_execution: execution =
   210   {version_id = Document_ID.none, execution_id = Document_ID.none, frontier = Symtab.empty};
   211 
   212 fun new_execution version_id frontier : execution =
   213   {version_id = version_id, execution_id = Execution.start (), frontier = frontier};
   214 
   215 abstype state = State of
   216  {versions: version Inttab.table,  (*version id -> document content*)
   217   commands: (string * Token.T list lazy) Inttab.table,  (*command id -> named command span*)
   218   execution: execution}  (*current execution process*)
   219 with
   220 
   221 fun make_state (versions, commands, execution) =
   222   State {versions = versions, commands = commands, execution = execution};
   223 
   224 fun map_state f (State {versions, commands, execution}) =
   225   make_state (f (versions, commands, execution));
   226 
   227 val init_state =
   228   make_state (Inttab.make [(Document_ID.none, empty_version)], Inttab.empty, no_execution);
   229 
   230 
   231 (* document versions *)
   232 
   233 fun define_version version_id version =
   234   map_state (fn (versions, commands, {frontier, ...}) =>
   235     let
   236       val versions' = Inttab.update_new (version_id, version) versions
   237         handle Inttab.DUP dup => err_dup "document version" dup;
   238       val execution' = new_execution version_id frontier;
   239     in (versions', commands, execution') end);
   240 
   241 fun the_version (State {versions, ...}) version_id =
   242   (case Inttab.lookup versions version_id of
   243     NONE => err_undef "document version" version_id
   244   | SOME version => version);
   245 
   246 fun delete_version version_id versions =
   247   Inttab.delete version_id versions
   248     handle Inttab.UNDEF _ => err_undef "document version" version_id;
   249 
   250 
   251 (* commands *)
   252 
   253 fun define_command command_id name text =
   254   map_state (fn (versions, commands, execution) =>
   255     let
   256       val id = Document_ID.print command_id;
   257       val span =
   258         Lazy.lazy (fn () =>
   259           Position.setmp_thread_data (Position.id_only id)
   260             (fn () => Thy_Syntax.parse_tokens (Keyword.get_lexicons ()) (Position.id id) text) ());
   261       val _ =
   262         Position.setmp_thread_data (Position.id_only id)
   263           (fn () => Output.status (Markup.markup_only Markup.accepted)) ();
   264       val commands' =
   265         Inttab.update_new (command_id, (name, span)) commands
   266           handle Inttab.DUP dup => err_dup "command" dup;
   267     in (versions, commands', execution) end);
   268 
   269 fun the_command (State {commands, ...}) command_id =
   270   (case Inttab.lookup commands command_id of
   271     NONE => err_undef "command" command_id
   272   | SOME command => command);
   273 
   274 val the_command_name = #1 oo the_command;
   275 
   276 end;
   277 
   278 
   279 (* remove_versions *)
   280 
   281 fun remove_versions version_ids state = state |> map_state (fn (versions, _, execution) =>
   282   let
   283     val _ =
   284       member (op =) version_ids (#version_id execution) andalso
   285         error ("Attempt to remove execution version " ^ Document_ID.print (#version_id execution));
   286 
   287     val versions' = fold delete_version version_ids versions;
   288     val commands' =
   289       (versions', Inttab.empty) |->
   290         Inttab.fold (fn (_, version) => nodes_of version |>
   291           String_Graph.fold (fn (_, (node, _)) => node |>
   292             iterate_entries (fn ((_, command_id), _) =>
   293               SOME o Inttab.insert (K true) (command_id, the_command state command_id))));
   294   in (versions', commands', execution) end);
   295 
   296 
   297 (* document execution *)
   298 
   299 fun start_execution state = state |> map_state (fn (versions, commands, execution) =>
   300   timeit "Document.start_execution" (fn () =>
   301     let
   302       val {version_id, execution_id, frontier} = execution;
   303       val pri = Options.default_int "editor_execution_priority";
   304 
   305       val new_tasks =
   306         nodes_of (the_version state version_id) |> String_Graph.schedule
   307           (fn deps => fn (name, node) =>
   308             if visible_node node orelse pending_result node then
   309               let
   310                 val former_task = Symtab.lookup frontier name;
   311                 fun body () =
   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                   handle exn => if Exn.is_interrupt exn then () (*sic!*) else reraise exn;
   320                 val future =
   321                   (singleton o Future.forks)
   322                     {name = "theory:" ^ name, group = SOME (Future.new_group NONE),
   323                       deps = the_list former_task @ map #2 (maps #2 deps),
   324                       pri = pri, interrupts = false} body;
   325               in [(name, Future.task_of future)] end
   326             else []);
   327       val frontier' = (fold o fold) Symtab.update new_tasks frontier;
   328       val execution' = {version_id = version_id, execution_id = execution_id, frontier = frontier'};
   329     in (versions, commands, execution') end));
   330 
   331 
   332 
   333 (** document update **)
   334 
   335 (* exec state assignment *)
   336 
   337 type assign_update = Command.exec option Inttab.table;  (*command id -> exec*)
   338 
   339 val assign_update_empty: assign_update = Inttab.empty;
   340 fun assign_update_defined (tab: assign_update) command_id = Inttab.defined tab command_id;
   341 fun assign_update_apply (tab: assign_update) node = Inttab.fold assign_entry tab node;
   342 
   343 fun assign_update_new upd (tab: assign_update) =
   344   Inttab.update_new upd tab
   345     handle Inttab.DUP dup => err_dup "exec state assignment" dup;
   346 
   347 fun assign_update_result (tab: assign_update) =
   348   Inttab.fold (fn (command_id, exec) => cons (command_id, Command.exec_ids exec)) tab [];
   349 
   350 
   351 (* update *)
   352 
   353 local
   354 
   355 fun make_required nodes =
   356   let
   357     val all_visible =
   358       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   359       |> String_Graph.all_preds nodes
   360       |> map (rpair ()) |> Symtab.make;
   361 
   362     val required =
   363       Symtab.fold (fn (a, ()) =>
   364         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   365           Symtab.update (a, ())) all_visible Symtab.empty;
   366   in required end;
   367 
   368 fun init_theory deps node span =
   369   let
   370     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   371     val (dir, header) = read_header node span;
   372     val master_dir =
   373       (case try Url.explode dir of
   374         SOME (Url.File path) => path
   375       | _ => Path.current);
   376     val imports = #imports header;
   377     val parents =
   378       imports |> map (fn (import, _) =>
   379         (case Thy_Info.lookup_theory import of
   380           SOME thy => thy
   381         | NONE =>
   382             Toplevel.end_theory (Position.file_only import)
   383               (case get_result (snd (the (AList.lookup (op =) deps import))) of
   384                 NONE => Toplevel.toplevel
   385               | SOME eval => Command.eval_result_state eval)));
   386     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   387   in Thy_Load.begin_theory master_dir header parents end;
   388 
   389 fun check_theory full name node =
   390   is_some (Thy_Info.lookup_theory name) orelse
   391   can get_header node andalso (not full orelse is_some (get_result node));
   392 
   393 fun last_common state node_required node0 node =
   394   let
   395     fun update_flags prev (visible, initial) =
   396       let
   397         val visible' = visible andalso prev <> visible_last node;
   398         val initial' = initial andalso
   399           (case prev of
   400             NONE => true
   401           | SOME command_id => not (Keyword.is_theory_begin (the_command_name state command_id)));
   402       in (visible', initial') end;
   403 
   404     fun get_common ((prev, command_id), opt_exec) (_, ok, flags, assign_update) =
   405       if ok then
   406         let
   407           val flags' as (visible', _) = update_flags prev flags;
   408           val ok' =
   409             (case (lookup_entry node0 command_id, opt_exec) of
   410               (SOME (eval0, _), SOME (eval, _)) =>
   411                 Command.eval_eq (eval0, eval) andalso
   412                   (visible' orelse node_required orelse Command.eval_running eval)
   413             | _ => false);
   414           val assign_update' = assign_update |> ok' ?
   415             (case opt_exec of
   416               SOME (eval, prints) =>
   417                 let
   418                   val command_visible = visible_command node command_id;
   419                   val command_name = the_command_name state command_id;
   420                 in
   421                   (case Command.print command_visible command_name eval prints of
   422                     SOME prints' => assign_update_new (command_id, SOME (eval, prints'))
   423                   | NONE => I)
   424                 end
   425             | NONE => I);
   426         in SOME (prev, ok', flags', assign_update') end
   427       else NONE;
   428     val (common, ok, flags, assign_update') =
   429       iterate_entries get_common node (NONE, true, (true, true), assign_update_empty);
   430     val (common', flags') =
   431       if ok then
   432         let val last = Entries.get_after (get_entries node) common
   433         in (last, update_flags last flags) end
   434       else (common, flags);
   435   in (assign_update', common', flags') end;
   436 
   437 fun illegal_init _ = error "Illegal theory header after end of theory";
   438 
   439 fun new_exec state proper_init command_visible command_id' (assign_update, command_exec, init) =
   440   if not proper_init andalso is_none init then NONE
   441   else
   442     let
   443       val (_, (eval, _)) = command_exec;
   444       val (command_name, span) = the_command state command_id' ||> Lazy.force;
   445 
   446       val eval' = Command.eval (fn () => the_default illegal_init init span) span eval;
   447       val prints' = perhaps (Command.print command_visible command_name eval') [];
   448       val exec' = (eval', prints');
   449 
   450       val assign_update' = assign_update_new (command_id', SOME exec') assign_update;
   451       val init' = if Keyword.is_theory_begin command_name then NONE else init;
   452     in SOME (assign_update', (command_id', (eval', prints')), init') end;
   453 
   454 fun removed_execs node0 (command_id, exec_ids) =
   455   subtract (op =) exec_ids (Command.exec_ids (lookup_entry node0 command_id));
   456 
   457 in
   458 
   459 fun update old_version_id new_version_id edits state =
   460   let
   461     val old_version = the_version state old_version_id;
   462     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   463 
   464     val nodes = nodes_of new_version;
   465     val required = make_required nodes;
   466     val required0 = make_required (nodes_of old_version);
   467     val edited = fold (fn (name, _) => Symtab.update (name, ())) edits Symtab.empty;
   468 
   469     val updated = timeit "Document.update" (fn () =>
   470       nodes |> String_Graph.schedule
   471         (fn deps => fn (name, node) =>
   472           (singleton o Future.forks)
   473             {name = "Document.update", group = NONE,
   474               deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   475             (fn () => timeit ("Document.update " ^ name) (fn () =>
   476               let
   477                 val imports = map (apsnd Future.join) deps;
   478                 val imports_result_changed = exists (#4 o #1 o #2) imports;
   479                 val node_required = Symtab.defined required name;
   480               in
   481                 if Symtab.defined edited name orelse visible_node node orelse
   482                   imports_result_changed orelse Symtab.defined required0 name <> node_required
   483                 then
   484                   let
   485                     val node0 = node_of old_version name;
   486                     val init = init_theory imports node;
   487                     val proper_init =
   488                       check_theory false name node andalso
   489                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   490 
   491                     val (print_execs, common, (still_visible, initial)) =
   492                       if imports_result_changed then (assign_update_empty, NONE, (true, true))
   493                       else last_common state node_required node0 node;
   494                     val common_command_exec = the_default_entry node common;
   495 
   496                     val (updated_execs, (command_id', (eval', _)), _) =
   497                       (print_execs, common_command_exec, if initial then SOME init else NONE)
   498                       |> (still_visible orelse node_required) ?
   499                         iterate_entries_after common
   500                           (fn ((prev, id), _) => fn res =>
   501                             if not node_required andalso prev = visible_last node then NONE
   502                             else new_exec state proper_init (visible_command node id) id res) node;
   503 
   504                     val assigned_execs =
   505                       (node0, updated_execs) |-> iterate_entries_after common
   506                         (fn ((_, command_id0), exec0) => fn res =>
   507                           if is_none exec0 then NONE
   508                           else if assign_update_defined updated_execs command_id0 then SOME res
   509                           else SOME (assign_update_new (command_id0, NONE) res));
   510 
   511                     val last_exec =
   512                       if command_id' = Document_ID.none then NONE else SOME command_id';
   513                     val result =
   514                       if is_none last_exec orelse is_some (after_entry node last_exec) then NONE
   515                       else SOME eval';
   516 
   517                     val assign_update = assign_update_result assigned_execs;
   518                     val removed = maps (removed_execs node0) assign_update;
   519                     val _ = List.app Execution.cancel removed;
   520 
   521                     val node' = node
   522                       |> assign_update_apply assigned_execs
   523                       |> set_result result;
   524                     val assigned_node = SOME (name, node');
   525                     val result_changed = changed_result node0 node';
   526                   in ((removed, assign_update, assigned_node, result_changed), node') end
   527                 else (([], [], NONE, false), node)
   528               end)))
   529       |> Future.joins |> map #1);
   530 
   531     val removed = maps #1 updated;
   532     val assign_update = maps #2 updated;
   533     val assigned_nodes = map_filter #3 updated;
   534 
   535     val state' = state
   536       |> define_version new_version_id (fold put_node assigned_nodes new_version);
   537 
   538   in (removed, assign_update, state') end;
   539 
   540 end;
   541 
   542 
   543 
   544 (** global state **)
   545 
   546 val global_state = Synchronized.var "Document.global_state" init_state;
   547 
   548 fun state () = Synchronized.value global_state;
   549 val change_state = Synchronized.change global_state;
   550 
   551 end;
   552