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