src/Pure/PIDE/document.ML
author wenzelm
Wed Jul 03 21:32:58 2013 +0200 (2013-07-03 ago)
changeset 52512 c4891dbd5161
parent 52511 d5d2093ff224
child 52513 04210c1bcb90
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, with asynchronous read/eval/print processes.
     6 *)
     7 
     8 signature DOCUMENT =
     9 sig
    10   type id = int
    11   type version_id = id
    12   type command_id = id
    13   type exec_id = id
    14   val no_id: id
    15   val new_id: unit -> id
    16   val parse_id: string -> id
    17   val print_id: id -> string
    18   type node_header = string * Thy_Header.header * string list
    19   datatype node_edit =
    20     Clear |    (* FIXME unused !? *)
    21     Edits of (command_id option * command_id option) list |
    22     Deps of node_header |
    23     Perspective of command_id list
    24   type edit = string * node_edit
    25   type state
    26   val init_state: state
    27   val define_command: command_id -> string -> string -> state -> state
    28   val remove_versions: version_id list -> state -> state
    29   val discontinue_execution: state -> unit
    30   val cancel_execution: state -> unit
    31   val start_execution: state -> unit
    32   val timing: bool Unsynchronized.ref
    33   val update: version_id -> version_id -> edit list -> state ->
    34     (command_id * exec_id option) list * state
    35   val state: unit -> state
    36   val change_state: (state -> state) -> unit
    37 end;
    38 
    39 structure Document: DOCUMENT =
    40 struct
    41 
    42 (* unique identifiers *)
    43 
    44 type id = int;
    45 type version_id = id;
    46 type command_id = id;
    47 type exec_id = id;
    48 
    49 val no_id = 0;
    50 val new_id = Synchronized.counter ();
    51 
    52 val parse_id = Markup.parse_int;
    53 val print_id = Markup.print_int;
    54 
    55 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    56 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    57 
    58 
    59 
    60 (** document structure **)
    61 
    62 type node_header = string * Thy_Header.header * string list;
    63 type perspective = (command_id -> bool) * command_id option;
    64 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    65 
    66 type print = string * unit lazy;
    67 type exec = ((Toplevel.state * {malformed: bool}) * print list) Command.memo; (*eval/print process*)
    68 val no_exec = Command.memo_value ((Toplevel.toplevel, {malformed = false}), []);
    69 
    70 abstype node = Node of
    71  {header: node_header,  (*master directory, theory header, errors*)
    72   perspective: perspective,  (*visible commands, last visible command*)
    73   entries: (exec_id * exec) option Entries.T * bool,  (*command entries with excecutions, stable*)
    74   result: exec option}  (*result of last execution*)
    75 and version = Version of node String_Graph.T  (*development graph wrt. static imports*)
    76 with
    77 
    78 fun make_node (header, perspective, entries, result) =
    79   Node {header = header, perspective = perspective, entries = entries, result = result};
    80 
    81 fun map_node f (Node {header, perspective, entries, result}) =
    82   make_node (f (header, perspective, entries, result));
    83 
    84 fun make_perspective command_ids : perspective =
    85   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    86 
    87 val no_header = ("", Thy_Header.make ("", Position.none) [] [], ["Bad theory header"]);
    88 val no_perspective = make_perspective [];
    89 
    90 val empty_node = make_node (no_header, no_perspective, (Entries.empty, true), NONE);
    91 val clear_node =
    92   map_node (fn (header, _, _, _) => (header, no_perspective, (Entries.empty, true), NONE));
    93 
    94 
    95 (* basic components *)
    96 
    97 fun set_header header =
    98   map_node (fn (_, perspective, entries, result) => (header, perspective, entries, result));
    99 
   100 fun get_header (Node {header = (master, header, errors), ...}) =
   101   if null errors then (master, header)
   102   else error (cat_lines errors);
   103 
   104 fun read_header node span =
   105   let
   106     val (dir, {name = (name, _), imports, keywords}) = get_header node;
   107     val {name = (_, pos), imports = imports', ...} = Thy_Header.read_tokens span;
   108   in (dir, Thy_Header.make (name, pos) (map #1 imports ~~ map #2 imports') keywords) end;
   109 
   110 fun get_perspective (Node {perspective, ...}) = perspective;
   111 fun set_perspective ids =
   112   map_node (fn (header, _, entries, result) => (header, make_perspective ids, entries, result));
   113 
   114 val visible_command = #1 o get_perspective;
   115 val visible_last = #2 o get_perspective;
   116 val visible_node = is_some o visible_last
   117 
   118 fun map_entries f =
   119   map_node (fn (header, perspective, (entries, stable), result) =>
   120     (header, perspective, (f entries, stable), result));
   121 fun get_entries (Node {entries = (entries, _), ...}) = entries;
   122 
   123 fun entries_stable stable =
   124   map_node (fn (header, perspective, (entries, _), result) =>
   125     (header, perspective, (entries, stable), result));
   126 fun stable_entries (Node {entries = (_, stable), ...}) = stable;
   127 
   128 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   129 fun iterate_entries_after start f (Node {entries = (entries, _), ...}) =
   130   (case Entries.get_after entries start of
   131     NONE => I
   132   | SOME id => Entries.iterate (SOME id) f entries);
   133 
   134 fun get_result (Node {result, ...}) = result;
   135 fun set_result result =
   136   map_node (fn (header, perspective, entries, _) => (header, perspective, entries, result));
   137 
   138 fun get_node nodes name = String_Graph.get_node nodes name
   139   handle String_Graph.UNDEF _ => empty_node;
   140 fun default_node name = String_Graph.default_node (name, empty_node);
   141 fun update_node name f = default_node name #> String_Graph.map_node name f;
   142 
   143 
   144 (* node edits and associated executions *)
   145 
   146 datatype node_edit =
   147   Clear |
   148   Edits of (command_id option * command_id option) list |
   149   Deps of node_header |
   150   Perspective of command_id list;
   151 
   152 type edit = string * node_edit;
   153 
   154 val after_entry = Entries.get_after o get_entries;
   155 
   156 fun lookup_entry node id =
   157   (case Entries.lookup (get_entries node) id of
   158     NONE => NONE
   159   | SOME (exec, _) => exec);
   160 
   161 fun the_entry node id =
   162   (case Entries.lookup (get_entries node) id of
   163     NONE => err_undef "command entry" id
   164   | SOME (exec, _) => exec);
   165 
   166 fun the_default_entry node (SOME id) = (id, the_default (no_id, no_exec) (the_entry node id))
   167   | the_default_entry _ NONE = (no_id, (no_id, no_exec));
   168 
   169 fun update_entry id exec =
   170   map_entries (Entries.update (id, exec));
   171 
   172 fun reset_entry id node =
   173   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   174 
   175 fun reset_after id entries =
   176   (case Entries.get_after entries id of
   177     NONE => entries
   178   | SOME next => Entries.update (next, NONE) entries);
   179 
   180 val edit_node = map_entries o fold
   181   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   182     | (id, NONE) => Entries.delete_after id #> reset_after id);
   183 
   184 
   185 (* version operations *)
   186 
   187 val empty_version = Version String_Graph.empty;
   188 
   189 fun nodes_of (Version nodes) = nodes;
   190 val node_of = get_node o nodes_of;
   191 
   192 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   193 
   194 fun edit_nodes (name, node_edit) (Version nodes) =
   195   Version
   196     (case node_edit of
   197       Clear => update_node name clear_node nodes
   198     | Edits edits => update_node name (edit_node edits) nodes
   199     | Deps (master, header, errors) =>
   200         let
   201           val imports = map fst (#imports header);
   202           val errors1 =
   203             (Thy_Header.define_keywords header; errors)
   204               handle ERROR msg => errors @ [msg];
   205           val nodes1 = nodes
   206             |> default_node name
   207             |> fold default_node imports;
   208           val nodes2 = nodes1
   209             |> String_Graph.Keys.fold
   210                 (fn dep => String_Graph.del_edge (dep, name)) (String_Graph.imm_preds nodes1 name);
   211           val (nodes3, errors2) =
   212             (String_Graph.add_deps_acyclic (name, imports) nodes2, errors1)
   213               handle String_Graph.CYCLES cs => (nodes2, errors1 @ map cycle_msg cs);
   214         in String_Graph.map_node name (set_header (master, header, errors2)) nodes3 end
   215     | Perspective perspective => update_node name (set_perspective perspective) nodes);
   216 
   217 fun put_node (name, node) (Version nodes) =
   218   Version (update_node name (K node) nodes);
   219 
   220 end;
   221 
   222 
   223 
   224 (** main state -- document structure and execution process **)
   225 
   226 abstype state = State of
   227  {versions: version Inttab.table,  (*version_id -> document content*)
   228   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> named span*)
   229   execution: version_id * Future.group * bool Unsynchronized.ref}  (*current execution process*)
   230 with
   231 
   232 fun make_state (versions, commands, execution) =
   233   State {versions = versions, commands = commands, execution = execution};
   234 
   235 fun map_state f (State {versions, commands, execution}) =
   236   make_state (f (versions, commands, execution));
   237 
   238 val init_state =
   239   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty,
   240     (no_id, Future.new_group NONE, Unsynchronized.ref false));
   241 
   242 fun execution_of (State {execution, ...}) = execution;
   243 
   244 
   245 (* document versions *)
   246 
   247 fun define_version (id: version_id) version =
   248   map_state (fn (versions, commands, _) =>
   249     let
   250       val versions' = Inttab.update_new (id, version) versions
   251         handle Inttab.DUP dup => err_dup "document version" dup;
   252       val execution' = (id, Future.new_group NONE, Unsynchronized.ref true);
   253     in (versions', commands, execution') end);
   254 
   255 fun the_version (State {versions, ...}) (id: version_id) =
   256   (case Inttab.lookup versions id of
   257     NONE => err_undef "document version" id
   258   | SOME version => version);
   259 
   260 fun delete_version (id: version_id) versions = Inttab.delete id versions
   261   handle Inttab.UNDEF _ => err_undef "document version" id;
   262 
   263 
   264 (* commands *)
   265 
   266 fun define_command (id: command_id) name text =
   267   map_state (fn (versions, commands, execution) =>
   268     let
   269       val id_string = print_id id;
   270       val span = Lazy.lazy (fn () =>
   271         Position.setmp_thread_data (Position.id_only id_string)
   272           (fn () => Thy_Syntax.parse_tokens (Keyword.get_lexicons ()) (Position.id id_string) text)
   273             ());
   274       val _ =
   275         Position.setmp_thread_data (Position.id_only id_string)
   276           (fn () => Output.status (Markup.markup_only Markup.accepted)) ();
   277       val commands' =
   278         Inttab.update_new (id, (name, span)) commands
   279           handle Inttab.DUP dup => err_dup "command" dup;
   280     in (versions, commands', execution) end);
   281 
   282 fun the_command (State {commands, ...}) (id: command_id) =
   283   (case Inttab.lookup commands id of
   284     NONE => err_undef "command" id
   285   | SOME command => command);
   286 
   287 end;
   288 
   289 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   290   let
   291     val _ = member (op =) ids (#1 execution) andalso
   292       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   293 
   294     val versions' = fold delete_version ids versions;
   295     val commands' =
   296       (versions', Inttab.empty) |->
   297         Inttab.fold (fn (_, version) => nodes_of version |>
   298           String_Graph.fold (fn (_, (node, _)) => node |>
   299             iterate_entries (fn ((_, id), _) =>
   300               SOME o Inttab.insert (K true) (id, the_command state id))));
   301   in (versions', commands', execution) end);
   302 
   303 
   304 (* consolidated states *)
   305 
   306 fun stable_command (exec_id, exec) =
   307   not (Par_Exn.is_interrupted (Future.join_results (Goal.peek_futures exec_id))) andalso
   308     (case Exn.capture Command.memo_result exec of
   309       Exn.Exn exn => not (Exn.is_interrupt exn)
   310     | Exn.Res _ => true);
   311 
   312 fun finished_theory node =
   313   (case Exn.capture (Command.memo_result o the) (get_result node) of
   314     Exn.Res ((st, _), _) => can (Toplevel.end_theory Position.none) st
   315   | _ => false);
   316 
   317 
   318 
   319 (** document execution **)
   320 
   321 val discontinue_execution = execution_of #> (fn (_, _, running) => running := false);
   322 val cancel_execution = execution_of #> (fn (_, group, _) => Future.cancel_group group);
   323 val terminate_execution = execution_of #> (fn (_, group, _) => Future.terminate group);
   324 
   325 fun start_execution state =
   326   let
   327     fun run node command_id exec =
   328       let
   329         val (_, print) = Command.memo_eval exec;
   330         val _ =
   331           if visible_command node command_id then
   332             print |> List.app (fn (a, pr) =>
   333               ignore
   334                 (Lazy.future {name = a, group = NONE, deps = [], pri = 0, interrupts = true} pr))
   335           else ();
   336       in () end;
   337 
   338     val (version_id, group, running) = execution_of state;
   339 
   340     val _ =
   341       (singleton o Future.forks)
   342         {name = "Document.execution", group = SOME group, deps = [], pri = ~2, interrupts = true}
   343         (fn () =>
   344          (OS.Process.sleep (seconds 0.02);
   345           nodes_of (the_version state version_id) |> String_Graph.schedule
   346             (fn deps => fn (name, node) =>
   347               if not (visible_node node) andalso finished_theory node then
   348                 Future.value ()
   349               else
   350                 (singleton o Future.forks)
   351                   {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   352                     deps = map (Future.task_of o #2) deps, pri = ~2, interrupts = false}
   353                   (fn () =>
   354                     iterate_entries (fn ((_, id), opt_exec) => fn () =>
   355                       (case opt_exec of
   356                         SOME (_, exec) => if ! running then SOME (run node id exec) else NONE
   357                       | NONE => NONE)) node ()))));
   358   in () end;
   359 
   360 
   361 
   362 (** document update **)
   363 
   364 val timing = Unsynchronized.ref false;
   365 fun timeit msg e = cond_timeit (! timing) msg e;
   366 
   367 local
   368 
   369 fun make_required nodes =
   370   let
   371     val all_visible =
   372       String_Graph.fold (fn (a, (node, _)) => visible_node node ? cons a) nodes []
   373       |> String_Graph.all_preds nodes
   374       |> map (rpair ()) |> Symtab.make;
   375 
   376     val required =
   377       Symtab.fold (fn (a, ()) =>
   378         exists (Symtab.defined all_visible) (String_Graph.immediate_succs nodes a) ?
   379           Symtab.update (a, ())) all_visible Symtab.empty;
   380   in Symtab.defined required end;
   381 
   382 fun init_theory deps node span =
   383   let
   384     (* FIXME provide files via Isabelle/Scala, not master_dir *)
   385     val (dir, header) = read_header node span;
   386     val master_dir =
   387       (case try Url.explode dir of
   388         SOME (Url.File path) => path
   389       | _ => Path.current);
   390     val imports = #imports header;
   391     val parents =
   392       imports |> map (fn (import, _) =>
   393         (case Thy_Info.lookup_theory import of
   394           SOME thy => thy
   395         | NONE =>
   396             Toplevel.end_theory (Position.file_only import)
   397               (fst (fst
   398                 (Command.memo_result
   399                   (the_default no_exec
   400                     (get_result (snd (the (AList.lookup (op =) deps import))))))))));
   401     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   402   in Thy_Load.begin_theory master_dir header parents end;
   403 
   404 fun check_theory full name node =
   405   is_some (Thy_Info.lookup_theory name) orelse
   406   can get_header node andalso (not full orelse is_some (get_result node));
   407 
   408 fun last_common state last_visible node0 node =
   409   let
   410     fun update_flags prev (visible, initial) =
   411       let
   412         val visible' = visible andalso prev <> last_visible;
   413         val initial' = initial andalso
   414           (case prev of
   415             NONE => true
   416           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   417       in (visible', initial') end;
   418     fun get_common ((prev, id), opt_exec) (same, (_, flags)) =
   419       if same then
   420         let
   421           val flags' = update_flags prev flags;
   422           val same' =
   423             (case opt_exec of
   424               NONE => false
   425             | SOME (exec_id, exec) =>
   426                 (case lookup_entry node0 id of
   427                   NONE => false
   428                 | SOME (exec_id0, _) => exec_id = exec_id0 andalso stable_command (exec_id, exec)));
   429         in SOME (same', (prev, flags')) end
   430       else NONE;
   431     val (same, (common, flags)) =
   432       iterate_entries get_common node (true, (NONE, (true, true)));
   433   in
   434     if same then
   435       let val last = Entries.get_after (get_entries node) common
   436       in (last, update_flags last flags) end
   437     else (common, flags)
   438   end;
   439 
   440 fun illegal_init _ = error "Illegal theory header after end of theory";
   441 
   442 fun new_exec state proper_init command_id' (execs, command_exec, init) =
   443   if not proper_init andalso is_none init then NONE
   444   else
   445     let
   446       val (name, span) = the_command state command_id' ||> Lazy.force;
   447       val (modify_init, init') =
   448         if Keyword.is_theory_begin name then
   449           (Toplevel.modify_init (fn () => the_default illegal_init init span), NONE)
   450         else (I, init);
   451       val exec_id' = new_id ();
   452       val exec_id'_string = print_id exec_id';
   453       val read =
   454         Position.setmp_thread_data (Position.id_only exec_id'_string)
   455           (fn () =>
   456             Command.read span
   457             |> modify_init
   458             |> Toplevel.put_id exec_id'_string);
   459       val exec' =
   460         Command.memo (fn () =>
   461           let
   462             val (st_malformed, _) = Command.memo_result (snd (snd command_exec));
   463             val tr = read ();
   464             val ({failed}, (st', malformed')) = Command.eval span tr st_malformed;
   465             val print = if failed then [] else Command.print tr st';
   466           in ((st', malformed'), print) end);
   467       val command_exec' = (command_id', (exec_id', exec'));
   468     in SOME (command_exec' :: execs, command_exec', init') end;
   469 
   470 in
   471 
   472 fun update (old_id: version_id) (new_id: version_id) edits state =
   473   let
   474     val old_version = the_version state old_id;
   475     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   476     val new_version = timeit "Document.edit_nodes" (fn () => fold edit_nodes edits old_version);
   477 
   478     val nodes = nodes_of new_version;
   479     val is_required = make_required nodes;
   480 
   481     val _ = timeit "Document.terminate_execution" (fn () => terminate_execution state);
   482     val updated = timeit "Document.update" (fn () =>
   483       nodes |> String_Graph.schedule
   484         (fn deps => fn (name, node) =>
   485           (singleton o Future.forks)
   486             {name = "Document.update", group = NONE,
   487               deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   488             (fn () =>
   489               let
   490                 val imports = map (apsnd Future.join) deps;
   491                 val updated_imports = exists (is_some o #3 o #1 o #2) imports;
   492                 val required = is_required name;
   493               in
   494                 if updated_imports orelse AList.defined (op =) edits name orelse
   495                   not (stable_entries node) orelse not (finished_theory node)
   496                 then
   497                   let
   498                     val node0 = node_of old_version name;
   499                     val init = init_theory imports node;
   500                     val proper_init =
   501                       check_theory false name node andalso
   502                       forall (fn (name, (_, node)) => check_theory true name node) imports;
   503 
   504                     val last_visible = visible_last node;
   505                     val (common, (visible, initial)) =
   506                       if updated_imports then (NONE, (true, true))
   507                       else last_common state last_visible node0 node;
   508                     val common_command_exec = the_default_entry node common;
   509 
   510                     val (new_execs, (command_id', (_, exec')), _) =
   511                       ([], common_command_exec, if initial then SOME init else NONE) |>
   512                       (visible orelse required) ?
   513                         iterate_entries_after common
   514                           (fn ((prev, id), _) => fn res =>
   515                             if not required andalso prev = last_visible then NONE
   516                             else new_exec state proper_init id res) node;
   517 
   518                     val no_execs =
   519                       iterate_entries_after common
   520                         (fn ((_, id0), exec0) => fn res =>
   521                           if is_none exec0 then NONE
   522                           else if exists (fn (_, (id, _)) => id0 = id) new_execs then SOME res
   523                           else SOME (id0 :: res)) node0 [];
   524 
   525                     val last_exec = if command_id' = no_id then NONE else SOME command_id';
   526                     val result =
   527                       if is_some (after_entry node last_exec) then NONE
   528                       else SOME exec';
   529 
   530                     val node' = node
   531                       |> fold reset_entry no_execs
   532                       |> fold (fn (id, exec) => update_entry id (SOME exec)) new_execs
   533                       |> entries_stable (null new_execs)
   534                       |> set_result result;
   535                     val updated_node =
   536                       if null no_execs andalso null new_execs then NONE
   537                       else SOME (name, node');
   538                   in ((no_execs, new_execs, updated_node), node') end
   539                 else (([], [], NONE), node)
   540               end))
   541       |> Future.joins |> map #1);
   542 
   543     val command_execs =
   544       map (rpair NONE) (maps #1 updated) @
   545       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   546     val updated_nodes = map_filter #3 updated;
   547 
   548     val state' = state
   549       |> define_version new_id (fold put_node updated_nodes new_version);
   550   in (command_execs, state') end;
   551 
   552 end;
   553 
   554 
   555 
   556 (** global state **)
   557 
   558 val global_state = Synchronized.var "Document.global_state" init_state;
   559 
   560 fun state () = Synchronized.value global_state;
   561 val change_state = Synchronized.change global_state;
   562 
   563 end;
   564