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