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