src/Pure/PIDE/document.ML
author wenzelm
Thu Mar 15 17:40:26 2012 +0100 (2012-03-15)
changeset 46945 26007caf6e9c
parent 46938 cda018294515
child 46950 d0181abdbdac
permissions -rw-r--r--
declare keywords as side-effect of header edit;
parse_command span is now lazy instead of future, to happen synchronously after header edit in new_exec (before execution);
     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) Exn.result
    19   datatype node_edit =
    20     Clear |
    21     Edits of (command_id option * command_id option) list |
    22     Header 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 cancel_execution: state -> Future.task list
    29   val update_perspective: version_id -> version_id -> string -> command_id list -> state -> state
    30   val update: version_id -> version_id -> edit list -> state ->
    31     ((command_id * exec_id option) list * (string * command_id option) list) * state
    32   val execute: version_id -> state -> state
    33   val remove_versions: version_id list -> state -> state
    34   val state: unit -> state
    35   val change_state: (state -> state) -> unit
    36 end;
    37 
    38 structure Document: DOCUMENT =
    39 struct
    40 
    41 (* unique identifiers *)
    42 
    43 type id = int;
    44 type version_id = id;
    45 type command_id = id;
    46 type exec_id = id;
    47 
    48 val no_id = 0;
    49 val new_id = Synchronized.counter ();
    50 
    51 val parse_id = Markup.parse_int;
    52 val print_id = Markup.print_int;
    53 
    54 fun err_dup kind id = error ("Duplicate " ^ kind ^ ": " ^ print_id id);
    55 fun err_undef kind id = error ("Undefined " ^ kind ^ ": " ^ print_id id);
    56 
    57 
    58 
    59 (** document structure **)
    60 
    61 type node_header = (string * Thy_Header.header) Exn.result;
    62 type perspective = (command_id -> bool) * command_id option; (*visible commands, last*)
    63 structure Entries = Linear_Set(type key = command_id val ord = int_ord);
    64 
    65 type exec = exec_id * (Toplevel.state * unit lazy) lazy;  (*eval/print process*)
    66 val no_print = Lazy.value ();
    67 val no_exec = (no_id, Lazy.value (Toplevel.toplevel, no_print));
    68 
    69 abstype node = Node of
    70  {touched: bool,
    71   header: node_header,
    72   perspective: perspective,
    73   entries: exec option Entries.T,  (*command entries with excecutions*)
    74   last_exec: command_id option,  (*last command with exec state assignment*)
    75   result: Toplevel.state lazy}
    76 and version = Version of node Graph.T  (*development graph wrt. static imports*)
    77 with
    78 
    79 fun make_node (touched, header, perspective, entries, last_exec, result) =
    80   Node {touched = touched, header = header, perspective = perspective,
    81     entries = entries, last_exec = last_exec, result = result};
    82 
    83 fun map_node f (Node {touched, header, perspective, entries, last_exec, result}) =
    84   make_node (f (touched, header, perspective, entries, last_exec, result));
    85 
    86 fun make_perspective command_ids : perspective =
    87   (Inttab.defined (Inttab.make (map (rpair ()) command_ids)), try List.last command_ids);
    88 
    89 val no_header = Exn.Exn (ERROR "Bad theory header");
    90 val no_perspective = make_perspective [];
    91 val no_result = Lazy.value Toplevel.toplevel;
    92 
    93 val empty_node = make_node (false, no_header, no_perspective, Entries.empty, NONE, no_result);
    94 val clear_node = map_node (fn (_, header, _, _, _, _) =>
    95   (false, header, no_perspective, Entries.empty, NONE, no_result));
    96 
    97 
    98 (* basic components *)
    99 
   100 fun is_touched (Node {touched, ...}) = touched;
   101 fun set_touched touched =
   102   map_node (fn (_, header, perspective, entries, last_exec, result) =>
   103     (touched, header, perspective, entries, last_exec, result));
   104 
   105 fun get_header (Node {header, ...}) = header;
   106 fun set_header header =
   107   map_node (fn (touched, _, perspective, entries, last_exec, result) =>
   108     (touched, header, perspective, entries, last_exec, result));
   109 
   110 fun get_perspective (Node {perspective, ...}) = perspective;
   111 fun set_perspective ids =
   112   map_node (fn (touched, header, _, entries, last_exec, result) =>
   113     (touched, header, make_perspective ids, entries, last_exec, result));
   114 
   115 fun map_entries f =
   116   map_node (fn (touched, header, perspective, entries, last_exec, result) =>
   117     (touched, header, perspective, f entries, last_exec, result));
   118 fun get_entries (Node {entries, ...}) = entries;
   119 
   120 fun iterate_entries f = Entries.iterate NONE f o get_entries;
   121 fun iterate_entries_after start f (Node {entries, ...}) =
   122   (case Entries.get_after entries start of
   123     NONE => I
   124   | SOME id => Entries.iterate (SOME id) f entries);
   125 
   126 fun get_last_exec (Node {last_exec, ...}) = last_exec;
   127 fun set_last_exec last_exec =
   128   map_node (fn (touched, header, perspective, entries, _, result) =>
   129     (touched, header, perspective, entries, last_exec, result));
   130 
   131 fun get_theory pos (Node {result, ...}) = Toplevel.end_theory pos (Lazy.force result);
   132 fun set_result result =
   133   map_node (fn (touched, header, perspective, entries, last_exec, _) =>
   134     (touched, header, perspective, entries, last_exec, result));
   135 
   136 fun get_node nodes name = Graph.get_node nodes name handle Graph.UNDEF _ => empty_node;
   137 fun default_node name = Graph.default_node (name, empty_node);
   138 fun update_node name f = default_node name #> Graph.map_node name f;
   139 
   140 
   141 (* node edits and associated executions *)
   142 
   143 datatype node_edit =
   144   Clear |
   145   Edits of (command_id option * command_id option) list |
   146   Header of node_header |
   147   Perspective of command_id list;
   148 
   149 type edit = string * node_edit;
   150 
   151 fun after_entry (Node {entries, ...}) = Entries.get_after entries;
   152 
   153 fun lookup_entry (Node {entries, ...}) id =
   154   (case Entries.lookup entries id of
   155     NONE => NONE
   156   | SOME (exec, _) => exec);
   157 
   158 fun the_entry (Node {entries, ...}) id =
   159   (case Entries.lookup entries id of
   160     NONE => err_undef "command entry" id
   161   | SOME (exec, _) => exec);
   162 
   163 fun the_default_entry node (SOME id) = (id, (the_default no_exec (the_entry node id)))
   164   | the_default_entry _ NONE = (no_id, no_exec);
   165 
   166 fun update_entry id exec =
   167   map_entries (Entries.update (id, exec));
   168 
   169 fun reset_entry id node =
   170   if is_some (lookup_entry node id) then update_entry id NONE node else node;
   171 
   172 fun reset_after id entries =
   173   (case Entries.get_after entries id of
   174     NONE => entries
   175   | SOME next => Entries.update (next, NONE) entries);
   176 
   177 val edit_node = map_entries o fold
   178   (fn (id, SOME id2) => Entries.insert_after id (id2, NONE)
   179     | (id, NONE) => Entries.delete_after id #> reset_after id);
   180 
   181 
   182 (* version operations *)
   183 
   184 val empty_version = Version Graph.empty;
   185 
   186 fun nodes_of (Version nodes) = nodes;
   187 val node_of = get_node o nodes_of;
   188 
   189 local
   190 
   191 fun cycle_msg names = "Cyclic dependency of " ^ space_implode " via " (map quote names);
   192 
   193 fun touch_node name nodes =
   194   fold (fn desc =>
   195       update_node desc
   196         (set_touched true #>
   197           desc <> name ? (map_entries (reset_after NONE) #> set_result no_result)))
   198     (Graph.all_succs nodes [name]) nodes;
   199 
   200 in
   201 
   202 fun edit_nodes (name, node_edit) (Version nodes) =
   203   Version
   204     (case node_edit of
   205       Clear =>
   206         nodes
   207         |> update_node name clear_node
   208         |> touch_node name
   209     | Edits edits =>
   210         nodes
   211         |> update_node name (edit_node edits)
   212         |> touch_node name
   213     | Header header =>
   214         let
   215           val imports = (case header of Exn.Res (_, {imports, ...}) => imports | _ => []);
   216           val keywords = (case header of Exn.Res (_, {keywords, ...}) => keywords | _ => []);
   217           val header' =
   218             (List.app Keyword.declare keywords; header)
   219               handle exn as ERROR _ => Exn.Exn exn;
   220           val nodes1 = nodes
   221             |> default_node name
   222             |> fold default_node imports;
   223           val nodes2 = nodes1
   224             |> Graph.Keys.fold
   225                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   226           val (header'', nodes3) =
   227             (header', Graph.add_deps_acyclic (name, imports) nodes2)
   228               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   229         in Graph.map_node name (set_header header'') nodes3 end
   230         |> touch_node name
   231     | Perspective perspective =>
   232         update_node name (set_perspective perspective) nodes);
   233 
   234 end;
   235 
   236 fun put_node (name, node) (Version nodes) =
   237   Version (update_node name (K node) nodes);
   238 
   239 end;
   240 
   241 
   242 
   243 (** global state -- document structure and execution process **)
   244 
   245 abstype state = State of
   246  {versions: version Inttab.table,  (*version_id -> document content*)
   247   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> name * span*)
   248   execution: version_id * Future.group}  (*current execution process*)
   249 with
   250 
   251 fun make_state (versions, commands, execution) =
   252   State {versions = versions, commands = commands, execution = execution};
   253 
   254 fun map_state f (State {versions, commands, execution}) =
   255   make_state (f (versions, commands, execution));
   256 
   257 val init_state =
   258   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty, (no_id, Future.new_group NONE));
   259 
   260 
   261 (* document versions *)
   262 
   263 fun define_version (id: version_id) version =
   264   map_state (fn (versions, commands, execution) =>
   265     let val versions' = Inttab.update_new (id, version) versions
   266       handle Inttab.DUP dup => err_dup "document version" dup
   267     in (versions', commands, execution) end);
   268 
   269 fun the_version (State {versions, ...}) (id: version_id) =
   270   (case Inttab.lookup versions id of
   271     NONE => err_undef "document version" id
   272   | SOME version => version);
   273 
   274 fun delete_version (id: version_id) versions = Inttab.delete id versions
   275   handle Inttab.UNDEF _ => err_undef "document version" id;
   276 
   277 
   278 (* commands *)
   279 
   280 fun parse_command id text =
   281   Position.setmp_thread_data (Position.id_only id)
   282     (fn () =>
   283       let
   284         val toks = Thy_Syntax.parse_tokens (#1 (Outer_Syntax.get_syntax ())) (Position.id id) text;
   285         val _ = Output.status (Markup.markup_only Isabelle_Markup.parsed);
   286       in toks end) ();
   287 
   288 fun define_command (id: command_id) name text =
   289   map_state (fn (versions, commands, execution) =>
   290     let
   291       val span = Lazy.lazy (fn () => parse_command (print_id id) text);
   292       val commands' =
   293         Inttab.update_new (id, (name, span)) commands
   294           handle Inttab.DUP dup => err_dup "command" dup;
   295     in (versions, commands', execution) end);
   296 
   297 fun the_command (State {commands, ...}) (id: command_id) =
   298   (case Inttab.lookup commands id of
   299     NONE => err_undef "command" id
   300   | SOME command => command);
   301 
   302 
   303 (* document execution *)
   304 
   305 fun cancel_execution (State {execution, ...}) = Future.cancel_group (#2 execution);
   306 
   307 end;
   308 
   309 
   310 (* toplevel transactions *)
   311 
   312 local
   313 
   314 fun timing tr t =
   315   if Timing.is_relevant t then Toplevel.status tr (Isabelle_Markup.timing t) else ();
   316 
   317 fun proof_status tr st =
   318   (case try Toplevel.proof_of st of
   319     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   320   | NONE => ());
   321 
   322 fun print_state tr st =
   323   (Lazy.lazy o Toplevel.setmp_thread_position tr)
   324     (fn () => Toplevel.print_state false st);
   325 
   326 fun run int tr st =
   327   (case Toplevel.transition int tr st of
   328     SOME (st', NONE) => ([], SOME st')
   329   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages exn, NONE)
   330   | NONE => ([(serial (), ML_Compiler.exn_message Runtime.TERMINATE)], NONE));
   331 
   332 in
   333 
   334 fun run_command tr st =
   335   let
   336     val is_init = Toplevel.is_init tr;
   337     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   338 
   339     val _ = Multithreading.interrupted ();
   340     val _ = Toplevel.status tr Isabelle_Markup.forked;
   341     val start = Timing.start ();
   342     val (errs, result) = run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   343     val _ = timing tr (Timing.result start);
   344     val _ = Toplevel.status tr Isabelle_Markup.joined;
   345     val _ = List.app (Toplevel.error_msg tr) errs;
   346   in
   347     (case result of
   348       NONE =>
   349         let
   350           val _ = if null errs then Exn.interrupt () else ();
   351           val _ = Toplevel.status tr Isabelle_Markup.failed;
   352         in (st, no_print) end
   353     | SOME st' =>
   354         let
   355           val _ = Toplevel.status tr Isabelle_Markup.finished;
   356           val _ = proof_status tr st';
   357           val do_print =
   358             not is_init andalso
   359               (Toplevel.print_of tr orelse (is_proof andalso Toplevel.is_proof st'));
   360         in (st', if do_print then print_state tr st' else no_print) end)
   361   end;
   362 
   363 end;
   364 
   365 
   366 
   367 
   368 (** update **)
   369 
   370 (* perspective *)
   371 
   372 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   373   let
   374     val old_version = the_version state old_id;
   375     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   376     val new_version = edit_nodes (name, Perspective perspective) old_version;
   377   in define_version new_id new_version state end;
   378 
   379 
   380 (* edits *)
   381 
   382 local
   383 
   384 fun last_common state last_visible node0 node =
   385   let
   386     fun update_flags prev (visible, initial) =
   387       let
   388         val visible' = visible andalso prev <> last_visible;
   389         val initial' = initial andalso
   390           (case prev of
   391             NONE => true
   392           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   393       in (visible', initial') end;
   394     fun get_common ((prev, id), exec) (found, (_, flags)) =
   395       if found then NONE
   396       else
   397         let val found' =
   398           is_none exec orelse op <> (pairself (Option.map #1) (exec, lookup_entry node0 id));
   399         in SOME (found', (prev, update_flags prev flags)) end;
   400     val (found, (common, flags)) =
   401       iterate_entries get_common node (false, (NONE, (true, true)));
   402   in
   403     if found then (common, flags)
   404     else
   405       let val last = Entries.get_after (get_entries node) common
   406       in (last, update_flags last flags) end
   407   end;
   408 
   409 fun illegal_init () = error "Illegal theory header after end of theory";
   410 
   411 fun new_exec state bad_init command_id' (execs, command_exec, init) =
   412   if bad_init andalso is_none init then NONE
   413   else
   414     let
   415       val (name, span) = the_command state command_id' ||> Lazy.force;
   416       val (modify_init, init') =
   417         if Keyword.is_theory_begin name then
   418           (Toplevel.modify_init (the_default illegal_init init), NONE)
   419         else (I, init);
   420       val exec_id' = new_id ();
   421       val exec_id'_string = print_id exec_id';
   422       val tr =
   423         Position.setmp_thread_data (Position.id_only exec_id'_string)
   424           (fn () =>
   425             #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   426             |> modify_init
   427             |> Toplevel.put_id exec_id'_string);
   428       val exec' = snd (snd command_exec) |> Lazy.map (fn (st, _) => run_command (tr ()) st);
   429       val command_exec' = (command_id', (exec_id', exec'));
   430     in SOME (command_exec' :: execs, command_exec', init') end;
   431 
   432 fun make_required nodes =
   433   let
   434     val all_visible =
   435       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   436       |> Graph.all_preds nodes;
   437     val required =
   438       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   439         all_visible Symtab.empty;
   440   in Symtab.defined required end;
   441 
   442 fun check_theory nodes name =
   443   is_some (Thy_Info.lookup_theory name) orelse  (* FIXME more robust!? *)
   444   is_some (Exn.get_res (get_header (get_node nodes name)));
   445 
   446 fun init_theory deps node =
   447   let
   448     (* FIXME provide files via Scala layer, not master_dir *)
   449     val (master_dir, header) = Exn.release (get_header node);
   450     val parents =
   451       #imports header |> map (fn import =>
   452         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   453           SOME thy => thy
   454         | NONE =>
   455             get_theory (Position.file_only import)
   456               (snd (Future.join (the (AList.lookup (op =) deps import))))));
   457   in Thy_Load.begin_theory (Path.explode master_dir) header parents end;
   458 
   459 in
   460 
   461 fun update (old_id: version_id) (new_id: version_id) edits state =
   462   let
   463     val old_version = the_version state old_id;
   464     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   465     val new_version = fold edit_nodes edits old_version;
   466 
   467     val nodes = nodes_of new_version;
   468     val is_required = make_required nodes;
   469 
   470     val updated =
   471       nodes |> Graph.schedule
   472         (fn deps => fn (name, node) =>
   473           if not (is_touched node orelse is_required name)
   474           then Future.value (([], [], []), node)
   475           else
   476             let
   477               val node0 = node_of old_version name;
   478               fun init () = init_theory deps node;
   479               val bad_init =
   480                 not (check_theory nodes name andalso forall (check_theory nodes o #1) deps);
   481             in
   482               (singleton o Future.forks)
   483                 {name = "Document.update", group = NONE,
   484                   deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   485                 (fn () =>
   486                   let
   487                     val required = is_required name;
   488                     val last_visible = #2 (get_perspective node);
   489                     val (common, (visible, initial)) = last_common state last_visible node0 node;
   490                     val common_command_exec = the_default_entry node common;
   491 
   492                     val (execs, (command_id, (_, exec)), _) =
   493                       ([], common_command_exec, if initial then SOME init else NONE) |>
   494                       (visible orelse required) ?
   495                         iterate_entries_after common
   496                           (fn ((prev, id), _) => fn res =>
   497                             if not required andalso prev = last_visible then NONE
   498                             else new_exec state bad_init id res) node;
   499 
   500                     val no_execs =
   501                       iterate_entries_after common
   502                         (fn ((_, id0), exec0) => fn res =>
   503                           if is_none exec0 then NONE
   504                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   505                           else SOME (id0 :: res)) node0 [];
   506 
   507                     val last_exec = if command_id = no_id then NONE else SOME command_id;
   508                     val result =
   509                       if is_some (after_entry node last_exec) then no_result
   510                       else Lazy.map #1 exec;
   511 
   512                     val node' = node
   513                       |> fold reset_entry no_execs
   514                       |> fold (fn (id, exec) => update_entry id (SOME exec)) execs
   515                       |> set_last_exec last_exec
   516                       |> set_result result
   517                       |> set_touched false;
   518                   in ((no_execs, execs, [(name, node')]), node') end)
   519             end)
   520       |> Future.joins |> map #1;
   521 
   522     val command_execs =
   523       map (rpair NONE) (maps #1 updated) @
   524       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   525     val updated_nodes = maps #3 updated;
   526     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   527 
   528     val state' = state
   529       |> define_version new_id (fold put_node updated_nodes new_version);
   530   in ((command_execs, last_execs), state') end;
   531 
   532 end;
   533 
   534 
   535 (* execute *)
   536 
   537 fun execute version_id state =
   538   state |> map_state (fn (versions, commands, _) =>
   539     let
   540       val version = the_version state version_id;
   541 
   542       fun force_exec _ _ NONE = ()
   543         | force_exec node command_id (SOME (_, exec)) =
   544             let
   545               val (_, print) = Lazy.force exec;
   546               val _ =
   547                 if #1 (get_perspective node) command_id
   548                 then ignore (Lazy.future Future.default_params print)
   549                 else ();
   550             in () end;
   551 
   552       val group = Future.new_group NONE;
   553       val _ =
   554         nodes_of version |> Graph.schedule
   555           (fn deps => fn (name, node) =>
   556             (singleton o Future.forks)
   557               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   558                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   559               (iterate_entries (fn ((_, id), exec) => fn () =>
   560                 SOME (force_exec node id exec)) node));
   561 
   562     in (versions, commands, (version_id, group)) end);
   563 
   564 
   565 (* remove versions *)
   566 
   567 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   568   let
   569     val _ = member (op =) ids (#1 execution) andalso
   570       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   571 
   572     val versions' = fold delete_version ids versions;
   573     val commands' =
   574       (versions', Inttab.empty) |->
   575         Inttab.fold (fn (_, version) => nodes_of version |>
   576           Graph.fold (fn (_, (node, _)) => node |>
   577             iterate_entries (fn ((_, id), _) =>
   578               SOME o Inttab.insert (K true) (id, the_command state id))));
   579   in (versions', commands', execution) end);
   580 
   581 
   582 
   583 (** global state **)
   584 
   585 val global_state = Synchronized.var "Document" init_state;
   586 
   587 fun state () = Synchronized.value global_state;
   588 val change_state = Synchronized.change global_state;
   589 
   590 end;
   591