src/Pure/PIDE/document.ML
author wenzelm
Fri Jul 12 11:07:02 2013 +0200 (2013-07-12)
changeset 52605 a2a805549c74
parent 52604 ff2f0818aebc
child 52606 0d68d108d7e0
permissions -rw-r--r--
clarified module name;
     1 (*  Title:      Pure/PIDE/document.ML
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 *)
     7 
     8 signature DOCUMENT =
     9 sig
    10   type node_header = string * Thy_Header.header * string list
    11   datatype node_edit =
    12     Clear |    (* FIXME unused !? *)
    13     Edits of (Document_ID.command option * Document_ID.command option) list |
    14     Deps of node_header |
    15     Perspective of Document_ID.command list
    16   type edit = string * node_edit
    17   type state
    18   val init_state: state
    19   val define_command: Document_ID.command -> string -> string -> state -> state
    20   val remove_versions: Document_ID.version list -> state -> state
    21   val discontinue_execution: state -> unit
    22   val cancel_execution: state -> unit
    23   val start_execution: state -> unit
    24   val timing: bool Unsynchronized.ref
    25   val update: Document_ID.version -> Document_ID.version -> edit list -> state ->
    26     (Document_ID.command * Document_ID.exec list) list * state
    27   val state: unit -> state
    28   val change_state: (state -> state) -> unit
    29 end;
    30 
    31 structure Document: DOCUMENT =
    32 struct
    33 
    34 (** document structure **)
    35 
    36 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ Document_ID.print id);
    37 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ Document_ID.print id);
    38 
    39 type node_header = string * Thy_Header.header * string list;
    40 type perspective = Inttab.set * Document_ID.command option;
    41 structure Entries = Linear_Set(type key = Document_ID.command val ord = int_ord);
    42 
    43 abstype node = Node of
    44  {header: node_header,  (*master directory, theory header, errors*)
    45   perspective: perspective,  (*visible commands, last visible command*)
    46   entries: Command.exec option Entries.T * bool,  (*command entries with excecutions, stable*)
    47   result: Command.eval option}  (*result of last execution*)
    48 and version = Version of node String_Graph.T  (*development graph wrt. static imports*)
    49 with
    50 
    51 fun make_node (header, perspective, entries, result) =
    52   Node {header = header, perspective = perspective, entries = entries, result = result};
    53 
    54 fun map_node f (Node {header, perspective, entries, result}) =
    55   make_node (f (header, perspective, entries, result));
    56 
    57 fun make_perspective command_ids : perspective =
    58   (Inttab.make_set command_ids, try List.last command_ids);
    59 
    60 val no_header = ("", Thy_Header.make ("", Position.none) [] [], ["Bad theory header"]);
    61 val no_perspective = make_perspective [];
    62 
    63 val empty_node = make_node (no_header, no_perspective, (Entries.empty, true), NONE);
    64 val clear_node =
    65   map_node (fn (header, _, _, _) => (header, no_perspective, (Entries.empty, true), NONE));
    66 
    67 
    68 (* basic components *)
    69 
    70 fun set_header header =
    71   map_node (fn (_, perspective, entries, result) => (header, perspective, entries, result));
    72 
    73 fun get_header (Node {header = (master, header, errors), ...}) =
    74   if null errors then (master, header)
    75   else error (cat_lines errors);
    76 
    77 fun read_header node span =
    78   let
    79     val (dir, {name = (name, _), imports, keywords}) = get_header node;
    80     val {name = (_, pos), imports = imports', ...} = Thy_Header.read_tokens span;
    81   in (dir, Thy_Header.make (name, pos) (map #1 imports ~~ map #2 imports') keywords) end;
    82 
    83 fun get_perspective (Node {perspective, ...}) = perspective;
    84 fun set_perspective ids =
    85   map_node (fn (header, _, entries, result) => (header, make_perspective ids, entries, result));
    86 
    87 val visible_command = Inttab.defined o #1 o get_perspective;
    88 val visible_last = #2 o get_perspective;
    89 val visible_node = is_some o visible_last
    90 
    91 fun map_entries f =
    92   map_node (fn (header, perspective, (entries, stable), result) =>
    93     (header, perspective, (f entries, stable), result));
    94 fun get_entries (Node {entries = (entries, _), ...}) = entries;
    95 
    96 fun entries_stable stable =
    97   map_node (fn (header, perspective, (entries, _), result) =>
    98     (header, perspective, (entries, stable), result));
    99 fun stable_entries (Node {entries = (_, stable), ...}) = stable;
   100 
   101 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   102 fun iterate_entries_after start f (Node {entries = (entries, _), ...}) =
   103   (case Entries.get_after entries start of
   104     NONE => I
   105   | SOME id => Entries.iterate (SOME id) f entries);
   106 
   107 fun get_result (Node {result, ...}) = result;
   108 fun set_result result =
   109   map_node (fn (header, perspective, entries, _) => (header, perspective, entries, result));
   110 
   111 fun changed_result node node' =
   112   (case (get_result node, get_result node') of
   113     (SOME eval, SOME eval') => not (Command.eval_same (eval, eval'))
   114   | (NONE, NONE) => false
   115   | _ => true);
   116 
   117 fun finished_theory node =
   118   (case Exn.capture (Command.eval_result_state o the) (get_result node) of
   119     Exn.Res st => can (Toplevel.end_theory Position.none) st
   120   | _ => false);
   121 
   122 fun get_node nodes name = String_Graph.get_node nodes name
   123   handle String_Graph.UNDEF _ => empty_node;
   124 fun default_node name = String_Graph.default_node (name, empty_node);
   125 fun update_node name f = default_node name #> String_Graph.map_node name f;
   126 
   127 
   128 (* node edits and associated executions *)
   129 
   130 datatype node_edit =
   131   Clear |
   132   Edits of (Document_ID.command option * Document_ID.command option) list |
   133   Deps of node_header |
   134   Perspective of Document_ID.command list;
   135 
   136 type edit = string * node_edit;
   137 
   138 val after_entry = Entries.get_after o get_entries;
   139 
   140 fun lookup_entry node id =
   141   (case Entries.lookup (get_entries node) id of
   142     NONE => NONE
   143   | SOME (exec, _) => exec);
   144 
   145 fun the_entry node id =
   146   (case Entries.lookup (get_entries node) id of
   147     NONE => err_undef "command entry" id
   148   | SOME (exec, _) => exec);
   149 
   150 fun the_default_entry node (SOME id) = (id, the_default Command.no_exec (the_entry node id))
   151   | the_default_entry _ NONE = (Document_ID.none, Command.no_exec);
   152 
   153 fun assign_entry (command_id, exec) node =
   154   if is_none (Entries.lookup (get_entries node) command_id) then node
   155   else map_entries (Entries.update (command_id, exec)) node;
   156 
   157 fun reset_after id entries =
   158   (case Entries.get_after entries id of
   159     NONE => entries
   160   | SOME next => Entries.update (next, NONE) entries);
   161 
   162 val edit_node = map_entries o fold
   163   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   164     | (id, NONE) => Entries.delete_after id #> reset_after id);
   165 
   166 
   167 (* version operations *)
   168 
   169 val empty_version = Version String_Graph.empty;
   170 
   171 fun nodes_of (Version nodes) = nodes;
   172 val node_of = get_node o nodes_of;
   173 
   174 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   175 
   176 fun edit_nodes (name, node_edit) (Version nodes) =
   177   Version
   178     (case node_edit of
   179       Clear => update_node name clear_node nodes
   180     | Edits edits => update_node name (edit_node edits) nodes
   181     | Deps (master, header, errors) =>
   182         let
   183           val imports = map fst (#imports header);
   184           val errors1 =
   185             (Thy_Header.define_keywords header; errors)
   186               handle ERROR msg => errors @ [msg];
   187           val nodes1 = nodes
   188             |> default_node name
   189             |> fold default_node imports;
   190           val nodes2 = nodes1
   191             |> String_Graph.Keys.fold
   192                 (fn dep => String_Graph.del_edge (dep, name)) (String_Graph.imm_preds nodes1 name);
   193           val (nodes3, errors2) =
   194             (String_Graph.add_deps_acyclic (name, imports) nodes2, errors1)
   195               handle String_Graph.CYCLES cs => (nodes2, errors1 @ map cycle_msg cs);
   196         in String_Graph.map_node name (set_header (master, header, errors2)) nodes3 end
   197     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   198 
   199 fun put_node (name, node) (Version nodes) =
   200   Version (update_node name (K node) nodes);
   201 
   202 end;
   203 
   204 
   205 
   206 (** main state -- document structure and execution process **)
   207 
   208 type execution = {version_id: Document_ID.version, context: Execution.context};
   209 
   210 val no_execution = {version_id = Document_ID.none, context = Execution.no_context};
   211 fun make_execution version_id = {version_id = version_id, context = Execution.fresh_context ()};
   212 
   213 abstype state = State of
   214  {versions: version Inttab.table,  (*version id -> document content*)
   215   commands: (string * Token.T list lazy) Inttab.table,  (*command id -> named command span*)
   216   execution: execution}  (*current execution process*)
   217 with
   218 
   219 fun make_state (versions, commands, execution) =
   220   State {versions = versions, commands = commands, execution = execution};
   221 
   222 fun map_state f (State {versions, commands, execution}) =
   223   make_state (f (versions, commands, execution));
   224 
   225 val init_state =
   226   make_state (Inttab.make [(Document_ID.none, empty_version)], Inttab.empty, no_execution);
   227 
   228 fun execution_of (State {execution, ...}) = execution;
   229 
   230 
   231 (* document versions *)
   232 
   233 fun define_version version_id version =
   234   map_state (fn (versions, commands, _) =>
   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' = make_execution version_id;
   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 discontinue_execution state =
   300   Execution.drop_context (#context (execution_of state));
   301 
   302 fun cancel_execution state =
   303   (Execution.drop_context (#context (execution_of state)); Execution.terminate_all ());
   304 
   305 fun start_execution state =
   306   let
   307     val {version_id, context} = execution_of state;
   308     val _ =
   309       if Execution.is_running context then
   310         nodes_of (the_version state version_id) |> String_Graph.schedule
   311           (fn deps => fn (name, node) =>
   312             if not (visible_node node) andalso finished_theory node then
   313               Future.value ()
   314             else
   315               (singleton o Future.forks)
   316                 {name = "theory:" ^ name, group = SOME (Future.new_group NONE),
   317                   deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   318                 (fn () =>
   319                   iterate_entries (fn (_, opt_exec) => fn () =>
   320                     (case opt_exec of
   321                       SOME exec =>
   322                         if Execution.is_running context then SOME (Command.exec context exec)
   323                         else NONE
   324                     | NONE => NONE)) node ()))
   325       else [];
   326   in () end;
   327 
   328 
   329 
   330 (** document update **)
   331 
   332 (* exec state assignment *)
   333 
   334 type assign_update = Command.exec option Inttab.table;  (*command id -> exec*)
   335 
   336 val assign_update_empty: assign_update = Inttab.empty;
   337 fun assign_update_null (tab: assign_update) = Inttab.is_empty tab;
   338 fun assign_update_defined (tab: assign_update) command_id = Inttab.defined tab command_id;
   339 fun assign_update_apply (tab: assign_update) node = Inttab.fold assign_entry tab node;
   340 
   341 fun assign_update_new upd (tab: assign_update) =
   342   Inttab.update_new upd tab
   343     handle Inttab.DUP dup => err_dup "exec state assignment" dup;
   344 
   345 fun assign_update_result (tab: assign_update) =
   346   Inttab.fold (fn (command_id, exec) => cons (command_id, Command.exec_ids exec)) tab [];
   347 
   348 
   349 (* update *)
   350 
   351 val timing = Unsynchronized.ref false;
   352 fun timeit msg e = cond_timeit (! timing) msg e;
   353 
   354 local
   355 
   356 fun make_required nodes =
   357   let
   358     val all_visible =
   359       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   360       |> String_Graph.all_preds nodes
   361       |> map (rpair ()) |> Symtab.make;
   362 
   363     val required =
   364       Symtab.fold (fn (a, ()) =>
   365         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   366           Symtab.update (a, ())) all_visible Symtab.empty;
   367   in Symtab.defined required end;
   368 
   369 fun init_theory deps node span =
   370   let
   371     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   372     val (dir, header) = read_header node span;
   373     val master_dir =
   374       (case try Url.explode dir of
   375         SOME (Url.File path) => path
   376       | _ => Path.current);
   377     val imports = #imports header;
   378     val parents =
   379       imports |> map (fn (import, _) =>
   380         (case Thy_Info.lookup_theory import of
   381           SOME thy => thy
   382         | NONE =>
   383             Toplevel.end_theory (Position.file_only import)
   384               (case get_result (snd (the (AList.lookup (op =) deps import))) of
   385                 NONE => Toplevel.toplevel
   386               | SOME eval => Command.eval_result_state eval)));
   387     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   388   in Thy_Load.begin_theory master_dir header parents end;
   389 
   390 fun check_theory full name node =
   391   is_some (Thy_Info.lookup_theory name) orelse
   392   can get_header node andalso (not full orelse is_some (get_result node));
   393 
   394 fun last_common state node0 node =
   395   let
   396     fun update_flags prev (visible, initial) =
   397       let
   398         val visible' = visible andalso prev <> visible_last node;
   399         val initial' = initial andalso
   400           (case prev of
   401             NONE => true
   402           | SOME command_id => not (Keyword.is_theory_begin (the_command_name state command_id)));
   403       in (visible', initial') end;
   404 
   405     fun get_common ((prev, command_id), opt_exec) (_, same, flags, assign_update) =
   406       if same then
   407         let
   408           val flags' = update_flags prev flags;
   409           val same' =
   410             (case (lookup_entry node0 command_id, opt_exec) of
   411               (SOME (eval0, _), SOME (eval, _)) => Command.eval_same (eval0, eval)
   412             | _ => false);
   413           val assign_update' = assign_update |> same' ?
   414             (case opt_exec of
   415               SOME (eval, prints) =>
   416                 let
   417                   val command_visible = visible_command node command_id;
   418                   val command_name = the_command_name state command_id;
   419                 in
   420                   (case Command.print command_visible command_name eval prints of
   421                     SOME prints' => assign_update_new (command_id, SOME (eval, prints'))
   422                   | NONE => I)
   423                 end
   424             | NONE => I);
   425         in SOME (prev, same', flags', assign_update') end
   426       else NONE;
   427     val (common, same, flags, assign_update') =
   428       iterate_entries get_common node (NONE, true, (true, true), assign_update_empty);
   429     val (common', flags') =
   430       if same then
   431         let val last = Entries.get_after (get_entries node) common
   432         in (last, update_flags last flags) end
   433       else (common, flags);
   434   in (assign_update', common', flags') end;
   435 
   436 fun illegal_init _ = error "Illegal theory header after end of theory";
   437 
   438 fun new_exec state proper_init command_visible command_id' (assign_update, command_exec, init) =
   439   if not proper_init andalso is_none init then NONE
   440   else
   441     let
   442       val (_, (eval, _)) = command_exec;
   443       val (command_name, span) = the_command state command_id' ||> Lazy.force;
   444 
   445       val eval' = Command.eval (fn () => the_default illegal_init init span) span eval;
   446       val prints' = perhaps (Command.print command_visible command_name eval') [];
   447       val exec' = (eval', prints');
   448 
   449       val assign_update' = assign_update_new (command_id', SOME exec') assign_update;
   450       val init' = if Keyword.is_theory_begin command_name then NONE else init;
   451     in SOME (assign_update', (command_id', (eval', prints')), init') end;
   452 
   453 fun cancel_old_execs node0 (command_id, exec_ids) =
   454   subtract (op =) exec_ids (Command.exec_ids (lookup_entry node0 command_id))
   455   |> map_filter (Execution.peek_running #> Option.map (tap Future.cancel_group));
   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 is_required = make_required nodes;
   466 
   467     val updated = timeit "Document.update" (fn () =>
   468       nodes |> String_Graph.schedule
   469         (fn deps => fn (name, node) =>
   470           (singleton o Future.forks)
   471             {name = "Document.update", group = NONE,
   472               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   473             (fn () =>
   474               let
   475                 val imports = map (apsnd Future.join) deps;
   476                 val imports_changed = exists (#4 o #1 o #2) imports;
   477                 val node_required = is_required name;
   478               in
   479                 if imports_changed orelse AList.defined (op =) edits name orelse
   480                   not (stable_entries node) orelse not (finished_theory node)
   481                 then
   482                   let
   483                     val node0 = node_of old_version name;
   484                     val init = init_theory imports node;
   485                     val proper_init =
   486                       check_theory false name node andalso
   487                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   488 
   489                     val (print_execs, common, (still_visible, initial)) =
   490                       if imports_changed then (assign_update_empty, NONE, (true, true))
   491                       else last_common state node0 node;
   492                     val common_command_exec = the_default_entry node common;
   493 
   494                     val (updated_execs, (command_id', (eval', _)), _) =
   495                       (print_execs, common_command_exec, if initial then SOME init else NONE)
   496                       |> (still_visible orelse node_required) ?
   497                         iterate_entries_after common
   498                           (fn ((prev, id), _) => fn res =>
   499                             if not node_required andalso prev = visible_last node then NONE
   500                             else new_exec state proper_init (visible_command node id) id res) node;
   501 
   502                     val assigned_execs =
   503                       (node0, updated_execs) |-> iterate_entries_after common
   504                         (fn ((_, command_id0), exec0) => fn res =>
   505                           if is_none exec0 then NONE
   506                           else if assign_update_defined updated_execs command_id0 then SOME res
   507                           else SOME (assign_update_new (command_id0, NONE) res));
   508 
   509                     val last_exec =
   510                       if command_id' = Document_ID.none then NONE else SOME command_id';
   511                     val result =
   512                       if is_none last_exec orelse is_some (after_entry node last_exec) then NONE
   513                       else SOME eval';
   514 
   515                     val assign_update = assign_update_result assigned_execs;
   516                     val old_groups = maps (cancel_old_execs node0) assign_update;
   517 
   518                     val node' = node
   519                       |> assign_update_apply assigned_execs
   520                       |> entries_stable (assign_update_null updated_execs)
   521                       |> set_result result;
   522                     val assigned_node = SOME (name, node');
   523                     val result_changed = changed_result node0 node';
   524                   in ((assign_update, old_groups, assigned_node, result_changed), node') end
   525                 else (([], [], NONE, false), node)
   526               end))
   527       |> Future.joins |> map #1);
   528 
   529     val assign_update = maps #1 updated;
   530     val old_groups = maps #2 updated;
   531     val assigned_nodes = map_filter #3 updated;
   532 
   533     val state' = state
   534       |> define_version new_version_id (fold put_node assigned_nodes new_version);
   535 
   536     val _ = timeit "Document.terminate" (fn () => List.app Future.terminate old_groups);
   537   in (assign_update, state') end;
   538 
   539 end;
   540 
   541 
   542 
   543 (** global state **)
   544 
   545 val global_state = Synchronized.var "Document.global_state" init_state;
   546 
   547 fun state () = Synchronized.value global_state;
   548 val change_state = Synchronized.change global_state;
   549 
   550 end;
   551