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