src/Pure/PIDE/document.scala
author wenzelm
Fri Aug 12 22:10:49 2011 +0200 (2011-08-12)
changeset 44163 32e0c150c010
parent 44160 8848867501fb
child 44182 ecb51b457064
permissions -rw-r--r--
normalized theory dependencies wrt. file_store;
     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 = new Counter
    27 
    28 
    29 
    30   /** document structure **/
    31 
    32   /* named nodes -- development graph */
    33 
    34   type Edit[A] = (String, Node.Edit[A])
    35   type Edit_Text = Edit[Text.Edit]
    36   type Edit_Command = Edit[(Option[Command], Option[Command])]
    37   type Edit_Command_ID = Edit[(Option[Command_ID], Option[Command_ID])]
    38 
    39   object Node
    40   {
    41     sealed abstract class Edit[A]
    42     {
    43       def map[B](f: A => B): Edit[B] =
    44         this match {
    45           case Remove() => Remove()
    46           case Edits(es) => Edits(es.map(f))
    47           case Update_Header(header: Header) => Update_Header(header)
    48         }
    49     }
    50     case class Remove[A]() extends Edit[A]
    51     case class Edits[A](edits: List[A]) extends Edit[A]
    52     case class Update_Header[A](header: Header) extends Edit[A]
    53 
    54     sealed case class Header(val master_dir: String, val thy_header: Exn.Result[Thy_Header])
    55     {
    56       def norm_deps(f: (String, Path) => String): Header =
    57         copy(thy_header =
    58           thy_header match {
    59             case Exn.Res(header) =>
    60               Exn.capture { header.norm_deps(name => f(master_dir, Path.explode(name))) }
    61             case exn => exn
    62           })
    63     }
    64     val empty_header = Header("", Exn.Exn(ERROR("Bad theory header")))
    65 
    66     val empty: Node = Node(empty_header, Map(), Linear_Set())
    67 
    68     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    69       : Iterator[(Command, Text.Offset)] =
    70     {
    71       var i = offset
    72       for (command <- commands) yield {
    73         val start = i
    74         i += command.length
    75         (command, start)
    76       }
    77     }
    78   }
    79 
    80   private val block_size = 1024
    81 
    82   sealed case class Node(
    83     val header: Node.Header,
    84     val blobs: Map[String, Blob],
    85     val commands: Linear_Set[Command])
    86   {
    87     /* commands */
    88 
    89     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
    90     {
    91       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
    92       var next_block = 0
    93       var last_stop = 0
    94       for ((command, start) <- Node.command_starts(commands.iterator)) {
    95         last_stop = start + command.length
    96         while (last_stop + 1 > next_block) {
    97           blocks += (command -> start)
    98           next_block += block_size
    99         }
   100       }
   101       (blocks.toArray, Text.Range(0, last_stop))
   102     }
   103 
   104     def full_range: Text.Range = full_index._2
   105 
   106     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   107     {
   108       if (!commands.isEmpty && full_range.contains(i)) {
   109         val (cmd0, start0) = full_index._1(i / block_size)
   110         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   111           case (cmd, start) => start + cmd.length <= i }
   112       }
   113       else Iterator.empty
   114     }
   115 
   116     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   117       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   118 
   119     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   120     {
   121       val range = command_range(i)
   122       if (range.hasNext) Some(range.next) else None
   123     }
   124 
   125     def proper_command_at(i: Text.Offset): Option[Command] =
   126       command_at(i) match {
   127         case Some((command, _)) =>
   128           commands.reverse_iterator(command).find(cmd => !cmd.is_ignored)
   129         case None => None
   130       }
   131 
   132     def command_start(cmd: Command): Option[Text.Offset] =
   133       command_starts.find(_._1 == cmd).map(_._2)
   134 
   135     def command_starts: Iterator[(Command, Text.Offset)] =
   136       Node.command_starts(commands.iterator)
   137   }
   138 
   139 
   140 
   141   /** versioning **/
   142 
   143   /* particular document versions */
   144 
   145   object Version
   146   {
   147     val init: Version = Version(no_id, Map().withDefaultValue(Node.empty))
   148   }
   149 
   150   sealed case class Version(val id: Version_ID, val nodes: Map[String, Node])
   151 
   152 
   153   /* changes of plain text, eventually resulting in document edits */
   154 
   155   object Change
   156   {
   157     val init = Change(Future.value(Version.init), Nil, Future.value(Version.init))
   158   }
   159 
   160   sealed case class Change(
   161     val previous: Future[Version],
   162     val edits: List[Edit_Text],
   163     val version: Future[Version])
   164   {
   165     def is_finished: Boolean = previous.is_finished && version.is_finished
   166   }
   167 
   168 
   169   /* history navigation */
   170 
   171   object History
   172   {
   173     val init = new History(List(Change.init))
   174   }
   175 
   176   // FIXME pruning, purging of state
   177   class History(val undo_list: List[Change])
   178   {
   179     require(!undo_list.isEmpty)
   180 
   181     def tip: Change = undo_list.head
   182     def +(change: Change): History = new History(change :: undo_list)
   183   }
   184 
   185 
   186 
   187   /** global state -- document structure, execution process, editing history **/
   188 
   189   abstract class Snapshot
   190   {
   191     val version: Version
   192     val node: Node
   193     val is_outdated: Boolean
   194     def lookup_command(id: Command_ID): Option[Command]
   195     def state(command: Command): Command.State
   196     def convert(i: Text.Offset): Text.Offset
   197     def convert(range: Text.Range): Text.Range
   198     def revert(i: Text.Offset): Text.Offset
   199     def revert(range: Text.Range): Text.Range
   200     def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   201       : Stream[Text.Info[Option[A]]]
   202   }
   203 
   204   object State
   205   {
   206     class Fail(state: State) extends Exception
   207 
   208     val init = State().define_version(Version.init, Map()).assign(Version.init.id, Nil)._2
   209 
   210     case class Assignment(
   211       val assignment: Map[Command, Exec_ID],
   212       val is_finished: Boolean = false)
   213     {
   214       def get_finished: Map[Command, Exec_ID] = { require(is_finished); assignment }
   215       def assign(command_execs: List[(Command, Exec_ID)]): Assignment =
   216       {
   217         require(!is_finished)
   218         Assignment(assignment ++ command_execs, true)
   219       }
   220     }
   221   }
   222 
   223   sealed case class State(
   224     val versions: Map[Version_ID, Version] = Map(),
   225     val commands: Map[Command_ID, Command.State] = Map(),
   226     val execs: Map[Exec_ID, (Command.State, Set[Version])] = Map(),
   227     val assignments: Map[Version_ID, State.Assignment] = Map(),
   228     val disposed: Set[ID] = Set(),  // FIXME unused!?
   229     val history: History = History.init)
   230   {
   231     private def fail[A]: A = throw new State.Fail(this)
   232 
   233     def define_version(version: Version, former_assignment: Map[Command, Exec_ID]): State =
   234     {
   235       val id = version.id
   236       if (versions.isDefinedAt(id) || disposed(id)) fail
   237       copy(versions = versions + (id -> version),
   238         assignments = assignments + (id -> State.Assignment(former_assignment)))
   239     }
   240 
   241     def define_command(command: Command): State =
   242     {
   243       val id = command.id
   244       if (commands.isDefinedAt(id) || disposed(id)) fail
   245       copy(commands = commands + (id -> command.empty_state))
   246     }
   247 
   248     def lookup_command(id: Command_ID): Option[Command] = commands.get(id).map(_.command)
   249 
   250     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   251     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)
   252     def the_exec_state(id: Exec_ID): Command.State = execs.getOrElse(id, fail)._1
   253     def the_assignment(version: Version): State.Assignment =
   254       assignments.getOrElse(version.id, fail)
   255 
   256     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   257       execs.get(id) match {
   258         case Some((st, occs)) =>
   259           val new_st = st.accumulate(message)
   260           (new_st, copy(execs = execs + (id -> (new_st, occs))))
   261         case None =>
   262           commands.get(id) match {
   263             case Some(st) =>
   264               val new_st = st.accumulate(message)
   265               (new_st, copy(commands = commands + (id -> new_st)))
   266             case None => fail
   267           }
   268       }
   269 
   270     def assign(id: Version_ID, edits: List[(Command_ID, Exec_ID)]): (List[Command], State) =
   271     {
   272       val version = the_version(id)
   273       val occs = Set(version)  // FIXME unused (!?)
   274 
   275       var new_execs = execs
   276       val assigned_execs =
   277         for ((cmd_id, exec_id) <- edits) yield {
   278           val st = the_command(cmd_id)
   279           if (new_execs.isDefinedAt(exec_id) || disposed(exec_id)) fail
   280           new_execs += (exec_id -> (st, occs))
   281           (st.command, exec_id)
   282         }
   283       val new_assignment = the_assignment(version).assign(assigned_execs)
   284       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   285       (assigned_execs.map(_._1), new_state)
   286     }
   287 
   288     def is_assigned(version: Version): Boolean =
   289       assignments.get(version.id) match {
   290         case Some(assgn) => assgn.is_finished
   291         case None => false
   292       }
   293 
   294     def extend_history(previous: Future[Version],
   295         edits: List[Edit_Text],
   296         version: Future[Version]): (Change, State) =
   297     {
   298       val change = Change(previous, edits, version)
   299       (change, copy(history = history + change))
   300     }
   301 
   302 
   303     // persistent user-view
   304     def snapshot(name: String, pending_edits: List[Text.Edit]): Snapshot =
   305     {
   306       val found_stable = history.undo_list.find(change =>
   307         change.is_finished && is_assigned(change.version.get_finished))
   308       require(found_stable.isDefined)
   309       val stable = found_stable.get
   310       val latest = history.undo_list.head
   311 
   312       // FIXME proper treatment of removed nodes
   313       val edits =
   314         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   315             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   316       lazy val reverse_edits = edits.reverse
   317 
   318       new Snapshot
   319       {
   320         val version = stable.version.get_finished
   321         val node = version.nodes(name)
   322         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   323 
   324         def lookup_command(id: Command_ID): Option[Command] = State.this.lookup_command(id)
   325 
   326         def state(command: Command): Command.State =
   327           try { the_exec_state(the_assignment(version).get_finished.getOrElse(command, fail)) }
   328           catch { case _: State.Fail => command.empty_state }
   329 
   330         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   331         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   332         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   333         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   334 
   335         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   336           : Stream[Text.Info[Option[A]]] =
   337         {
   338           val former_range = revert(range)
   339           for {
   340             (command, command_start) <- node.command_range(former_range).toStream
   341             Text.Info(r0, x) <- state(command).markup.
   342               select((former_range - command_start).restrict(command.range)) {
   343                 case Text.Info(r0, info)
   344                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   345                   result(Text.Info(convert(r0 + command_start), info))
   346               }
   347           } yield Text.Info(convert(r0 + command_start), x)
   348         }
   349       }
   350     }
   351   }
   352 }
   353