src/Pure/PIDE/document.scala
author wenzelm
Thu Dec 13 13:52:18 2012 +0100 (2012-12-13)
changeset 50500 c94bba7906d2
parent 50204 daeb1674fb91
child 51293 05b1bbae748d
permissions -rw-r--r--
identify dialogs via official serial and maintain as result message;
clarified Protocol.is_inlined: suppress result/tracing/state messages uniformly;
cumulate_markup/select_markup depending on command state;
explicit Rendering.output_messages;
tuned source structure;
     1 /*  Title:      Pure/PIDE/document.scala
     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 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 
    13 
    14 object Document
    15 {
    16   /* formal identifiers */
    17 
    18   type ID = Long
    19   val ID = Properties.Value.Long
    20 
    21   type Version_ID = ID
    22   type Command_ID = ID
    23   type Exec_ID = ID
    24 
    25   val no_id: ID = 0
    26   val new_id = Counter()
    27 
    28 
    29 
    30   /** document structure **/
    31 
    32   /* individual nodes */
    33 
    34   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    35   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    36   type Edit_Command = Edit[(Option[Command], Option[Command]), Command.Perspective]
    37 
    38   object Node
    39   {
    40     sealed case class Header(
    41       imports: List[Name],
    42       keywords: Thy_Header.Keywords,
    43       uses: List[(String, Boolean)],
    44       errors: List[String] = Nil)
    45     {
    46       def error(msg: String): Header = copy(errors = errors ::: List(msg))
    47     }
    48 
    49     def bad_header(msg: String): Header = Header(Nil, Nil, Nil, List(msg))
    50 
    51     object Name
    52     {
    53       val empty = Name("", "", "")
    54 
    55       object Ordering extends scala.math.Ordering[Name]
    56       {
    57         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
    58       }
    59     }
    60     sealed case class Name(node: String, dir: String, theory: String)
    61     {
    62       override def hashCode: Int = node.hashCode
    63       override def equals(that: Any): Boolean =
    64         that match {
    65           case other: Name => node == other.node
    66           case _ => false
    67         }
    68       override def toString: String = theory
    69     }
    70 
    71     sealed abstract class Edit[A, B]
    72     {
    73       def foreach(f: A => Unit)
    74       {
    75         this match {
    76           case Edits(es) => es.foreach(f)
    77           case _ =>
    78         }
    79       }
    80     }
    81     case class Clear[A, B]() extends Edit[A, B]
    82     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
    83     case class Deps[A, B](header: Header) extends Edit[A, B]
    84     case class Perspective[A, B](perspective: B) extends Edit[A, B]
    85 
    86     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    87       : Iterator[(Command, Text.Offset)] =
    88     {
    89       var i = offset
    90       for (command <- commands) yield {
    91         val start = i
    92         i += command.length
    93         (command, start)
    94       }
    95     }
    96 
    97     private val block_size = 1024
    98 
    99     val empty: Node = new Node()
   100   }
   101 
   102   final class Node private(
   103     val header: Node.Header = Node.bad_header("Bad theory header"),
   104     val perspective: Command.Perspective = Command.Perspective.empty,
   105     val commands: Linear_Set[Command] = Linear_Set.empty)
   106   {
   107     def clear: Node = new Node(header = header)
   108 
   109     def update_header(new_header: Node.Header): Node =
   110       new Node(new_header, perspective, commands)
   111 
   112     def update_perspective(new_perspective: Command.Perspective): Node =
   113       new Node(header, new_perspective, commands)
   114 
   115     def update_commands(new_commands: Linear_Set[Command]): Node =
   116       new Node(header, perspective, new_commands)
   117 
   118 
   119     /* commands */
   120 
   121     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   122     {
   123       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   124       var next_block = 0
   125       var last_stop = 0
   126       for ((command, start) <- Node.command_starts(commands.iterator)) {
   127         last_stop = start + command.length
   128         while (last_stop + 1 > next_block) {
   129           blocks += (command -> start)
   130           next_block += Node.block_size
   131         }
   132       }
   133       (blocks.toArray, Text.Range(0, last_stop))
   134     }
   135 
   136     def full_range: Text.Range = full_index._2
   137 
   138     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   139     {
   140       if (!commands.isEmpty && full_range.contains(i)) {
   141         val (cmd0, start0) = full_index._1(i / Node.block_size)
   142         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   143           case (cmd, start) => start + cmd.length <= i }
   144       }
   145       else Iterator.empty
   146     }
   147 
   148     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   149       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   150 
   151     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   152     {
   153       val range = command_range(i)
   154       if (range.hasNext) Some(range.next) else None
   155     }
   156 
   157     def command_start(cmd: Command): Option[Text.Offset] =
   158       Node.command_starts(commands.iterator).find(_._1 == cmd).map(_._2)
   159   }
   160 
   161 
   162   /* development graph */
   163 
   164   object Nodes
   165   {
   166     val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
   167   }
   168 
   169   final class Nodes private(graph: Graph[Node.Name, Node])
   170   {
   171     def get_name(s: String): Option[Node.Name] =
   172       graph.keys.find(name => name.node == s)
   173 
   174     def apply(name: Node.Name): Node =
   175       graph.default_node(name, Node.empty).get_node(name)
   176 
   177     def + (entry: (Node.Name, Node)): Nodes =
   178     {
   179       val (name, node) = entry
   180       val imports = node.header.imports
   181       val graph1 =
   182         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   183       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   184       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   185       new Nodes(graph3.map_node(name, _ => node))
   186     }
   187 
   188     def entries: Iterator[(Node.Name, Node)] =
   189       graph.entries.map({ case (name, (node, _)) => (name, node) })
   190 
   191     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   192     def topological_order: List[Node.Name] = graph.topological_order
   193   }
   194 
   195 
   196 
   197   /** versioning **/
   198 
   199   /* particular document versions */
   200 
   201   object Version
   202   {
   203     val init: Version = new Version()
   204 
   205     def make(syntax: Outer_Syntax, nodes: Nodes): Version =
   206       new Version(new_id(), syntax, nodes)
   207   }
   208 
   209   final class Version private(
   210     val id: Version_ID = no_id,
   211     val syntax: Outer_Syntax = Outer_Syntax.empty,
   212     val nodes: Nodes = Nodes.empty)
   213   {
   214     def is_init: Boolean = id == no_id
   215   }
   216 
   217 
   218   /* changes of plain text, eventually resulting in document edits */
   219 
   220   object Change
   221   {
   222     val init: Change = new Change()
   223 
   224     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   225       new Change(Some(previous), edits, version)
   226   }
   227 
   228   final class Change private(
   229     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   230     val edits: List[Edit_Text] = Nil,
   231     val version: Future[Version] = Future.value(Version.init))
   232   {
   233     def is_finished: Boolean =
   234       (previous match { case None => true case Some(future) => future.is_finished }) &&
   235       version.is_finished
   236 
   237     def truncate: Change = new Change(None, Nil, version)
   238   }
   239 
   240 
   241   /* history navigation */
   242 
   243   object History
   244   {
   245     val init: History = new History()
   246   }
   247 
   248   final class History private(
   249     val undo_list: List[Change] = List(Change.init))  // non-empty list
   250   {
   251     def tip: Change = undo_list.head
   252     def + (change: Change): History = new History(change :: undo_list)
   253 
   254     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   255     {
   256       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   257       val (retained, dropped) = undo_list.splitAt(n max retain)
   258 
   259       retained.splitAt(retained.length - 1) match {
   260         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   261         case _ => None
   262       }
   263     }
   264   }
   265 
   266 
   267 
   268   /** global state -- document structure, execution process, editing history **/
   269 
   270   abstract class Snapshot
   271   {
   272     val state: State
   273     val version: Version
   274     val node_name: Node.Name
   275     val node: Node
   276     val is_outdated: Boolean
   277     def convert(i: Text.Offset): Text.Offset
   278     def convert(range: Text.Range): Text.Range
   279     def revert(i: Text.Offset): Text.Offset
   280     def revert(range: Text.Range): Text.Range
   281     def eq_markup(other: Snapshot): Boolean
   282     def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   283       result: Command.State => PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]]
   284     def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   285       result: Command.State => PartialFunction[Text.Markup, A]): Stream[Text.Info[A]]
   286   }
   287 
   288   type Assign = List[(Document.Command_ID, Option[Document.Exec_ID])]  // exec state assignment
   289 
   290   object State
   291   {
   292     class Fail(state: State) extends Exception
   293 
   294     object Assignment
   295     {
   296       val init: Assignment = new Assignment()
   297     }
   298 
   299     final class Assignment private(
   300       val command_execs: Map[Command_ID, Exec_ID] = Map.empty,
   301       val is_finished: Boolean = false)
   302     {
   303       def check_finished: Assignment = { require(is_finished); this }
   304       def unfinished: Assignment = new Assignment(command_execs, false)
   305 
   306       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])]): Assignment =
   307       {
   308         require(!is_finished)
   309         val command_execs1 =
   310           (command_execs /: add_command_execs) {
   311             case (res, (command_id, None)) => res - command_id
   312             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   313           }
   314         new Assignment(command_execs1, true)
   315       }
   316     }
   317 
   318     val init: State =
   319       State().define_version(Version.init, Assignment.init).assign(Version.init.id)._2
   320   }
   321 
   322   final case class State private(
   323     val versions: Map[Version_ID, Version] = Map.empty,
   324     val commands: Map[Command_ID, Command.State] = Map.empty,  // static markup from define_command
   325     val execs: Map[Exec_ID, Command.State] = Map.empty,  // dynamic markup from execution
   326     val assignments: Map[Version_ID, State.Assignment] = Map.empty,
   327     val history: History = History.init)
   328   {
   329     private def fail[A]: A = throw new State.Fail(this)
   330 
   331     def define_version(version: Version, assignment: State.Assignment): State =
   332     {
   333       val id = version.id
   334       copy(versions = versions + (id -> version),
   335         assignments = assignments + (id -> assignment.unfinished))
   336     }
   337 
   338     def define_command(command: Command): State =
   339     {
   340       val id = command.id
   341       copy(commands = commands + (id -> command.init_state))
   342     }
   343 
   344     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   345 
   346     def find_command(version: Version, id: ID): Option[(Node, Command)] =
   347       commands.get(id) orElse execs.get(id) match {
   348         case None => None
   349         case Some(st) =>
   350           val command = st.command
   351           val node = version.nodes(command.node_name)
   352           Some((node, command))
   353       }
   354 
   355     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   356     def the_command_state(id: Command_ID): Command.State = commands.getOrElse(id, fail)
   357     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   358     def the_assignment(version: Version): State.Assignment =
   359       assignments.getOrElse(version.id, fail)
   360 
   361     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   362       execs.get(id) match {
   363         case Some(st) =>
   364           val new_st = st + (id, message)
   365           (new_st, copy(execs = execs + (id -> new_st)))
   366         case None =>
   367           commands.get(id) match {
   368             case Some(st) =>
   369               val new_st = st + (id, message)
   370               (new_st, copy(commands = commands + (id -> new_st)))
   371             case None => fail
   372           }
   373       }
   374 
   375     def assign(id: Version_ID, command_execs: Assign = Nil): (List[Command], State) =
   376     {
   377       val version = the_version(id)
   378 
   379       val (changed_commands, new_execs) =
   380         ((Nil: List[Command], execs) /: command_execs) {
   381           case ((commands1, execs1), (cmd_id, exec)) =>
   382             val st = the_command_state(cmd_id)
   383             val commands2 = st.command :: commands1
   384             val execs2 =
   385               exec match {
   386                 case None => execs1
   387                 case Some(exec_id) => execs1 + (exec_id -> st)
   388               }
   389             (commands2, execs2)
   390         }
   391       val new_assignment = the_assignment(version).assign(command_execs)
   392       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   393 
   394       (changed_commands, new_state)
   395     }
   396 
   397     def is_assigned(version: Version): Boolean =
   398       assignments.get(version.id) match {
   399         case Some(assgn) => assgn.is_finished
   400         case None => false
   401       }
   402 
   403     def is_stable(change: Change): Boolean =
   404       change.is_finished && is_assigned(change.version.get_finished)
   405 
   406     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   407     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   408     def tip_stable: Boolean = is_stable(history.tip)
   409     def tip_version: Version = history.tip.version.get_finished
   410 
   411     def continue_history(
   412         previous: Future[Version],
   413         edits: List[Edit_Text],
   414         version: Future[Version]): (Change, State) =
   415     {
   416       val change = Change.make(previous, edits, version)
   417       (change, copy(history = history + change))
   418     }
   419 
   420     def prune_history(retain: Int = 0): (List[Version], State) =
   421     {
   422       history.prune(is_stable, retain) match {
   423         case Some((dropped, history1)) =>
   424           val dropped_versions = dropped.map(change => change.version.get_finished)
   425           val state1 = copy(history = history1)
   426           (dropped_versions, state1)
   427         case None => fail
   428       }
   429     }
   430 
   431     def removed_versions(removed: List[Version_ID]): State =
   432     {
   433       val versions1 = versions -- removed
   434       val assignments1 = assignments -- removed
   435       var commands1 = Map.empty[Command_ID, Command.State]
   436       var execs1 = Map.empty[Exec_ID, Command.State]
   437       for {
   438         (version_id, version) <- versions1.iterator
   439         command_execs = assignments1(version_id).command_execs
   440         (_, node) <- version.nodes.entries
   441         command <- node.commands.iterator
   442       } {
   443         val id = command.id
   444         if (!commands1.isDefinedAt(id) && commands.isDefinedAt(id))
   445           commands1 += (id -> commands(id))
   446         if (command_execs.isDefinedAt(id)) {
   447           val exec_id = command_execs(id)
   448           if (!execs1.isDefinedAt(exec_id) && execs.isDefinedAt(exec_id))
   449             execs1 += (exec_id -> execs(exec_id))
   450         }
   451       }
   452       copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
   453     }
   454 
   455     def command_state(version: Version, command: Command): Command.State =
   456     {
   457       require(is_assigned(version))
   458       try {
   459         the_exec(the_assignment(version).check_finished.command_execs
   460           .getOrElse(command.id, fail))
   461       }
   462       catch {
   463         case _: State.Fail =>
   464           try { the_command_state(command.id) }
   465           catch { case _: State.Fail => command.init_state }
   466       }
   467     }
   468 
   469     def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
   470       node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
   471 
   472     // persistent user-view
   473     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   474       : Snapshot =
   475     {
   476       val stable = recent_stable
   477       val latest = history.tip
   478 
   479       // FIXME proper treatment of removed nodes
   480       val edits =
   481         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   482             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   483       lazy val reverse_edits = edits.reverse
   484 
   485       new Snapshot
   486       {
   487         val state = State.this
   488         val version = stable.version.get_finished
   489         val node_name = name
   490         val node = version.nodes(name)
   491         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   492 
   493         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   494         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   495         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   496         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   497 
   498         def eq_markup(other: Snapshot): Boolean =
   499           !is_outdated && !other.is_outdated &&
   500             node.commands.size == other.node.commands.size &&
   501             ((node.commands.iterator zip other.node.commands.iterator) forall {
   502               case (cmd1, cmd2) =>
   503                 cmd1.source == cmd2.source &&
   504                 (state.command_state(version, cmd1).markup eq
   505                  other.state.command_state(other.version, cmd2).markup)
   506             })
   507 
   508         def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   509           result: Command.State => PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]] =
   510         {
   511           val former_range = revert(range)
   512           for {
   513             (command, command_start) <- node.command_range(former_range).toStream
   514             st = state.command_state(version, command)
   515             res = result(st)
   516             Text.Info(r0, a) <- st.markup.
   517               cumulate[A]((former_range - command_start).restrict(command.range), info, elements,
   518                 {
   519                   case (a, Text.Info(r0, b))
   520                   if res.isDefinedAt((a, Text.Info(convert(r0 + command_start), b))) =>
   521                     res((a, Text.Info(convert(r0 + command_start), b)))
   522                 })
   523           } yield Text.Info(convert(r0 + command_start), a)
   524         }
   525 
   526         def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   527           result: Command.State => PartialFunction[Text.Markup, A]): Stream[Text.Info[A]] =
   528         {
   529           def result1(st: Command.State) =
   530           {
   531             val res = result(st)
   532             new PartialFunction[(Option[A], Text.Markup), Option[A]] {
   533               def isDefinedAt(arg: (Option[A], Text.Markup)): Boolean = res.isDefinedAt(arg._2)
   534               def apply(arg: (Option[A], Text.Markup)): Option[A] = Some(res(arg._2))
   535             }
   536           }
   537           for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
   538             yield Text.Info(r, x)
   539         }
   540       }
   541     }
   542   }
   543 }
   544