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