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