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