src/Pure/PIDE/command.scala
author wenzelm
Mon Mar 16 11:07:56 2015 +0100 (2015-03-16 ago)
changeset 59713 6da3efec20ca
parent 59710 aed304412e43
child 59715 4f0d0e4ad68d
permissions -rw-r--r--
clarified modules;
     1 /*  Title:      Pure/PIDE/command.scala
     2     Author:     Fabian Immler, TU Munich
     3     Author:     Makarius
     4 
     5 Prover commands with accumulated results from execution.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 import scala.collection.immutable.SortedMap
    13 import scala.util.parsing.input.CharSequenceReader
    14 
    15 
    16 object Command
    17 {
    18   type Edit = (Option[Command], Option[Command])
    19 
    20   type Blob = Exn.Result[(Document.Node.Name, Option[(SHA1.Digest, Symbol.Text_Chunk)])]
    21   type Blobs_Info = (List[Blob], Int)
    22   val no_blobs: Blobs_Info = (Nil, -1)
    23 
    24 
    25   /** accumulated results from prover **/
    26 
    27   /* results */
    28 
    29   object Results
    30   {
    31     type Entry = (Long, XML.Tree)
    32     val empty = new Results(SortedMap.empty)
    33     def make(args: TraversableOnce[Results.Entry]): Results = (empty /: args)(_ + _)
    34     def merge(args: TraversableOnce[Results]): Results = (empty /: args)(_ ++ _)
    35   }
    36 
    37   final class Results private(private val rep: SortedMap[Long, XML.Tree])
    38   {
    39     def defined(serial: Long): Boolean = rep.isDefinedAt(serial)
    40     def get(serial: Long): Option[XML.Tree] = rep.get(serial)
    41     def iterator: Iterator[Results.Entry] = rep.iterator
    42 
    43     def + (entry: Results.Entry): Results =
    44       if (defined(entry._1)) this
    45       else new Results(rep + entry)
    46 
    47     def ++ (other: Results): Results =
    48       if (this eq other) this
    49       else if (rep.isEmpty) other
    50       else (this /: other.iterator)(_ + _)
    51 
    52     override def hashCode: Int = rep.hashCode
    53     override def equals(that: Any): Boolean =
    54       that match {
    55         case other: Results => rep == other.rep
    56         case _ => false
    57       }
    58     override def toString: String = iterator.mkString("Results(", ", ", ")")
    59   }
    60 
    61 
    62   /* markup */
    63 
    64   object Markup_Index
    65   {
    66     val markup: Markup_Index = Markup_Index(false, Symbol.Text_Chunk.Default)
    67   }
    68 
    69   sealed case class Markup_Index(status: Boolean, chunk_name: Symbol.Text_Chunk.Name)
    70 
    71   object Markups
    72   {
    73     val empty: Markups = new Markups(Map.empty)
    74 
    75     def init(markup: Markup_Tree): Markups =
    76       new Markups(Map(Markup_Index.markup -> markup))
    77   }
    78 
    79   final class Markups private(private val rep: Map[Markup_Index, Markup_Tree])
    80   {
    81     def is_empty: Boolean = rep.isEmpty
    82 
    83     def apply(index: Markup_Index): Markup_Tree =
    84       rep.getOrElse(index, Markup_Tree.empty)
    85 
    86     def add(index: Markup_Index, markup: Text.Markup): Markups =
    87       new Markups(rep + (index -> (this(index) + markup)))
    88 
    89     def redirection_iterator: Iterator[Document_ID.Generic] =
    90       for (Markup_Index(_, Symbol.Text_Chunk.Id(id)) <- rep.keysIterator)
    91         yield id
    92 
    93     def redirect(other_id: Document_ID.Generic): Markups =
    94     {
    95       val rep1 =
    96         (for {
    97           (Markup_Index(status, Symbol.Text_Chunk.Id(id)), markup) <- rep.iterator
    98           if other_id == id
    99         } yield (Markup_Index(status, Symbol.Text_Chunk.Default), markup)).toMap
   100       if (rep1.isEmpty) Markups.empty else new Markups(rep1)
   101     }
   102 
   103     override def hashCode: Int = rep.hashCode
   104     override def equals(that: Any): Boolean =
   105       that match {
   106         case other: Markups => rep == other.rep
   107         case _ => false
   108       }
   109     override def toString: String = rep.iterator.mkString("Markups(", ", ", ")")
   110   }
   111 
   112 
   113   /* state */
   114 
   115   object State
   116   {
   117     def merge_results(states: List[State]): Command.Results =
   118       Results.merge(states.map(_.results))
   119 
   120     def merge_markup(states: List[State], index: Markup_Index,
   121         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   122       Markup_Tree.merge(states.map(_.markup(index)), range, elements)
   123   }
   124 
   125   sealed case class State(
   126     command: Command,
   127     status: List[Markup] = Nil,
   128     results: Results = Results.empty,
   129     markups: Markups = Markups.empty)
   130   {
   131     lazy val protocol_status: Protocol.Status =
   132     {
   133       val warnings =
   134         if (results.iterator.exists(p => Protocol.is_warning(p._2) || Protocol.is_legacy(p._2)))
   135           List(Markup(Markup.WARNING, Nil))
   136         else Nil
   137       val errors =
   138         if (results.iterator.exists(p => Protocol.is_error(p._2)))
   139           List(Markup(Markup.ERROR, Nil))
   140         else Nil
   141       Protocol.Status.make((warnings ::: errors ::: status).iterator)
   142     }
   143 
   144     def markup(index: Markup_Index): Markup_Tree = markups(index)
   145 
   146     def redirect(other_command: Command): Option[State] =
   147     {
   148       val markups1 = markups.redirect(other_command.id)
   149       if (markups1.is_empty) None
   150       else Some(new State(other_command, Nil, Results.empty, markups1))
   151     }
   152 
   153     def eq_content(other: State): Boolean =
   154       command.source == other.command.source &&
   155       status == other.status &&
   156       results == other.results &&
   157       markups == other.markups
   158 
   159     private def add_status(st: Markup): State =
   160       copy(status = st :: status)
   161 
   162     private def add_markup(
   163       status: Boolean, chunk_name: Symbol.Text_Chunk.Name, m: Text.Markup): State =
   164     {
   165       val markups1 =
   166         if (status || Protocol.liberal_status_elements(m.info.name))
   167           markups.add(Markup_Index(true, chunk_name), m)
   168         else markups
   169       copy(markups = markups1.add(Markup_Index(false, chunk_name), m))
   170     }
   171 
   172     def accumulate(
   173         self_id: Document_ID.Generic => Boolean,
   174         other_id: Document_ID.Generic => Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)],
   175         message: XML.Elem): State =
   176       message match {
   177         case XML.Elem(Markup(Markup.STATUS, _), msgs) =>
   178           (this /: msgs)((state, msg) =>
   179             msg match {
   180               case elem @ XML.Elem(markup, Nil) =>
   181                 state.
   182                   add_status(markup).
   183                   add_markup(true, Symbol.Text_Chunk.Default, Text.Info(command.proper_range, elem))
   184               case _ =>
   185                 Output.warning("Ignored status message: " + msg)
   186                 state
   187             })
   188 
   189         case XML.Elem(Markup(Markup.REPORT, _), msgs) =>
   190           (this /: msgs)((state, msg) =>
   191             {
   192               def bad(): Unit = Output.warning("Ignored report message: " + msg)
   193 
   194               msg match {
   195                 case XML.Elem(Markup(name, atts @ Position.Identified(id, chunk_name)), args) =>
   196 
   197                   val target =
   198                     if (self_id(id) && command.chunks.isDefinedAt(chunk_name))
   199                       Some((chunk_name, command.chunks(chunk_name)))
   200                     else if (chunk_name == Symbol.Text_Chunk.Default) other_id(id)
   201                     else None
   202 
   203                   (target, atts) match {
   204                     case (Some((target_name, target_chunk)), Position.Range(symbol_range)) =>
   205                       target_chunk.incorporate(symbol_range) match {
   206                         case Some(range) =>
   207                           val props = Position.purge(atts)
   208                           val info = Text.Info(range, XML.Elem(Markup(name, props), args))
   209                           state.add_markup(false, target_name, info)
   210                         case None => bad(); state
   211                       }
   212                     case _ =>
   213                       // silently ignore excessive reports
   214                       state
   215                   }
   216 
   217                 case XML.Elem(Markup(name, atts), args)
   218                 if !atts.exists({ case (a, _) => Markup.POSITION_PROPERTIES(a) }) =>
   219                   val range = command.proper_range
   220                   val props = Position.purge(atts)
   221                   val info: Text.Markup = Text.Info(range, XML.Elem(Markup(name, props), args))
   222                   state.add_markup(false, Symbol.Text_Chunk.Default, info)
   223 
   224                 case _ => bad(); state
   225               }
   226             })
   227         case XML.Elem(Markup(name, props), body) =>
   228           props match {
   229             case Markup.Serial(i) =>
   230               val message1 = XML.Elem(Markup(Markup.message(name), props), body)
   231               val message2 = XML.Elem(Markup(name, props), body)
   232 
   233               var st = copy(results = results + (i -> message1))
   234               if (Protocol.is_inlined(message)) {
   235                 for {
   236                   (chunk_name, chunk) <- command.chunks.iterator
   237                   range <- Protocol_Message.positions(
   238                     self_id, command.position, chunk_name, chunk, message)
   239                 } st = st.add_markup(false, chunk_name, Text.Info(range, message2))
   240               }
   241               st
   242 
   243             case _ =>
   244               Output.warning("Ignored message without serial number: " + message)
   245               this
   246           }
   247     }
   248   }
   249 
   250 
   251 
   252   /** static content **/
   253 
   254   /* make commands */
   255 
   256   def apply(
   257     id: Document_ID.Command,
   258     node_name: Document.Node.Name,
   259     blobs_info: Blobs_Info,
   260     span: Command_Span.Span): Command =
   261   {
   262     val (source, span1) = span.compact_source
   263     new Command(id, node_name, blobs_info, span1, source, Results.empty, Markup_Tree.empty)
   264   }
   265 
   266   val empty: Command =
   267     Command(Document_ID.none, Document.Node.Name.empty, no_blobs, Command_Span.empty)
   268 
   269   def unparsed(
   270     id: Document_ID.Command,
   271     source: String,
   272     results: Results,
   273     markup: Markup_Tree): Command =
   274   {
   275     val (source1, span1) = Command_Span.unparsed(source).compact_source
   276     new Command(id, Document.Node.Name.empty, no_blobs, span1, source1, results, markup)
   277   }
   278 
   279   def unparsed(source: String): Command =
   280     unparsed(Document_ID.none, source, Results.empty, Markup_Tree.empty)
   281 
   282   def rich_text(id: Document_ID.Command, results: Results, body: XML.Body): Command =
   283   {
   284     val text = XML.content(body)
   285     val markup = Markup_Tree.from_XML(body)
   286     unparsed(id, text, results, markup)
   287   }
   288 
   289 
   290   /* perspective */
   291 
   292   object Perspective
   293   {
   294     val empty: Perspective = Perspective(Nil)
   295   }
   296 
   297   sealed case class Perspective(commands: List[Command])  // visible commands in canonical order
   298   {
   299     def is_empty: Boolean = commands.isEmpty
   300 
   301     def same(that: Perspective): Boolean =
   302     {
   303       val cmds1 = this.commands
   304       val cmds2 = that.commands
   305       require(!cmds1.exists(_.is_undefined))
   306       require(!cmds2.exists(_.is_undefined))
   307       cmds1.length == cmds2.length &&
   308         (cmds1.iterator zip cmds2.iterator).forall({ case (c1, c2) => c1.id == c2.id })
   309     }
   310   }
   311 
   312 
   313   /* blobs: inlined errors and auxiliary files */
   314 
   315   private def clean_tokens(tokens: List[Token]): List[(Token, Int)] =
   316   {
   317     def clean(toks: List[(Token, Int)]): List[(Token, Int)] =
   318       toks match {
   319         case (t1, i1) :: (t2, i2) :: rest =>
   320           if (t1.is_keyword && (t1.source == "%" || t1.source == "--")) clean(rest)
   321           else (t1, i1) :: clean((t2, i2) :: rest)
   322         case _ => toks
   323       }
   324     clean(tokens.zipWithIndex.filter({ case (t, _) => t.is_proper }))
   325   }
   326 
   327   private def find_file(tokens: List[(Token, Int)]): Option[(String, Int)] =
   328     tokens match {
   329       case (tok, _) :: toks =>
   330         if (tok.is_command)
   331           toks.collectFirst({ case (t, i) if t.is_name => (t.content, i) })
   332         else None
   333       case Nil => None
   334     }
   335 
   336   def span_files(syntax: Prover.Syntax, span: Command_Span.Span): (List[String], Int) =
   337     span.kind match {
   338       case Command_Span.Command_Span(name, _) =>
   339         syntax.load_command(name) match {
   340           case Some(exts) =>
   341             find_file(clean_tokens(span.content)) match {
   342               case Some((file, i)) =>
   343                 if (exts.isEmpty) (List(file), i)
   344                 else (exts.map(ext => file + "." + ext), i)
   345               case None => (Nil, -1)
   346             }
   347           case None => (Nil, -1)
   348         }
   349       case _ => (Nil, -1)
   350     }
   351 
   352   def blobs_info(
   353     resources: Resources,
   354     syntax: Prover.Syntax,
   355     get_blob: Document.Node.Name => Option[Document.Blob],
   356     can_import: Document.Node.Name => Boolean,
   357     node_name: Document.Node.Name,
   358     span: Command_Span.Span): Blobs_Info =
   359   {
   360     span.kind match {
   361       // inlined errors
   362       case Command_Span.Command_Span(name, _) if syntax.is_theory_begin(name) =>
   363         val header =
   364           resources.check_thy_reader("", node_name,
   365             new CharSequenceReader(span.source), Token.Pos.id(Markup.COMMAND))
   366         val import_errors =
   367           for ((imp, pos) <- header.imports if !can_import(imp)) yield {
   368             val name = imp.node
   369             "Bad theory import " + Markup.Path(name).markup(quote(name)) + Position.here(pos)
   370           }
   371         ((header.errors ::: import_errors).map(msg => Exn.Exn(ERROR(msg)): Command.Blob), -1)
   372 
   373       // auxiliary files
   374       case _ =>
   375         val (files, index) = span_files(syntax, span)
   376         val blobs =
   377           files.map(file =>
   378             (Exn.capture {
   379               val name =
   380                 Document.Node.Name(resources.append(node_name.master_dir, Path.explode(file)))
   381               val blob = get_blob(name).map(blob => ((blob.bytes.sha1_digest, blob.chunk)))
   382               (name, blob)
   383             }).user_error)
   384         (blobs, index)
   385     }
   386   }
   387 }
   388 
   389 
   390 final class Command private(
   391     val id: Document_ID.Command,
   392     val node_name: Document.Node.Name,
   393     val blobs_info: Command.Blobs_Info,
   394     val span: Command_Span.Span,
   395     val source: String,
   396     val init_results: Command.Results,
   397     val init_markup: Markup_Tree)
   398 {
   399   /* name */
   400 
   401   def name: String =
   402     span.kind match { case Command_Span.Command_Span(name, _) => name case _ => "" }
   403 
   404   def position: Position.T =
   405     span.kind match { case Command_Span.Command_Span(_, pos) => pos case _ => Position.none }
   406 
   407   override def toString: String = id + "/" + span.kind.toString
   408 
   409 
   410   /* classification */
   411 
   412   def is_proper: Boolean = span.kind.isInstanceOf[Command_Span.Command_Span]
   413   def is_ignored: Boolean = span.kind == Command_Span.Ignored_Span
   414 
   415   def is_undefined: Boolean = id == Document_ID.none
   416   val is_unparsed: Boolean = span.content.exists(_.is_unparsed)
   417   val is_unfinished: Boolean = span.content.exists(_.is_unfinished)
   418 
   419 
   420   /* blobs */
   421 
   422   def blobs: List[Command.Blob] = blobs_info._1
   423   def blobs_index: Int = blobs_info._2
   424 
   425   def blobs_names: List[Document.Node.Name] =
   426     for (Exn.Res((name, _)) <- blobs) yield name
   427 
   428   def blobs_defined: List[(Document.Node.Name, SHA1.Digest)] =
   429     for (Exn.Res((name, Some((digest, _)))) <- blobs) yield (name, digest)
   430 
   431   def blobs_changed(doc_blobs: Document.Blobs): Boolean =
   432     blobs.exists({ case Exn.Res((name, _)) => doc_blobs.changed(name) case _ => false })
   433 
   434 
   435   /* source chunks */
   436 
   437   val chunk: Symbol.Text_Chunk = Symbol.Text_Chunk(source)
   438 
   439   val chunks: Map[Symbol.Text_Chunk.Name, Symbol.Text_Chunk] =
   440     ((Symbol.Text_Chunk.Default -> chunk) ::
   441       (for (Exn.Res((name, Some((_, file)))) <- blobs)
   442         yield (Symbol.Text_Chunk.File(name.node) -> file))).toMap
   443 
   444   def length: Int = source.length
   445   def range: Text.Range = chunk.range
   446 
   447   val proper_range: Text.Range =
   448     Text.Range(0,
   449       (length /: span.content.reverse.iterator.takeWhile(_.is_improper))(_ - _.source.length))
   450 
   451   def source(range: Text.Range): String = source.substring(range.start, range.stop)
   452 
   453 
   454   /* accumulated results */
   455 
   456   val init_state: Command.State =
   457     Command.State(this, results = init_results, markups = Command.Markups.init(init_markup))
   458 
   459   val empty_state: Command.State = Command.State(this)
   460 }