src/Pure/PIDE/document.scala
author wenzelm
Sat Nov 12 11:45:49 2011 +0100 (2011-11-12 ago)
changeset 45467 3f290b6288cf
parent 45459 a5c1599f664d
child 45468 33e946d3f449
permissions -rw-r--r--
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,
   187         Library.sort_wrt((name: Node.Name) => name.node, nodes.keys.toList))
   188     }
   189   }
   190 
   191 
   192   /* changes of plain text, eventually resulting in document edits */
   193 
   194   object Change
   195   {
   196     val init: Change = Change(Some(Future.value(Version.init)), Nil, Future.value(Version.init))
   197   }
   198 
   199   sealed case class Change(
   200     val previous: Option[Future[Version]],
   201     val edits: List[Edit_Text],
   202     val version: Future[Version])
   203   {
   204     def is_finished: Boolean =
   205       (previous match { case None => true case Some(future) => future.is_finished }) &&
   206       version.is_finished
   207 
   208     def truncate: Change = copy(previous = None, edits = Nil)
   209   }
   210 
   211 
   212   /* history navigation */
   213 
   214   object History
   215   {
   216     val init: History = History(List(Change.init))
   217   }
   218 
   219   // FIXME pruning, purging of state
   220   sealed case class History(val undo_list: List[Change])
   221   {
   222     require(!undo_list.isEmpty)
   223 
   224     def tip: Change = undo_list.head
   225     def +(change: Change): History = copy(undo_list = change :: undo_list)
   226   }
   227 
   228 
   229 
   230   /** global state -- document structure, execution process, editing history **/
   231 
   232   abstract class Snapshot
   233   {
   234     val state: State
   235     val version: Version
   236     val node: Node
   237     val is_outdated: Boolean
   238     def command_state(command: Command): Command.State
   239     def convert(i: Text.Offset): Text.Offset
   240     def convert(range: Text.Range): Text.Range
   241     def revert(i: Text.Offset): Text.Offset
   242     def revert(range: Text.Range): Text.Range
   243     def cumulate_markup[A](range: Text.Range)(body: Markup_Tree.Cumulate[A]): Stream[Text.Info[A]]
   244     def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   245       : Stream[Text.Info[Option[A]]]
   246   }
   247 
   248   type Assign =
   249    (List[(Document.Command_ID, Option[Document.Exec_ID])],  // exec state assignment
   250     List[(String, Option[Document.Command_ID])])  // last exec
   251 
   252   val no_assign: Assign = (Nil, Nil)
   253 
   254   object State
   255   {
   256     class Fail(state: State) extends Exception
   257 
   258     val init: State =
   259       State().define_version(Version.init, Assignment.init).assign(Version.init.id, no_assign)._2
   260 
   261     object Assignment
   262     {
   263       val init: Assignment = Assignment(Map.empty, Map.empty, false)
   264     }
   265 
   266     case class Assignment(
   267       val command_execs: Map[Command_ID, Exec_ID],
   268       val last_execs: Map[String, Option[Command_ID]],
   269       val is_finished: Boolean)
   270     {
   271       def check_finished: Assignment = { require(is_finished); this }
   272       def unfinished: Assignment = copy(is_finished = false)
   273 
   274       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])],
   275         add_last_execs: List[(String, Option[Command_ID])]): Assignment =
   276       {
   277         require(!is_finished)
   278         val command_execs1 =
   279           (command_execs /: add_command_execs) {
   280             case (res, (command_id, None)) => res - command_id
   281             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   282           }
   283         Assignment(command_execs1, last_execs ++ add_last_execs, true)
   284       }
   285     }
   286   }
   287 
   288   sealed case class State(
   289     val versions: Map[Version_ID, Version] = Map(),
   290     val commands: Map[Command_ID, Command.State] = Map(),  // static markup from define_command
   291     val execs: Map[Exec_ID, Command.State] = Map(),  // dynamic markup from execution
   292     val assignments: Map[Version_ID, State.Assignment] = Map(),
   293     val history: History = History.init)
   294   {
   295     private def fail[A]: A = throw new State.Fail(this)
   296 
   297     def define_version(version: Version, assignment: State.Assignment): State =
   298     {
   299       val id = version.id
   300       copy(versions = versions + (id -> version),
   301         assignments = assignments + (id -> assignment.unfinished))
   302     }
   303 
   304     def define_command(command: Command): State =
   305     {
   306       val id = command.id
   307       copy(commands = commands + (id -> command.empty_state))
   308     }
   309 
   310     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   311 
   312     def find_command(version: Version, id: ID): Option[(Node, Command)] =
   313       commands.get(id) orElse execs.get(id) match {
   314         case None => None
   315         case Some(st) =>
   316           val command = st.command
   317           version.nodes.get(command.node_name).map((_, command))
   318       }
   319 
   320     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   321     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   322     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   323     def the_assignment(version: Version): State.Assignment =
   324       assignments.getOrElse(version.id, fail)
   325 
   326     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   327       execs.get(id) match {
   328         case Some(st) =>
   329           val new_st = st.accumulate(message)
   330           (new_st, copy(execs = execs + (id -> new_st)))
   331         case None =>
   332           commands.get(id) match {
   333             case Some(st) =>
   334               val new_st = st.accumulate(message)
   335               (new_st, copy(commands = commands + (id -> new_st)))
   336             case None => fail
   337           }
   338       }
   339 
   340     def assign(id: Version_ID, arg: Assign): (List[Command], State) =
   341     {
   342       val version = the_version(id)
   343       val (command_execs, last_execs) = arg
   344 
   345       val (changed_commands, new_execs) =
   346         ((Nil: List[Command], execs) /: command_execs) {
   347           case ((commands1, execs1), (cmd_id, exec)) =>
   348             val st = the_command(cmd_id)
   349             val commands2 = st.command :: commands1
   350             val execs2 =
   351               exec match {
   352                 case None => execs1
   353                 case Some(exec_id) => execs1 + (exec_id -> st)
   354               }
   355             (commands2, execs2)
   356         }
   357       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   358       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   359 
   360       (changed_commands, new_state)
   361     }
   362 
   363     def is_assigned(version: Version): Boolean =
   364       assignments.get(version.id) match {
   365         case Some(assgn) => assgn.is_finished
   366         case None => false
   367       }
   368 
   369     def is_stable(change: Change): Boolean =
   370       change.is_finished && is_assigned(change.version.get_finished)
   371 
   372     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   373     def tip_stable: Boolean = is_stable(history.tip)
   374     def tip_version: Version = history.tip.version.get_finished
   375 
   376     def last_exec_offset(name: Node.Name): Text.Offset =
   377     {
   378       val version = tip_version
   379       the_assignment(version).last_execs.get(name.node) match {
   380         case Some(Some(id)) =>
   381           val node = version.nodes(name)
   382           val cmd = the_command(id).command
   383           node.command_start(cmd) match {
   384             case None => 0
   385             case Some(start) => start + cmd.length
   386           }
   387         case _ => 0
   388       }
   389     }
   390 
   391     def continue_history(
   392         previous: Future[Version],
   393         edits: List[Edit_Text],
   394         version: Future[Version]): (Change, State) =
   395     {
   396       val change = Change(Some(previous), edits, version)
   397       (change, copy(history = history + change))
   398     }
   399 
   400     def prune_history(retain: Int = 0): (List[Version], State) =
   401     {
   402       val undo_list = history.undo_list
   403       val n = undo_list.iterator.zipWithIndex.find(p => is_stable(p._1)).get._2 + 1
   404       val (retained, dropped) = undo_list.splitAt(n max retain)
   405 
   406       retained.splitAt(retained.length - 1) match {
   407         case (prefix, List(last)) =>
   408           val dropped_versions = dropped.map(change => change.version.get_finished)
   409           val state1 = copy(history = History(prefix ::: List(last.truncate)))
   410           (dropped_versions, state1)
   411         case _ => fail
   412       }
   413     }
   414 
   415     def removed_versions(removed: List[Version_ID]): State =
   416     {
   417       val versions1 = versions -- removed
   418       val assignments1 = assignments -- removed
   419       var commands1 = Map.empty[Command_ID, Command.State]
   420       var execs1 = Map.empty[Exec_ID, Command.State]
   421       for {
   422         (version_id, version) <- versions1.iterator
   423         val command_execs = assignments1(version_id).command_execs
   424         (_, node) <- version.nodes.iterator
   425         command <- node.commands.iterator
   426       } {
   427         val id = command.id
   428         if (!commands1.isDefinedAt(id) && commands.isDefinedAt(id))
   429           commands1 += (id -> commands(id))
   430         if (command_execs.isDefinedAt(id)) {
   431           val exec_id = command_execs(id)
   432           if (!execs1.isDefinedAt(exec_id) && execs.isDefinedAt(exec_id))
   433             execs1 += (exec_id -> execs(exec_id))
   434         }
   435       }
   436       copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
   437     }
   438 
   439     def command_state(version: Version, command: Command): Command.State =
   440     {
   441       require(is_assigned(version))
   442       try {
   443         the_exec(the_assignment(version).check_finished.command_execs
   444           .getOrElse(command.id, fail))
   445       }
   446       catch { case _: State.Fail => command.empty_state }
   447     }
   448 
   449 
   450     // persistent user-view
   451     def snapshot(name: Node.Name, pending_edits: List[Text.Edit]): Snapshot =
   452     {
   453       val stable = recent_stable
   454       val latest = history.tip
   455 
   456       // FIXME proper treatment of removed nodes
   457       val edits =
   458         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   459             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   460       lazy val reverse_edits = edits.reverse
   461 
   462       new Snapshot
   463       {
   464         val state = State.this
   465         val version = stable.version.get_finished
   466         val node = version.nodes(name)
   467         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   468         def command_state(command: Command): Command.State = state.command_state(version, command)
   469 
   470         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   471         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   472         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   473         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   474 
   475         def cumulate_markup[A](range: Text.Range)(body: Markup_Tree.Cumulate[A])
   476           : Stream[Text.Info[A]] =
   477         {
   478           val info = body.info
   479           val result = body.result
   480 
   481           val former_range = revert(range)
   482           for {
   483             (command, command_start) <- node.command_range(former_range).toStream
   484             Text.Info(r0, a) <- command_state(command).markup.
   485               cumulate((former_range - command_start).restrict(command.range))(
   486                 Markup_Tree.Cumulate[A](info,
   487                   {
   488                     case (a, Text.Info(r0, b))
   489                     if result.isDefinedAt((a, Text.Info(convert(r0 + command_start), b))) =>
   490                       result((a, Text.Info(convert(r0 + command_start), b)))
   491                   }))
   492           } yield Text.Info(convert(r0 + command_start), a)
   493         }
   494 
   495         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   496           : Stream[Text.Info[Option[A]]] =
   497         {
   498           val former_range = revert(range)
   499           for {
   500             (command, command_start) <- node.command_range(former_range).toStream
   501             Text.Info(r0, x) <- command_state(command).markup.
   502               select((former_range - command_start).restrict(command.range)) {
   503                 case Text.Info(r0, info)
   504                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   505                   result(Text.Info(convert(r0 + command_start), info))
   506               }
   507           } yield Text.Info(convert(r0 + command_start), x)
   508         }
   509       }
   510     }
   511   }
   512 }
   513