src/Pure/PIDE/document.ML
author wenzelm
Thu Mar 15 22:08:53 2012 +0100 (2012-03-15)
changeset 46950 d0181abdbdac
parent 46945 26007caf6e9c
child 46958 0ec8f04e753a
permissions -rw-r--r--
declare command keywords via theory header, including strict checking outside Pure;
     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 (fn (name, decl) =>
   219                 Keyword.declare name (Option.map Keyword.make decl)) keywords; header)
   220               handle exn as ERROR _ => Exn.Exn exn;
   221           val nodes1 = nodes
   222             |> default_node name
   223             |> fold default_node imports;
   224           val nodes2 = nodes1
   225             |> Graph.Keys.fold
   226                 (fn dep => Graph.del_edge (dep, name)) (Graph.imm_preds nodes1 name);
   227           val (header'', nodes3) =
   228             (header', Graph.add_deps_acyclic (name, imports) nodes2)
   229               handle Graph.CYCLES cs => (Exn.Exn (ERROR (cat_lines (map cycle_msg cs))), nodes2);
   230         in Graph.map_node name (set_header header'') nodes3 end
   231         |> touch_node name
   232     | Perspective perspective =>
   233         update_node name (set_perspective perspective) nodes);
   234 
   235 end;
   236 
   237 fun put_node (name, node) (Version nodes) =
   238   Version (update_node name (K node) nodes);
   239 
   240 end;
   241 
   242 
   243 
   244 (** global state -- document structure and execution process **)
   245 
   246 abstype state = State of
   247  {versions: version Inttab.table,  (*version_id -> document content*)
   248   commands: (string * Token.T list lazy) Inttab.table,  (*command_id -> name * span*)
   249   execution: version_id * Future.group}  (*current execution process*)
   250 with
   251 
   252 fun make_state (versions, commands, execution) =
   253   State {versions = versions, commands = commands, execution = execution};
   254 
   255 fun map_state f (State {versions, commands, execution}) =
   256   make_state (f (versions, commands, execution));
   257 
   258 val init_state =
   259   make_state (Inttab.make [(no_id, empty_version)], Inttab.empty, (no_id, Future.new_group NONE));
   260 
   261 
   262 (* document versions *)
   263 
   264 fun define_version (id: version_id) version =
   265   map_state (fn (versions, commands, execution) =>
   266     let val versions' = Inttab.update_new (id, version) versions
   267       handle Inttab.DUP dup => err_dup "document version" dup
   268     in (versions', commands, execution) end);
   269 
   270 fun the_version (State {versions, ...}) (id: version_id) =
   271   (case Inttab.lookup versions id of
   272     NONE => err_undef "document version" id
   273   | SOME version => version);
   274 
   275 fun delete_version (id: version_id) versions = Inttab.delete id versions
   276   handle Inttab.UNDEF _ => err_undef "document version" id;
   277 
   278 
   279 (* commands *)
   280 
   281 fun parse_command id text =
   282   Position.setmp_thread_data (Position.id_only id)
   283     (fn () =>
   284       let
   285         val toks = Thy_Syntax.parse_tokens (#1 (Outer_Syntax.get_syntax ())) (Position.id id) text;
   286         val _ = Output.status (Markup.markup_only Isabelle_Markup.parsed);
   287       in toks end) ();
   288 
   289 fun define_command (id: command_id) name text =
   290   map_state (fn (versions, commands, execution) =>
   291     let
   292       val span = Lazy.lazy (fn () => parse_command (print_id id) text);
   293       val commands' =
   294         Inttab.update_new (id, (name, span)) commands
   295           handle Inttab.DUP dup => err_dup "command" dup;
   296     in (versions, commands', execution) end);
   297 
   298 fun the_command (State {commands, ...}) (id: command_id) =
   299   (case Inttab.lookup commands id of
   300     NONE => err_undef "command" id
   301   | SOME command => command);
   302 
   303 
   304 (* document execution *)
   305 
   306 fun cancel_execution (State {execution, ...}) = Future.cancel_group (#2 execution);
   307 
   308 end;
   309 
   310 
   311 (* toplevel transactions *)
   312 
   313 local
   314 
   315 fun timing tr t =
   316   if Timing.is_relevant t then Toplevel.status tr (Isabelle_Markup.timing t) else ();
   317 
   318 fun proof_status tr st =
   319   (case try Toplevel.proof_of st of
   320     SOME prf => Toplevel.status tr (Proof.status_markup prf)
   321   | NONE => ());
   322 
   323 fun print_state tr st =
   324   (Lazy.lazy o Toplevel.setmp_thread_position tr)
   325     (fn () => Toplevel.print_state false st);
   326 
   327 fun run int tr st =
   328   (case Toplevel.transition int tr st of
   329     SOME (st', NONE) => ([], SOME st')
   330   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages exn, NONE)
   331   | NONE => ([(serial (), ML_Compiler.exn_message Runtime.TERMINATE)], NONE));
   332 
   333 in
   334 
   335 fun run_command tr st =
   336   let
   337     val is_init = Toplevel.is_init tr;
   338     val is_proof = Keyword.is_proof (Toplevel.name_of tr);
   339 
   340     val _ = Multithreading.interrupted ();
   341     val _ = Toplevel.status tr Isabelle_Markup.forked;
   342     val start = Timing.start ();
   343     val (errs, result) = run (is_init orelse is_proof) (Toplevel.set_print false tr) st;
   344     val _ = timing tr (Timing.result start);
   345     val _ = Toplevel.status tr Isabelle_Markup.joined;
   346     val _ = List.app (Toplevel.error_msg tr) errs;
   347   in
   348     (case result of
   349       NONE =>
   350         let
   351           val _ = if null errs then Exn.interrupt () else ();
   352           val _ = Toplevel.status tr Isabelle_Markup.failed;
   353         in (st, no_print) end
   354     | SOME st' =>
   355         let
   356           val _ = Toplevel.status tr Isabelle_Markup.finished;
   357           val _ = proof_status tr st';
   358           val do_print =
   359             not is_init andalso
   360               (Toplevel.print_of tr orelse (is_proof andalso Toplevel.is_proof st'));
   361         in (st', if do_print then print_state tr st' else no_print) end)
   362   end;
   363 
   364 end;
   365 
   366 
   367 
   368 
   369 (** update **)
   370 
   371 (* perspective *)
   372 
   373 fun update_perspective (old_id: version_id) (new_id: version_id) name perspective state =
   374   let
   375     val old_version = the_version state old_id;
   376     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 -- needed? *)
   377     val new_version = edit_nodes (name, Perspective perspective) old_version;
   378   in define_version new_id new_version state end;
   379 
   380 
   381 (* edits *)
   382 
   383 local
   384 
   385 fun last_common state last_visible node0 node =
   386   let
   387     fun update_flags prev (visible, initial) =
   388       let
   389         val visible' = visible andalso prev <> last_visible;
   390         val initial' = initial andalso
   391           (case prev of
   392             NONE => true
   393           | SOME id => not (Keyword.is_theory_begin (#1 (the_command state id))));
   394       in (visible', initial') end;
   395     fun get_common ((prev, id), exec) (found, (_, flags)) =
   396       if found then NONE
   397       else
   398         let val found' =
   399           is_none exec orelse op <> (pairself (Option.map #1) (exec, lookup_entry node0 id));
   400         in SOME (found', (prev, update_flags prev flags)) end;
   401     val (found, (common, flags)) =
   402       iterate_entries get_common node (false, (NONE, (true, true)));
   403   in
   404     if found then (common, flags)
   405     else
   406       let val last = Entries.get_after (get_entries node) common
   407       in (last, update_flags last flags) end
   408   end;
   409 
   410 fun illegal_init () = error "Illegal theory header after end of theory";
   411 
   412 fun new_exec state bad_init command_id' (execs, command_exec, init) =
   413   if bad_init andalso is_none init then NONE
   414   else
   415     let
   416       val (name, span) = the_command state command_id' ||> Lazy.force;
   417       val (modify_init, init') =
   418         if Keyword.is_theory_begin name then
   419           (Toplevel.modify_init (the_default illegal_init init), NONE)
   420         else (I, init);
   421       val exec_id' = new_id ();
   422       val exec_id'_string = print_id exec_id';
   423       val tr =
   424         Position.setmp_thread_data (Position.id_only exec_id'_string)
   425           (fn () =>
   426             #1 (Outer_Syntax.read_span (#2 (Outer_Syntax.get_syntax ())) span)
   427             |> modify_init
   428             |> Toplevel.put_id exec_id'_string);
   429       val exec' = snd (snd command_exec) |> Lazy.map (fn (st, _) => run_command (tr ()) st);
   430       val command_exec' = (command_id', (exec_id', exec'));
   431     in SOME (command_exec' :: execs, command_exec', init') end;
   432 
   433 fun make_required nodes =
   434   let
   435     val all_visible =
   436       Graph.fold (fn (a, (node, _)) => is_some (#2 (get_perspective node)) ? cons a) nodes []
   437       |> Graph.all_preds nodes;
   438     val required =
   439       fold (fn a => exists (fn b => Graph.is_edge nodes (a, b)) all_visible ? Symtab.update (a, ()))
   440         all_visible Symtab.empty;
   441   in Symtab.defined required end;
   442 
   443 fun check_theory nodes name =
   444   is_some (Thy_Info.lookup_theory name) orelse  (* FIXME more robust!? *)
   445   is_some (Exn.get_res (get_header (get_node nodes name)));
   446 
   447 fun init_theory deps node =
   448   let
   449     (* FIXME provide files via Scala layer, not master_dir *)
   450     val (master_dir, header) = Exn.release (get_header node);
   451     val parents =
   452       #imports header |> map (fn import =>
   453         (case Thy_Info.lookup_theory import of  (* FIXME more robust!? *)
   454           SOME thy => thy
   455         | NONE =>
   456             get_theory (Position.file_only import)
   457               (snd (Future.join (the (AList.lookup (op =) deps import))))));
   458   in Thy_Load.begin_theory (Path.explode master_dir) header parents end;
   459 
   460 in
   461 
   462 fun update (old_id: version_id) (new_id: version_id) edits state =
   463   let
   464     val old_version = the_version state old_id;
   465     val _ = Time.now ();  (* FIXME odd workaround for polyml-5.4.0/x86_64 *)
   466     val new_version = fold edit_nodes edits old_version;
   467 
   468     val nodes = nodes_of new_version;
   469     val is_required = make_required nodes;
   470 
   471     val updated =
   472       nodes |> Graph.schedule
   473         (fn deps => fn (name, node) =>
   474           if not (is_touched node orelse is_required name)
   475           then Future.value (([], [], []), node)
   476           else
   477             let
   478               val node0 = node_of old_version name;
   479               fun init () = init_theory deps node;
   480               val bad_init =
   481                 not (check_theory nodes name andalso forall (check_theory nodes o #1) deps);
   482             in
   483               (singleton o Future.forks)
   484                 {name = "Document.update", group = NONE,
   485                   deps = map (Future.task_of o #2) deps, pri = 0, interrupts = false}
   486                 (fn () =>
   487                   let
   488                     val required = is_required name;
   489                     val last_visible = #2 (get_perspective node);
   490                     val (common, (visible, initial)) = last_common state last_visible node0 node;
   491                     val common_command_exec = the_default_entry node common;
   492 
   493                     val (execs, (command_id, (_, exec)), _) =
   494                       ([], common_command_exec, if initial then SOME init else NONE) |>
   495                       (visible orelse required) ?
   496                         iterate_entries_after common
   497                           (fn ((prev, id), _) => fn res =>
   498                             if not required andalso prev = last_visible then NONE
   499                             else new_exec state bad_init id res) node;
   500 
   501                     val no_execs =
   502                       iterate_entries_after common
   503                         (fn ((_, id0), exec0) => fn res =>
   504                           if is_none exec0 then NONE
   505                           else if exists (fn (_, (id, _)) => id0 = id) execs then SOME res
   506                           else SOME (id0 :: res)) node0 [];
   507 
   508                     val last_exec = if command_id = no_id then NONE else SOME command_id;
   509                     val result =
   510                       if is_some (after_entry node last_exec) then no_result
   511                       else Lazy.map #1 exec;
   512 
   513                     val node' = node
   514                       |> fold reset_entry no_execs
   515                       |> fold (fn (id, exec) => update_entry id (SOME exec)) execs
   516                       |> set_last_exec last_exec
   517                       |> set_result result
   518                       |> set_touched false;
   519                   in ((no_execs, execs, [(name, node')]), node') end)
   520             end)
   521       |> Future.joins |> map #1;
   522 
   523     val command_execs =
   524       map (rpair NONE) (maps #1 updated) @
   525       map (fn (command_id, (exec_id, _)) => (command_id, SOME exec_id)) (maps #2 updated);
   526     val updated_nodes = maps #3 updated;
   527     val last_execs = map (fn (name, node) => (name, get_last_exec node)) updated_nodes;
   528 
   529     val state' = state
   530       |> define_version new_id (fold put_node updated_nodes new_version);
   531   in ((command_execs, last_execs), state') end;
   532 
   533 end;
   534 
   535 
   536 (* execute *)
   537 
   538 fun execute version_id state =
   539   state |> map_state (fn (versions, commands, _) =>
   540     let
   541       val version = the_version state version_id;
   542 
   543       fun force_exec _ _ NONE = ()
   544         | force_exec node command_id (SOME (_, exec)) =
   545             let
   546               val (_, print) = Lazy.force exec;
   547               val _ =
   548                 if #1 (get_perspective node) command_id
   549                 then ignore (Lazy.future Future.default_params print)
   550                 else ();
   551             in () end;
   552 
   553       val group = Future.new_group NONE;
   554       val _ =
   555         nodes_of version |> Graph.schedule
   556           (fn deps => fn (name, node) =>
   557             (singleton o Future.forks)
   558               {name = "theory:" ^ name, group = SOME (Future.new_group (SOME group)),
   559                 deps = map (Future.task_of o #2) deps, pri = 1, interrupts = false}
   560               (iterate_entries (fn ((_, id), exec) => fn () =>
   561                 SOME (force_exec node id exec)) node));
   562 
   563     in (versions, commands, (version_id, group)) end);
   564 
   565 
   566 (* remove versions *)
   567 
   568 fun remove_versions ids state = state |> map_state (fn (versions, _, execution) =>
   569   let
   570     val _ = member (op =) ids (#1 execution) andalso
   571       error ("Attempt to remove execution version " ^ print_id (#1 execution));
   572 
   573     val versions' = fold delete_version ids versions;
   574     val commands' =
   575       (versions', Inttab.empty) |->
   576         Inttab.fold (fn (_, version) => nodes_of version |>
   577           Graph.fold (fn (_, (node, _)) => node |>
   578             iterate_entries (fn ((_, id), _) =>
   579               SOME o Inttab.insert (K true) (id, the_command state id))));
   580   in (versions', commands', execution) end);
   581 
   582 
   583 
   584 (** global state **)
   585 
   586 val global_state = Synchronized.var "Document" init_state;
   587 
   588 fun state () = Synchronized.value global_state;
   589 val change_state = Synchronized.change global_state;
   590 
   591 end;
   592