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