src/Pure/PIDE/command.scala
author wenzelm
Sat Jan 07 20:37:48 2017 +0100 (2017-01-07 ago)
changeset 64825 e78b62c289bb
parent 64824 330ec9bc4b75
child 65335 7634d33c1a79
permissions -rw-r--r--
more uniform node_header (non-strict);
removed dead code;
     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 
    14 
    15 object Command
    16 {
    17   type Edit = (Option[Command], Option[Command])
    18 
    19   type Blob = Exn.Result[(Document.Node.Name, Option[(SHA1.Digest, Symbol.Text_Chunk)])]
    20   type Blobs_Info = (List[Blob], Int)
    21   val no_blobs: Blobs_Info = (Nil, -1)
    22 
    23 
    24   /** accumulated results from prover **/
    25 
    26   /* results */
    27 
    28   object Results
    29   {
    30     type Entry = (Long, XML.Tree)
    31     val empty = new Results(SortedMap.empty)
    32     def make(args: TraversableOnce[Results.Entry]): Results = (empty /: args)(_ + _)
    33     def merge(args: TraversableOnce[Results]): Results = (empty /: args)(_ ++ _)
    34   }
    35 
    36   final class Results private(private val rep: SortedMap[Long, XML.Tree])
    37   {
    38     def is_empty: Boolean = rep.isEmpty
    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     private def add_status(st: Markup): State =
   154       copy(status = st :: status)
   155 
   156     private def add_markup(
   157       status: Boolean, chunk_name: Symbol.Text_Chunk.Name, m: Text.Markup): State =
   158     {
   159       val markups1 =
   160         if (status || Protocol.liberal_status_elements(m.info.name))
   161           markups.add(Markup_Index(true, chunk_name), m)
   162         else markups
   163       copy(markups = markups1.add(Markup_Index(false, chunk_name), m))
   164     }
   165 
   166     def accumulate(
   167         self_id: Document_ID.Generic => Boolean,
   168         other_id: Document_ID.Generic => Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)],
   169         message: XML.Elem): State =
   170       message match {
   171         case XML.Elem(Markup(Markup.STATUS, _), msgs) =>
   172           (this /: msgs)((state, msg) =>
   173             msg match {
   174               case elem @ XML.Elem(markup, Nil) =>
   175                 state.
   176                   add_status(markup).
   177                   add_markup(true, Symbol.Text_Chunk.Default, Text.Info(command.proper_range, elem))
   178               case _ =>
   179                 Output.warning("Ignored status message: " + msg)
   180                 state
   181             })
   182 
   183         case XML.Elem(Markup(Markup.REPORT, _), msgs) =>
   184           (this /: msgs)((state, msg) =>
   185             {
   186               def bad(): Unit = Output.warning("Ignored report message: " + msg)
   187 
   188               msg match {
   189                 case XML.Elem(Markup(name, atts @ Position.Identified(id, chunk_name)), args) =>
   190 
   191                   val target =
   192                     if (self_id(id) && command.chunks.isDefinedAt(chunk_name))
   193                       Some((chunk_name, command.chunks(chunk_name)))
   194                     else if (chunk_name == Symbol.Text_Chunk.Default) other_id(id)
   195                     else None
   196 
   197                   (target, atts) match {
   198                     case (Some((target_name, target_chunk)), Position.Range(symbol_range)) =>
   199                       target_chunk.incorporate(symbol_range) match {
   200                         case Some(range) =>
   201                           val props = Position.purge(atts)
   202                           val info = Text.Info(range, XML.Elem(Markup(name, props), args))
   203                           state.add_markup(false, target_name, info)
   204                         case None => bad(); state
   205                       }
   206                     case _ =>
   207                       // silently ignore excessive reports
   208                       state
   209                   }
   210 
   211                 case XML.Elem(Markup(name, atts), args)
   212                 if !atts.exists({ case (a, _) => Markup.POSITION_PROPERTIES(a) }) =>
   213                   val range = command.proper_range
   214                   val props = Position.purge(atts)
   215                   val info: Text.Markup = Text.Info(range, XML.Elem(Markup(name, props), args))
   216                   state.add_markup(false, Symbol.Text_Chunk.Default, info)
   217 
   218                 case _ => bad(); state
   219               }
   220             })
   221         case XML.Elem(Markup(name, props), body) =>
   222           props match {
   223             case Markup.Serial(i) =>
   224               val message1 = XML.Elem(Markup(Markup.message(name), props), body)
   225               val message2 = XML.Elem(Markup(name, props), body)
   226 
   227               var st = copy(results = results + (i -> message1))
   228               if (Protocol.is_inlined(message)) {
   229                 for {
   230                   (chunk_name, chunk) <- command.chunks.iterator
   231                   range <- Protocol_Message.positions(
   232                     self_id, command.span.position, chunk_name, chunk, message)
   233                 } st = st.add_markup(false, chunk_name, Text.Info(range, message2))
   234               }
   235               st
   236 
   237             case _ =>
   238               Output.warning("Ignored message without serial number: " + message)
   239               this
   240           }
   241     }
   242   }
   243 
   244 
   245 
   246   /** static content **/
   247 
   248   /* make commands */
   249 
   250   def apply(
   251     id: Document_ID.Command,
   252     node_name: Document.Node.Name,
   253     blobs_info: Blobs_Info,
   254     span: Command_Span.Span): Command =
   255   {
   256     val (source, span1) = span.compact_source
   257     new Command(id, node_name, blobs_info, span1, source, Results.empty, Markup_Tree.empty)
   258   }
   259 
   260   val empty: Command =
   261     Command(Document_ID.none, Document.Node.Name.empty, no_blobs, Command_Span.empty)
   262 
   263   def unparsed(
   264     id: Document_ID.Command,
   265     source: String,
   266     results: Results,
   267     markup: Markup_Tree): Command =
   268   {
   269     val (source1, span1) = Command_Span.unparsed(source).compact_source
   270     new Command(id, Document.Node.Name.empty, no_blobs, span1, source1, results, markup)
   271   }
   272 
   273   def unparsed(source: String): Command =
   274     unparsed(Document_ID.none, source, Results.empty, Markup_Tree.empty)
   275 
   276   def rich_text(id: Document_ID.Command, results: Results, body: XML.Body): Command =
   277   {
   278     val text = XML.content(body)
   279     val markup = Markup_Tree.from_XML(body)
   280     unparsed(id, text, results, markup)
   281   }
   282 
   283 
   284   /* perspective */
   285 
   286   object Perspective
   287   {
   288     val empty: Perspective = Perspective(Nil)
   289   }
   290 
   291   sealed case class Perspective(commands: List[Command])  // visible commands in canonical order
   292   {
   293     def is_empty: Boolean = commands.isEmpty
   294 
   295     def same(that: Perspective): Boolean =
   296     {
   297       val cmds1 = this.commands
   298       val cmds2 = that.commands
   299       require(!cmds1.exists(_.is_undefined))
   300       require(!cmds2.exists(_.is_undefined))
   301       cmds1.length == cmds2.length &&
   302         (cmds1.iterator zip cmds2.iterator).forall({ case (c1, c2) => c1.id == c2.id })
   303     }
   304   }
   305 
   306 
   307   /* blobs: inlined errors and auxiliary files */
   308 
   309   private def clean_tokens(tokens: List[Token]): List[(Token, Int)] =
   310   {
   311     val markers = Set("%", "--", Symbol.comment, Symbol.comment_decoded)
   312     def clean(toks: List[(Token, Int)]): List[(Token, Int)] =
   313       toks match {
   314         case (t1, i1) :: (t2, i2) :: rest =>
   315           if (t1.is_keyword && markers(t1.source)) clean(rest)
   316           else (t1, i1) :: clean((t2, i2) :: rest)
   317         case _ => toks
   318       }
   319     clean(tokens.zipWithIndex.filter({ case (t, _) => t.is_proper }))
   320   }
   321 
   322   private def find_file(tokens: List[(Token, Int)]): Option[(String, Int)] =
   323     if (tokens.exists({ case (t, _) => t.is_command })) {
   324       tokens.dropWhile({ case (t, _) => !t.is_command }).
   325         collectFirst({ case (t, i) if t.is_embedded => (t.content, i) })
   326     }
   327     else None
   328 
   329   def span_files(syntax: Outer_Syntax, span: Command_Span.Span): (List[String], Int) =
   330     syntax.load_command(span.name) match {
   331       case Some(exts) =>
   332         find_file(clean_tokens(span.content)) match {
   333           case Some((file, i)) =>
   334             if (exts.isEmpty) (List(file), i)
   335             else (exts.map(ext => file + "." + ext), i)
   336           case None => (Nil, -1)
   337         }
   338       case None => (Nil, -1)
   339     }
   340 
   341   def blobs_info(
   342     resources: Resources,
   343     syntax: Outer_Syntax,
   344     get_blob: Document.Node.Name => Option[Document.Blob],
   345     can_import: Document.Node.Name => Boolean,
   346     node_name: Document.Node.Name,
   347     span: Command_Span.Span): Blobs_Info =
   348   {
   349     span.name match {
   350       // inlined errors
   351       case Thy_Header.THEORY =>
   352         val reader = Scan.char_reader(Token.implode(span.content))
   353         val header = resources.check_thy_reader("", node_name, reader)
   354         val errors =
   355           for ((imp, pos) <- header.imports if !can_import(imp)) yield {
   356             val msg =
   357               "Bad theory import " +
   358                 Markup.Path(imp.node).markup(quote(imp.toString)) + Position.here(pos)
   359             Exn.Exn(ERROR(msg)): Command.Blob
   360           }
   361         (errors, -1)
   362 
   363       // auxiliary files
   364       case _ =>
   365         val (files, index) = span_files(syntax, span)
   366         val blobs =
   367           files.map(file =>
   368             (Exn.capture {
   369               val name =
   370                 Document.Node.Name(resources.append(node_name.master_dir, Path.explode(file)))
   371               val blob = get_blob(name).map(blob => ((blob.bytes.sha1_digest, blob.chunk)))
   372               (name, blob)
   373             }).user_error)
   374         (blobs, index)
   375     }
   376   }
   377 }
   378 
   379 
   380 final class Command private(
   381     val id: Document_ID.Command,
   382     val node_name: Document.Node.Name,
   383     val blobs_info: Command.Blobs_Info,
   384     val span: Command_Span.Span,
   385     val source: String,
   386     val init_results: Command.Results,
   387     val init_markup: Markup_Tree)
   388 {
   389   override def toString: String = id + "/" + span.kind.toString
   390 
   391 
   392   /* classification */
   393 
   394   def is_proper: Boolean = span.kind.isInstanceOf[Command_Span.Command_Span]
   395   def is_ignored: Boolean = span.kind == Command_Span.Ignored_Span
   396 
   397   def is_undefined: Boolean = id == Document_ID.none
   398   val is_unparsed: Boolean = span.content.exists(_.is_unparsed)
   399   val is_unfinished: Boolean = span.content.exists(_.is_unfinished)
   400 
   401 
   402   /* blobs */
   403 
   404   def blobs: List[Command.Blob] = blobs_info._1
   405   def blobs_index: Int = blobs_info._2
   406 
   407   def blobs_names: List[Document.Node.Name] =
   408     for (Exn.Res((name, _)) <- blobs) yield name
   409 
   410   def blobs_undefined: List[Document.Node.Name] =
   411     for (Exn.Res((name, None)) <- blobs) yield name
   412 
   413   def blobs_defined: List[(Document.Node.Name, SHA1.Digest)] =
   414     for (Exn.Res((name, Some((digest, _)))) <- blobs) yield (name, digest)
   415 
   416   def blobs_changed(doc_blobs: Document.Blobs): Boolean =
   417     blobs.exists({ case Exn.Res((name, _)) => doc_blobs.changed(name) case _ => false })
   418 
   419 
   420   /* source chunks */
   421 
   422   val chunk: Symbol.Text_Chunk = Symbol.Text_Chunk(source)
   423 
   424   val chunks: Map[Symbol.Text_Chunk.Name, Symbol.Text_Chunk] =
   425     ((Symbol.Text_Chunk.Default -> chunk) ::
   426       (for (Exn.Res((name, Some((_, file)))) <- blobs)
   427         yield Symbol.Text_Chunk.File(name.node) -> file)).toMap
   428 
   429   def length: Int = source.length
   430   def range: Text.Range = chunk.range
   431 
   432   val proper_range: Text.Range =
   433     Text.Range(0,
   434       (length /: span.content.reverse.iterator.takeWhile(_.is_improper))(_ - _.source.length))
   435 
   436   def source(range: Text.Range): String = source.substring(range.start, range.stop)
   437 
   438 
   439   /* accumulated results */
   440 
   441   val init_state: Command.State =
   442     Command.State(this, results = init_results, markups = Command.Markups.init(init_markup))
   443 
   444   val empty_state: Command.State = Command.State(this)
   445 }