src/Pure/PIDE/document.scala
author wenzelm
Fri Nov 22 21:13:44 2013 +0100 (2013-11-22)
changeset 54562 301a721af68b
parent 54549 2a3053472ec3
child 55431 e0f20a44ff9d
permissions -rw-r--r--
clarified node edits sent to prover -- Clear/Blob only required for text edits within editor;
     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   /** document structure **/
    17 
    18   /* overlays -- print functions with arguments */
    19 
    20   object Overlays
    21   {
    22     val empty = new Overlays(Map.empty)
    23   }
    24 
    25   final class Overlays private(rep: Map[Node.Name, Node.Overlays])
    26   {
    27     def apply(name: Document.Node.Name): Node.Overlays =
    28       rep.getOrElse(name, Node.Overlays.empty)
    29 
    30     private def update(name: Node.Name, f: Node.Overlays => Node.Overlays): Overlays =
    31     {
    32       val node_overlays = f(apply(name))
    33       new Overlays(if (node_overlays.is_empty) rep - name else rep + (name -> node_overlays))
    34     }
    35 
    36     def insert(command: Command, fn: String, args: List[String]): Overlays =
    37       update(command.node_name, _.insert(command, fn, args))
    38 
    39     def remove(command: Command, fn: String, args: List[String]): Overlays =
    40       update(command.node_name, _.remove(command, fn, args))
    41   }
    42 
    43 
    44   /* individual nodes */
    45 
    46   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    47   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    48   type Edit_Command = Edit[Command.Edit, Command.Perspective]
    49 
    50   type Blobs = Map[Node.Name, Bytes]
    51 
    52   object Node
    53   {
    54     val empty: Node = new Node()
    55 
    56 
    57     /* header and name */
    58 
    59     sealed case class Header(
    60       imports: List[Name],
    61       keywords: Thy_Header.Keywords,
    62       errors: List[String] = Nil)
    63     {
    64       def error(msg: String): Header = copy(errors = errors ::: List(msg))
    65 
    66       def cat_errors(msg2: String): Header =
    67         copy(errors = errors.map(msg1 => Library.cat_message(msg1, msg2)))
    68     }
    69 
    70     def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
    71 
    72     val no_header = bad_header("No theory header")
    73 
    74     object Name
    75     {
    76       val empty = Name("")
    77 
    78       object Ordering extends scala.math.Ordering[Name]
    79       {
    80         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
    81       }
    82     }
    83 
    84     sealed case class Name(node: String, master_dir: String = "", theory: String = "")
    85     {
    86       override def hashCode: Int = node.hashCode
    87       override def equals(that: Any): Boolean =
    88         that match {
    89           case other: Name => node == other.node
    90           case _ => false
    91         }
    92 
    93       def is_theory: Boolean = !theory.isEmpty
    94       override def toString: String = if (is_theory) theory else node
    95     }
    96 
    97 
    98     /* node overlays */
    99 
   100     object Overlays
   101     {
   102       val empty = new Overlays(Multi_Map.empty)
   103     }
   104 
   105     final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
   106     {
   107       def commands: Set[Command] = rep.keySet
   108       def is_empty: Boolean = rep.isEmpty
   109       def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
   110       def insert(cmd: Command, fn: String, args: List[String]): Overlays =
   111         new Overlays(rep.insert(cmd, (fn, args)))
   112       def remove(cmd: Command, fn: String, args: List[String]): Overlays =
   113         new Overlays(rep.remove(cmd, (fn, args)))
   114     }
   115 
   116 
   117     /* edits */
   118 
   119     sealed abstract class Edit[A, B]
   120     {
   121       def foreach(f: A => Unit)
   122       {
   123         this match {
   124           case Edits(es) => es.foreach(f)
   125           case _ =>
   126         }
   127       }
   128     }
   129     case class Clear[A, B]() extends Edit[A, B]
   130     case class Blob[A, B]() extends Edit[A, B]
   131 
   132     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
   133     case class Deps[A, B](header: Header) extends Edit[A, B]
   134     case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
   135     type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
   136     type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
   137 
   138 
   139     /* commands */
   140 
   141     object Commands
   142     {
   143       def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
   144       val empty: Commands = apply(Linear_Set.empty)
   145 
   146       def starts(commands: Iterator[Command], offset: Text.Offset = 0)
   147         : Iterator[(Command, Text.Offset)] =
   148       {
   149         var i = offset
   150         for (command <- commands) yield {
   151           val start = i
   152           i += command.length
   153           (command, start)
   154         }
   155       }
   156 
   157       private val block_size = 1024
   158     }
   159 
   160     final class Commands private(val commands: Linear_Set[Command])
   161     {
   162       lazy val thy_load_commands: List[Command] =
   163         commands.iterator.filter(cmd => !cmd.blobs.isEmpty).toList
   164 
   165       private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   166       {
   167         val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   168         var next_block = 0
   169         var last_stop = 0
   170         for ((command, start) <- Commands.starts(commands.iterator)) {
   171           last_stop = start + command.length
   172           while (last_stop + 1 > next_block) {
   173             blocks += (command -> start)
   174             next_block += Commands.block_size
   175           }
   176         }
   177         (blocks.toArray, Text.Range(0, last_stop))
   178       }
   179 
   180       private def full_range: Text.Range = full_index._2
   181 
   182       def range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   183       {
   184         if (!commands.isEmpty && full_range.contains(i)) {
   185           val (cmd0, start0) = full_index._1(i / Commands.block_size)
   186           Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
   187             case (cmd, start) => start + cmd.length <= i }
   188         }
   189         else Iterator.empty
   190       }
   191     }
   192   }
   193 
   194   final class Node private(
   195     val header: Node.Header = Node.bad_header("Bad theory header"),
   196     val perspective: Node.Perspective_Command =
   197       Node.Perspective(false, Command.Perspective.empty, Node.Overlays.empty),
   198     _commands: Node.Commands = Node.Commands.empty)
   199   {
   200     def clear: Node = new Node(header = header)
   201 
   202     def update_header(new_header: Node.Header): Node =
   203       new Node(new_header, perspective, _commands)
   204 
   205     def update_perspective(new_perspective: Node.Perspective_Command): Node =
   206       new Node(header, new_perspective, _commands)
   207 
   208     def same_perspective(other_perspective: Node.Perspective_Command): Boolean =
   209       perspective.required == other_perspective.required &&
   210       perspective.visible.same(other_perspective.visible) &&
   211       perspective.overlays == other_perspective.overlays
   212 
   213     def commands: Linear_Set[Command] = _commands.commands
   214     def thy_load_commands: List[Command] = _commands.thy_load_commands
   215 
   216     def update_commands(new_commands: Linear_Set[Command]): Node =
   217       if (new_commands eq _commands.commands) this
   218       else new Node(header, perspective, Node.Commands(new_commands))
   219 
   220     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   221       _commands.range(i)
   222 
   223     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   224       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   225 
   226     def command_start(cmd: Command): Option[Text.Offset] =
   227       Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
   228   }
   229 
   230 
   231   /* development graph */
   232 
   233   object Nodes
   234   {
   235     val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
   236   }
   237 
   238   final class Nodes private(graph: Graph[Node.Name, Node])
   239   {
   240     def get_name(s: String): Option[Node.Name] =
   241       graph.keys.find(name => name.node == s)
   242 
   243     def apply(name: Node.Name): Node =
   244       graph.default_node(name, Node.empty).get_node(name)
   245 
   246     def + (entry: (Node.Name, Node)): Nodes =
   247     {
   248       val (name, node) = entry
   249       val imports = node.header.imports
   250       val graph1 =
   251         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   252       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   253       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   254       new Nodes(graph3.map_node(name, _ => node))
   255     }
   256 
   257     def entries: Iterator[(Node.Name, Node)] =
   258       graph.entries.map({ case (name, (node, _)) => (name, node) })
   259 
   260     def thy_load_commands(file_name: Node.Name): List[Command] =
   261       (for {
   262         (_, node) <- entries
   263         cmd <- node.thy_load_commands.iterator
   264         name <- cmd.blobs_names.iterator
   265         if name == file_name
   266       } yield cmd).toList
   267 
   268     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   269     def topological_order: List[Node.Name] = graph.topological_order
   270   }
   271 
   272 
   273 
   274   /** versioning **/
   275 
   276   /* particular document versions */
   277 
   278   object Version
   279   {
   280     val init: Version = new Version()
   281 
   282     def make(syntax: Outer_Syntax, nodes: Nodes): Version =
   283       new Version(Document_ID.make(), syntax, nodes)
   284   }
   285 
   286   final class Version private(
   287     val id: Document_ID.Version = Document_ID.none,
   288     val syntax: Outer_Syntax = Outer_Syntax.empty,
   289     val nodes: Nodes = Nodes.empty)
   290   {
   291     def is_init: Boolean = id == Document_ID.none
   292   }
   293 
   294 
   295   /* changes of plain text, eventually resulting in document edits */
   296 
   297   object Change
   298   {
   299     val init: Change = new Change()
   300 
   301     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   302       new Change(Some(previous), edits, version)
   303   }
   304 
   305   final class Change private(
   306     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   307     val edits: List[Edit_Text] = Nil,
   308     val version: Future[Version] = Future.value(Version.init))
   309   {
   310     def is_finished: Boolean =
   311       (previous match { case None => true case Some(future) => future.is_finished }) &&
   312       version.is_finished
   313 
   314     def truncate: Change = new Change(None, Nil, version)
   315   }
   316 
   317 
   318   /* history navigation */
   319 
   320   object History
   321   {
   322     val init: History = new History()
   323   }
   324 
   325   final class History private(
   326     val undo_list: List[Change] = List(Change.init))  // non-empty list
   327   {
   328     def tip: Change = undo_list.head
   329     def + (change: Change): History = new History(change :: undo_list)
   330 
   331     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   332     {
   333       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   334       val (retained, dropped) = undo_list.splitAt(n max retain)
   335 
   336       retained.splitAt(retained.length - 1) match {
   337         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   338         case _ => None
   339       }
   340     }
   341   }
   342 
   343 
   344 
   345   /** global state -- document structure, execution process, editing history **/
   346 
   347   object Snapshot
   348   {
   349     val init = State.init.snapshot()
   350   }
   351 
   352   abstract class Snapshot
   353   {
   354     val state: State
   355     val version: Version
   356     val is_outdated: Boolean
   357     def convert(i: Text.Offset): Text.Offset
   358     def revert(i: Text.Offset): Text.Offset
   359     def convert(range: Text.Range): Text.Range
   360     def revert(range: Text.Range): Text.Range
   361 
   362     val node_name: Node.Name
   363     val node: Node
   364     def eq_content(other: Snapshot): Boolean
   365     def cumulate_markup[A](
   366       range: Text.Range,
   367       info: A,
   368       elements: Option[Set[String]],
   369       result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]]
   370     def select_markup[A](
   371       range: Text.Range,
   372       elements: Option[Set[String]],
   373       result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]]
   374   }
   375 
   376   type Assign_Update =
   377     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   378 
   379   object State
   380   {
   381     class Fail(state: State) extends Exception
   382 
   383     object Assignment
   384     {
   385       val init: Assignment = new Assignment()
   386     }
   387 
   388     final class Assignment private(
   389       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   390       val is_finished: Boolean = false)
   391     {
   392       def check_finished: Assignment = { require(is_finished); this }
   393       def unfinished: Assignment = new Assignment(command_execs, false)
   394 
   395       def assign(update: Assign_Update): Assignment =
   396       {
   397         require(!is_finished)
   398         val command_execs1 =
   399           (command_execs /: update) {
   400             case (res, (command_id, exec_ids)) =>
   401               if (exec_ids.isEmpty) res - command_id
   402               else res + (command_id -> exec_ids)
   403           }
   404         new Assignment(command_execs1, true)
   405       }
   406     }
   407 
   408     val init: State =
   409       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   410   }
   411 
   412   final case class State private(
   413     val versions: Map[Document_ID.Version, Version] = Map.empty,
   414     val blobs: Set[SHA1.Digest] = Set.empty,   // inlined files
   415     val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
   416     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
   417     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   418     val history: History = History.init)
   419   {
   420     private def fail[A]: A = throw new State.Fail(this)
   421 
   422     def define_version(version: Version, assignment: State.Assignment): State =
   423     {
   424       val id = version.id
   425       copy(versions = versions + (id -> version),
   426         assignments = assignments + (id -> assignment.unfinished))
   427     }
   428 
   429     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   430     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   431 
   432     def define_command(command: Command): State =
   433     {
   434       val id = command.id
   435       copy(commands = commands + (id -> command.init_state))
   436     }
   437 
   438     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   439 
   440     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   441       commands.get(id) orElse execs.get(id) match {
   442         case None => None
   443         case Some(st) =>
   444           val command = st.command
   445           val node = version.nodes(command.node_name)
   446           if (node.commands.contains(command)) Some((node, command)) else None
   447       }
   448 
   449     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   450     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   451     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   452     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   453 
   454     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   455       execs.get(id) match {
   456         case Some(st) =>
   457           val new_st = st + (id, message)
   458           (new_st, copy(execs = execs + (id -> new_st)))
   459         case None =>
   460           commands.get(id) match {
   461             case Some(st) =>
   462               val new_st = st + (id, message)
   463               (new_st, copy(commands = commands + (id -> new_st)))
   464             case None => fail
   465           }
   466       }
   467 
   468     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   469     {
   470       val version = the_version(id)
   471 
   472       def upd(exec_id: Document_ID.Exec, st: Command.State)
   473           : Option[(Document_ID.Exec, Command.State)] =
   474         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   475 
   476       val (changed_commands, new_execs) =
   477         ((Nil: List[Command], execs) /: update) {
   478           case ((commands1, execs1), (command_id, exec)) =>
   479             val st = the_static_state(command_id)
   480             val command = st.command
   481             val commands2 = command :: commands1
   482             val execs2 =
   483               exec match {
   484                 case Nil => execs1
   485                 case eval_id :: print_ids =>
   486                   execs1 ++ upd(eval_id, st) ++
   487                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   488               }
   489             (commands2, execs2)
   490         }
   491       val new_assignment = the_assignment(version).assign(update)
   492       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   493 
   494       (changed_commands, new_state)
   495     }
   496 
   497     def is_assigned(version: Version): Boolean =
   498       assignments.get(version.id) match {
   499         case Some(assgn) => assgn.is_finished
   500         case None => false
   501       }
   502 
   503     def is_stable(change: Change): Boolean =
   504       change.is_finished && is_assigned(change.version.get_finished)
   505 
   506     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   507     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   508     def tip_stable: Boolean = is_stable(history.tip)
   509     def tip_version: Version = history.tip.version.get_finished
   510 
   511     def continue_history(
   512         previous: Future[Version],
   513         edits: List[Edit_Text],
   514         version: Future[Version]): (Change, State) =
   515     {
   516       val change = Change.make(previous, edits, version)
   517       (change, copy(history = history + change))
   518     }
   519 
   520     def prune_history(retain: Int = 0): (List[Version], State) =
   521     {
   522       history.prune(is_stable, retain) match {
   523         case Some((dropped, history1)) =>
   524           val dropped_versions = dropped.map(change => change.version.get_finished)
   525           val state1 = copy(history = history1)
   526           (dropped_versions, state1)
   527         case None => fail
   528       }
   529     }
   530 
   531     def removed_versions(removed: List[Document_ID.Version]): State =
   532     {
   533       val versions1 = versions -- removed
   534       val assignments1 = assignments -- removed
   535       var blobs1 = Set.empty[SHA1.Digest]
   536       var commands1 = Map.empty[Document_ID.Command, Command.State]
   537       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   538       for {
   539         (version_id, version) <- versions1.iterator
   540         command_execs = assignments1(version_id).command_execs
   541         (_, node) <- version.nodes.entries
   542         command <- node.commands.iterator
   543       } {
   544         for (digest <- command.blobs_digests; if !blobs1.contains(digest))
   545           blobs1 += digest
   546 
   547         if (!commands1.isDefinedAt(command.id))
   548           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   549 
   550         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   551           if (!execs1.isDefinedAt(exec_id))
   552             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   553         }
   554       }
   555       copy(versions = versions1, blobs = blobs1, commands = commands1, execs = execs1,
   556         assignments = assignments1)
   557     }
   558 
   559     def command_state(version: Version, command: Command): Command.State =
   560     {
   561       require(is_assigned(version))
   562       try {
   563         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   564           .map(the_dynamic_state(_)) match {
   565             case eval_state :: print_states => (eval_state /: print_states)(_ ++ _)
   566             case Nil => fail
   567           }
   568       }
   569       catch {
   570         case _: State.Fail =>
   571           try { the_static_state(command.id) }
   572           catch { case _: State.Fail => command.init_state }
   573       }
   574     }
   575 
   576     def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
   577       node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
   578 
   579     // persistent user-view
   580     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   581       : Snapshot =
   582     {
   583       val stable = recent_stable
   584       val latest = history.tip
   585 
   586       // FIXME proper treatment of removed nodes
   587       val edits =
   588         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   589             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   590       lazy val reverse_edits = edits.reverse
   591 
   592       new Snapshot
   593       {
   594         /* global information */
   595 
   596         val state = State.this
   597         val version = stable.version.get_finished
   598         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   599 
   600         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   601         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   602         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   603         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   604 
   605 
   606         /* local node content */
   607 
   608         val node_name = name
   609         val node = version.nodes(name)
   610 
   611         def eq_content(other: Snapshot): Boolean =
   612           !is_outdated && !other.is_outdated &&
   613             node.commands.size == other.node.commands.size &&
   614             ((node.commands.iterator zip other.node.commands.iterator) forall {
   615               case (cmd1, cmd2) =>
   616                 state.command_state(version, cmd1) eq_content
   617                   other.state.command_state(other.version, cmd2)
   618             })
   619 
   620         def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
   621           result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]] =
   622         {
   623           val former_range = revert(range)
   624           (for {
   625             (command, command_start) <- node.command_range(former_range)
   626             st = state.command_state(version, command)
   627             res = result(st)
   628             Text.Info(r0, a) <- st.markup.cumulate[A](
   629               (former_range - command_start).restrict(command.range), info, elements,
   630               { case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b)) }
   631             ).iterator
   632           } yield Text.Info(convert(r0 + command_start), a)).toList
   633         }
   634 
   635         def select_markup[A](range: Text.Range, elements: Option[Set[String]],
   636           result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]] =
   637         {
   638           def result1(st: Command.State): (Option[A], Text.Markup) => Option[Option[A]] =
   639           {
   640             val res = result(st)
   641             (_: Option[A], x: Text.Markup) =>
   642               res(x) match {
   643                 case None => None
   644                 case some => Some(some)
   645               }
   646           }
   647           for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
   648             yield Text.Info(r, x)
   649         }
   650       }
   651     }
   652   }
   653 }
   654