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