src/Pure/PIDE/document.scala
author wenzelm
Sun Feb 26 16:02:53 2012 +0100 (2012-02-26 ago)
changeset 46677 388ba4daae05
parent 46208 4cab63a6dc16
child 46678 c2dba08548f9
permissions -rw-r--r--
tuned;
     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   /* named nodes -- development graph */
    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   type Node_Header = Exn.Result[Thy_Header]
    39 
    40   object Node
    41   {
    42     object Name
    43     {
    44       val empty = Name("", "", "")
    45       def apply(path: Path): Name =
    46       {
    47         val node = path.implode
    48         val dir = path.dir.implode
    49         val theory = Thy_Header.thy_name(node) getOrElse error("Bad theory file name: " + path)
    50         Name(node, dir, theory)
    51       }
    52     }
    53     sealed case class Name(node: String, dir: String, theory: String)
    54     {
    55       override def hashCode: Int = node.hashCode
    56       override def equals(that: Any): Boolean =
    57         that match {
    58           case other: Name => node == other.node
    59           case _ => false
    60         }
    61       override def toString: String = theory
    62     }
    63 
    64     sealed abstract class Edit[A, B]
    65     {
    66       def foreach(f: A => Unit)
    67       {
    68         this match {
    69           case Edits(es) => es.foreach(f)
    70           case _ =>
    71         }
    72       }
    73     }
    74     case class Clear[A, B]() extends Edit[A, B]
    75     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
    76     case class Header[A, B](header: Node_Header) extends Edit[A, B]
    77     case class Perspective[A, B](perspective: B) extends Edit[A, B]
    78 
    79     def norm_header(f: String => String, g: String => String, header: Node_Header): Node_Header =
    80       header match {
    81         case Exn.Res(h) => Exn.capture { h.norm_deps(f, g) }
    82         case exn => exn
    83       }
    84 
    85     val empty: Node = Node()
    86 
    87     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    88       : Iterator[(Command, Text.Offset)] =
    89     {
    90       var i = offset
    91       for (command <- commands) yield {
    92         val start = i
    93         i += command.length
    94         (command, start)
    95       }
    96     }
    97   }
    98 
    99   private val block_size = 1024
   100 
   101   sealed case class Node(
   102     val header: Node_Header = Exn.Exn(ERROR("Bad theory header")),
   103     val perspective: Command.Perspective = Command.Perspective.empty,
   104     val blobs: Map[String, Blob] = Map.empty,
   105     val commands: Linear_Set[Command] = Linear_Set.empty)
   106   {
   107     def clear: Node = Node.empty.copy(header = header)
   108 
   109 
   110     /* commands */
   111 
   112     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   113     {
   114       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   115       var next_block = 0
   116       var last_stop = 0
   117       for ((command, start) <- Node.command_starts(commands.iterator)) {
   118         last_stop = start + command.length
   119         while (last_stop + 1 > next_block) {
   120           blocks += (command -> start)
   121           next_block += block_size
   122         }
   123       }
   124       (blocks.toArray, Text.Range(0, last_stop))
   125     }
   126 
   127     def full_range: Text.Range = full_index._2
   128 
   129     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   130     {
   131       if (!commands.isEmpty && full_range.contains(i)) {
   132         val (cmd0, start0) = full_index._1(i / block_size)
   133         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   134           case (cmd, start) => start + cmd.length <= i }
   135       }
   136       else Iterator.empty
   137     }
   138 
   139     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   140       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   141 
   142     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   143     {
   144       val range = command_range(i)
   145       if (range.hasNext) Some(range.next) else None
   146     }
   147 
   148     def proper_command_at(i: Text.Offset): Option[Command] =
   149       command_at(i) match {
   150         case Some((command, _)) =>
   151           commands.reverse_iterator(command).find(cmd => !cmd.is_ignored)
   152         case None => None
   153       }
   154 
   155     def command_start(cmd: Command): Option[Text.Offset] =
   156       Node.command_starts(commands.iterator).find(_._1 == cmd).map(_._2)
   157   }
   158 
   159 
   160 
   161   /** versioning **/
   162 
   163   /* particular document versions */
   164 
   165   type Nodes = Map[Node.Name, Node]
   166 
   167   object Version
   168   {
   169     val init: Version = Version()
   170   }
   171 
   172   sealed case class Version(
   173     val id: Version_ID = no_id,
   174     val nodes: Nodes = Map.empty.withDefaultValue(Node.empty))
   175   {
   176     def topological_order: List[Node.Name] =
   177     {
   178       val names = nodes.map({ case (name, node) => (name.node -> name) })
   179       def next(x: Node.Name): List[Node.Name] =
   180         nodes(x).header match {
   181           case Exn.Res(header) =>
   182             for (imp <- header.imports; name <- names.get(imp)) yield(name)
   183           case Exn.Exn(_) => Nil
   184         }
   185       Library.topological_order(next, nodes.keys.toList.sortBy(_.node))
   186     }
   187   }
   188 
   189 
   190   /* changes of plain text, eventually resulting in document edits */
   191 
   192   object Change
   193   {
   194     val init: Change = Change()
   195   }
   196 
   197   sealed case class Change(
   198     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   199     val edits: List[Edit_Text] = Nil,
   200     val version: Future[Version] = Future.value(Version.init))
   201   {
   202     def is_finished: Boolean =
   203       (previous match { case None => true case Some(future) => future.is_finished }) &&
   204       version.is_finished
   205 
   206     def truncate: Change = copy(previous = None, edits = Nil)
   207   }
   208 
   209 
   210   /* history navigation */
   211 
   212   object History
   213   {
   214     val init: History = History()
   215   }
   216 
   217   // FIXME pruning, purging of state
   218   sealed case class History(val undo_list: List[Change] = List(Change.init))
   219   {
   220     require(!undo_list.isEmpty)
   221 
   222     def tip: Change = undo_list.head
   223     def +(change: Change): History = copy(undo_list = change :: undo_list)
   224   }
   225 
   226 
   227 
   228   /** global state -- document structure, execution process, editing history **/
   229 
   230   abstract class Snapshot
   231   {
   232     val state: State
   233     val version: Version
   234     val node: Node
   235     val is_outdated: Boolean
   236     def convert(i: Text.Offset): Text.Offset
   237     def convert(range: Text.Range): Text.Range
   238     def revert(i: Text.Offset): Text.Offset
   239     def revert(range: Text.Range): Text.Range
   240     def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   241       result: PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]]
   242     def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   243       result: PartialFunction[Text.Markup, A]): Stream[Text.Info[A]]
   244   }
   245 
   246   type Assign =
   247    (List[(Document.Command_ID, Option[Document.Exec_ID])],  // exec state assignment
   248     List[(String, Option[Document.Command_ID])])  // last exec
   249 
   250   val no_assign: Assign = (Nil, Nil)
   251 
   252   object State
   253   {
   254     class Fail(state: State) extends Exception
   255 
   256     val init: State =
   257       State().define_version(Version.init, Assignment.init).assign(Version.init.id, no_assign)._2
   258 
   259     object Assignment
   260     {
   261       val init: Assignment = Assignment()
   262     }
   263 
   264     case class Assignment(
   265       val command_execs: Map[Command_ID, Exec_ID] = Map.empty,
   266       val last_execs: Map[String, Option[Command_ID]] = Map.empty,
   267       val is_finished: Boolean = false)
   268     {
   269       def check_finished: Assignment = { require(is_finished); this }
   270       def unfinished: Assignment = copy(is_finished = false)
   271 
   272       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])],
   273         add_last_execs: List[(String, Option[Command_ID])]): Assignment =
   274       {
   275         require(!is_finished)
   276         val command_execs1 =
   277           (command_execs /: add_command_execs) {
   278             case (res, (command_id, None)) => res - command_id
   279             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   280           }
   281         Assignment(command_execs1, last_execs ++ add_last_execs, true)
   282       }
   283     }
   284   }
   285 
   286   sealed case class State(
   287     val versions: Map[Version_ID, Version] = Map.empty,
   288     val commands: Map[Command_ID, Command.State] = Map.empty,  // static markup from define_command
   289     val execs: Map[Exec_ID, Command.State] = Map.empty,  // dynamic markup from execution
   290     val assignments: Map[Version_ID, State.Assignment] = Map.empty,
   291     val history: History = History.init)
   292   {
   293     private def fail[A]: A = throw new State.Fail(this)
   294 
   295     def define_version(version: Version, assignment: State.Assignment): State =
   296     {
   297       val id = version.id
   298       copy(versions = versions + (id -> version),
   299         assignments = assignments + (id -> assignment.unfinished))
   300     }
   301 
   302     def define_command(command: Command): State =
   303     {
   304       val id = command.id
   305       copy(commands = commands + (id -> command.empty_state))
   306     }
   307 
   308     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   309 
   310     def find_command(version: Version, id: ID): Option[(Node, Command)] =
   311       commands.get(id) orElse execs.get(id) match {
   312         case None => None
   313         case Some(st) =>
   314           val command = st.command
   315           version.nodes.get(command.node_name).map((_, command))
   316       }
   317 
   318     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   319     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   320     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   321     def the_assignment(version: Version): State.Assignment =
   322       assignments.getOrElse(version.id, fail)
   323 
   324     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   325       execs.get(id) match {
   326         case Some(st) =>
   327           val new_st = st + message
   328           (new_st, copy(execs = execs + (id -> new_st)))
   329         case None =>
   330           commands.get(id) match {
   331             case Some(st) =>
   332               val new_st = st + message
   333               (new_st, copy(commands = commands + (id -> new_st)))
   334             case None => fail
   335           }
   336       }
   337 
   338     def assign(id: Version_ID, arg: Assign): (List[Command], State) =
   339     {
   340       val version = the_version(id)
   341       val (command_execs, last_execs) = arg
   342 
   343       val (changed_commands, new_execs) =
   344         ((Nil: List[Command], execs) /: command_execs) {
   345           case ((commands1, execs1), (cmd_id, exec)) =>
   346             val st = the_command(cmd_id)
   347             val commands2 = st.command :: commands1
   348             val execs2 =
   349               exec match {
   350                 case None => execs1
   351                 case Some(exec_id) => execs1 + (exec_id -> st)
   352               }
   353             (commands2, execs2)
   354         }
   355       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   356       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   357 
   358       (changed_commands, new_state)
   359     }
   360 
   361     def is_assigned(version: Version): Boolean =
   362       assignments.get(version.id) match {
   363         case Some(assgn) => assgn.is_finished
   364         case None => false
   365       }
   366 
   367     def is_stable(change: Change): Boolean =
   368       change.is_finished && is_assigned(change.version.get_finished)
   369 
   370     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   371     def tip_stable: Boolean = is_stable(history.tip)
   372     def tip_version: Version = history.tip.version.get_finished
   373 
   374     def last_exec_offset(name: Node.Name): Text.Offset =
   375     {
   376       val version = tip_version
   377       the_assignment(version).last_execs.get(name.node) match {
   378         case Some(Some(id)) =>
   379           val node = version.nodes(name)
   380           val cmd = the_command(id).command
   381           node.command_start(cmd) match {
   382             case None => 0
   383             case Some(start) => start + cmd.length
   384           }
   385         case _ => 0
   386       }
   387     }
   388 
   389     def continue_history(
   390         previous: Future[Version],
   391         edits: List[Edit_Text],
   392         version: Future[Version]): (Change, State) =
   393     {
   394       val change = Change(Some(previous), edits, version)
   395       (change, copy(history = history + change))
   396     }
   397 
   398     def prune_history(retain: Int = 0): (List[Version], State) =
   399     {
   400       val undo_list = history.undo_list
   401       val n = undo_list.iterator.zipWithIndex.find(p => is_stable(p._1)).get._2 + 1
   402       val (retained, dropped) = undo_list.splitAt(n max retain)
   403 
   404       retained.splitAt(retained.length - 1) match {
   405         case (prefix, List(last)) =>
   406           val dropped_versions = dropped.map(change => change.version.get_finished)
   407           val state1 = copy(history = History(prefix ::: List(last.truncate)))
   408           (dropped_versions, state1)
   409         case _ => fail
   410       }
   411     }
   412 
   413     def removed_versions(removed: List[Version_ID]): State =
   414     {
   415       val versions1 = versions -- removed
   416       val assignments1 = assignments -- removed
   417       var commands1 = Map.empty[Command_ID, Command.State]
   418       var execs1 = Map.empty[Exec_ID, Command.State]
   419       for {
   420         (version_id, version) <- versions1.iterator
   421         val command_execs = assignments1(version_id).command_execs
   422         (_, node) <- version.nodes.iterator
   423         command <- node.commands.iterator
   424       } {
   425         val id = command.id
   426         if (!commands1.isDefinedAt(id) && commands.isDefinedAt(id))
   427           commands1 += (id -> commands(id))
   428         if (command_execs.isDefinedAt(id)) {
   429           val exec_id = command_execs(id)
   430           if (!execs1.isDefinedAt(exec_id) && execs.isDefinedAt(exec_id))
   431             execs1 += (exec_id -> execs(exec_id))
   432         }
   433       }
   434       copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
   435     }
   436 
   437     def command_state(version: Version, command: Command): Command.State =
   438     {
   439       require(is_assigned(version))
   440       try {
   441         the_exec(the_assignment(version).check_finished.command_execs
   442           .getOrElse(command.id, fail))
   443       }
   444       catch { case _: State.Fail => command.empty_state }
   445     }
   446 
   447 
   448     // persistent user-view
   449     def snapshot(name: Node.Name, pending_edits: List[Text.Edit]): Snapshot =
   450     {
   451       val stable = recent_stable
   452       val latest = history.tip
   453 
   454       // FIXME proper treatment of removed nodes
   455       val edits =
   456         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   457             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   458       lazy val reverse_edits = edits.reverse
   459 
   460       new Snapshot
   461       {
   462         val state = State.this
   463         val version = stable.version.get_finished
   464         val node = version.nodes(name)
   465         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   466 
   467         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   468         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   469         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   470         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   471 
   472         def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   473           result: PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]] =
   474         {
   475           val former_range = revert(range)
   476           for {
   477             (command, command_start) <- node.command_range(former_range).toStream
   478             Text.Info(r0, a) <- state.command_state(version, command).markup.
   479               cumulate[A]((former_range - command_start).restrict(command.range), info, elements,
   480                 {
   481                   case (a, Text.Info(r0, b))
   482                   if result.isDefinedAt((a, Text.Info(convert(r0 + command_start), b))) =>
   483                     result((a, Text.Info(convert(r0 + command_start), b)))
   484                 })
   485           } yield Text.Info(convert(r0 + command_start), a)
   486         }
   487 
   488         def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   489           result: PartialFunction[Text.Markup, A]): Stream[Text.Info[A]] =
   490         {
   491           val result1 =
   492             new PartialFunction[(Option[A], Text.Markup), Option[A]] {
   493               def isDefinedAt(arg: (Option[A], Text.Markup)): Boolean = result.isDefinedAt(arg._2)
   494               def apply(arg: (Option[A], Text.Markup)): Option[A] = Some(result(arg._2))
   495             }
   496           for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
   497             yield Text.Info(r, x)
   498         }
   499       }
   500     }
   501   }
   502 }
   503