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