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