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