src/Pure/PIDE/document.scala
author wenzelm
Mon Feb 27 17:13:25 2012 +0100 (2012-02-27 ago)
changeset 46712 8650d9a95736
parent 46684 7f741b2c82a3
child 46723 54ea872b60ea
permissions -rw-r--r--
prefer final ADTs -- prevent ooddities;
     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   final 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   final 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   final 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   final 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   object State
   277   {
   278     class Fail(state: State) extends Exception
   279 
   280     object Assignment
   281     {
   282       val init: Assignment = new Assignment()
   283     }
   284 
   285     final class Assignment private(
   286       val command_execs: Map[Command_ID, Exec_ID] = Map.empty,
   287       val last_execs: Map[String, Option[Command_ID]] = Map.empty,
   288       val is_finished: Boolean = false)
   289     {
   290       def check_finished: Assignment = { require(is_finished); this }
   291       def unfinished: Assignment = new Assignment(command_execs, last_execs, false)
   292 
   293       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])],
   294         add_last_execs: List[(String, Option[Command_ID])]): Assignment =
   295       {
   296         require(!is_finished)
   297         val command_execs1 =
   298           (command_execs /: add_command_execs) {
   299             case (res, (command_id, None)) => res - command_id
   300             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   301           }
   302         new Assignment(command_execs1, last_execs ++ add_last_execs, true)
   303       }
   304     }
   305 
   306     val init: State =
   307       State().define_version(Version.init, Assignment.init).assign(Version.init.id)._2
   308   }
   309 
   310   final case class State private(
   311     val versions: Map[Version_ID, Version] = Map.empty,
   312     val commands: Map[Command_ID, Command.State] = Map.empty,  // static markup from define_command
   313     val execs: Map[Exec_ID, Command.State] = Map.empty,  // dynamic markup from execution
   314     val assignments: Map[Version_ID, State.Assignment] = Map.empty,
   315     val history: History = History.init)
   316   {
   317     private def fail[A]: A = throw new State.Fail(this)
   318 
   319     def define_version(version: Version, assignment: State.Assignment): State =
   320     {
   321       val id = version.id
   322       copy(versions = versions + (id -> version),
   323         assignments = assignments + (id -> assignment.unfinished))
   324     }
   325 
   326     def define_command(command: Command): State =
   327     {
   328       val id = command.id
   329       copy(commands = commands + (id -> command.empty_state))
   330     }
   331 
   332     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   333 
   334     def find_command(version: Version, id: ID): Option[(Node, Command)] =
   335       commands.get(id) orElse execs.get(id) match {
   336         case None => None
   337         case Some(st) =>
   338           val command = st.command
   339           val node = version.nodes(command.node_name)
   340           Some((node, command))
   341       }
   342 
   343     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   344     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   345     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   346     def the_assignment(version: Version): State.Assignment =
   347       assignments.getOrElse(version.id, fail)
   348 
   349     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   350       execs.get(id) match {
   351         case Some(st) =>
   352           val new_st = st + message
   353           (new_st, copy(execs = execs + (id -> new_st)))
   354         case None =>
   355           commands.get(id) match {
   356             case Some(st) =>
   357               val new_st = st + message
   358               (new_st, copy(commands = commands + (id -> new_st)))
   359             case None => fail
   360           }
   361       }
   362 
   363     def assign(id: Version_ID, arg: Assign = (Nil, Nil)): (List[Command], State) =
   364     {
   365       val version = the_version(id)
   366       val (command_execs, last_execs) = arg
   367 
   368       val (changed_commands, new_execs) =
   369         ((Nil: List[Command], execs) /: command_execs) {
   370           case ((commands1, execs1), (cmd_id, exec)) =>
   371             val st = the_command(cmd_id)
   372             val commands2 = st.command :: commands1
   373             val execs2 =
   374               exec match {
   375                 case None => execs1
   376                 case Some(exec_id) => execs1 + (exec_id -> st)
   377               }
   378             (commands2, execs2)
   379         }
   380       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   381       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   382 
   383       (changed_commands, new_state)
   384     }
   385 
   386     def is_assigned(version: Version): Boolean =
   387       assignments.get(version.id) match {
   388         case Some(assgn) => assgn.is_finished
   389         case None => false
   390       }
   391 
   392     def is_stable(change: Change): Boolean =
   393       change.is_finished && is_assigned(change.version.get_finished)
   394 
   395     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   396     def tip_stable: Boolean = is_stable(history.tip)
   397     def tip_version: Version = history.tip.version.get_finished
   398 
   399     def last_exec_offset(name: Node.Name): Text.Offset =
   400     {
   401       val version = tip_version
   402       the_assignment(version).last_execs.get(name.node) match {
   403         case Some(Some(id)) =>
   404           val node = version.nodes(name)
   405           val cmd = the_command(id).command
   406           node.command_start(cmd) match {
   407             case None => 0
   408             case Some(start) => start + cmd.length
   409           }
   410         case _ => 0
   411       }
   412     }
   413 
   414     def continue_history(
   415         previous: Future[Version],
   416         edits: List[Edit_Text],
   417         version: Future[Version]): (Change, State) =
   418     {
   419       val change = Change.make(previous, edits, version)
   420       (change, copy(history = history + change))
   421     }
   422 
   423     def prune_history(retain: Int = 0): (List[Version], State) =
   424     {
   425       history.prune(is_stable, retain) match {
   426         case Some((dropped, history1)) =>
   427           val dropped_versions = dropped.map(change => change.version.get_finished)
   428           val state1 = copy(history = history1)
   429           (dropped_versions, state1)
   430         case None => fail
   431       }
   432     }
   433 
   434     def removed_versions(removed: List[Version_ID]): State =
   435     {
   436       val versions1 = versions -- removed
   437       val assignments1 = assignments -- removed
   438       var commands1 = Map.empty[Command_ID, Command.State]
   439       var execs1 = Map.empty[Exec_ID, Command.State]
   440       for {
   441         (version_id, version) <- versions1.iterator
   442         val command_execs = assignments1(version_id).command_execs
   443         (_, node) <- version.nodes.iterator
   444         command <- node.commands.iterator
   445       } {
   446         val id = command.id
   447         if (!commands1.isDefinedAt(id) && commands.isDefinedAt(id))
   448           commands1 += (id -> commands(id))
   449         if (command_execs.isDefinedAt(id)) {
   450           val exec_id = command_execs(id)
   451           if (!execs1.isDefinedAt(exec_id) && execs.isDefinedAt(exec_id))
   452             execs1 += (exec_id -> execs(exec_id))
   453         }
   454       }
   455       copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
   456     }
   457 
   458     def command_state(version: Version, command: Command): Command.State =
   459     {
   460       require(is_assigned(version))
   461       try {
   462         the_exec(the_assignment(version).check_finished.command_execs
   463           .getOrElse(command.id, fail))
   464       }
   465       catch { case _: State.Fail => command.empty_state }
   466     }
   467 
   468 
   469     // persistent user-view
   470     def snapshot(name: Node.Name, pending_edits: List[Text.Edit]): Snapshot =
   471     {
   472       val stable = recent_stable
   473       val latest = history.tip
   474 
   475       // FIXME proper treatment of removed nodes
   476       val edits =
   477         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   478             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   479       lazy val reverse_edits = edits.reverse
   480 
   481       new Snapshot
   482       {
   483         val state = State.this
   484         val version = stable.version.get_finished
   485         val node = version.nodes(name)
   486         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   487 
   488         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   489         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   490         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   491         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   492 
   493         def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   494           result: PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]] =
   495         {
   496           val former_range = revert(range)
   497           for {
   498             (command, command_start) <- node.command_range(former_range).toStream
   499             Text.Info(r0, a) <- state.command_state(version, command).markup.
   500               cumulate[A]((former_range - command_start).restrict(command.range), info, elements,
   501                 {
   502                   case (a, Text.Info(r0, b))
   503                   if result.isDefinedAt((a, Text.Info(convert(r0 + command_start), b))) =>
   504                     result((a, Text.Info(convert(r0 + command_start), b)))
   505                 })
   506           } yield Text.Info(convert(r0 + command_start), a)
   507         }
   508 
   509         def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   510           result: PartialFunction[Text.Markup, A]): Stream[Text.Info[A]] =
   511         {
   512           val result1 =
   513             new PartialFunction[(Option[A], Text.Markup), Option[A]] {
   514               def isDefinedAt(arg: (Option[A], Text.Markup)): Boolean = result.isDefinedAt(arg._2)
   515               def apply(arg: (Option[A], Text.Markup)): Option[A] = Some(result(arg._2))
   516             }
   517           for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
   518             yield Text.Info(r, x)
   519         }
   520       }
   521     }
   522   }
   523 }
   524