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