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