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