src/Pure/PIDE/command.scala
author wenzelm
Sun Mar 11 20:47:17 2018 +0100 (17 months ago ago)
changeset 67825 f9c071cc958b
parent 67824 661cd25304ae
child 67826 5ea76b219668
permissions -rw-r--r--
update XML cache for slightly modified messages;
     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     /* XML data representation */
    37 
    38     val encode: XML.Encode.T[Results] = (results: Results) =>
    39     { import XML.Encode._; list(pair(long, tree))(results.rep.toList) }
    40 
    41     val decode: XML.Decode.T[Results] = (body: XML.Body) =>
    42     { import XML.Decode._; make(list(pair(long, tree))(body)) }
    43   }
    44 
    45   final class Results private(private val rep: SortedMap[Long, XML.Tree])
    46   {
    47     def is_empty: Boolean = rep.isEmpty
    48     def defined(serial: Long): Boolean = rep.isDefinedAt(serial)
    49     def get(serial: Long): Option[XML.Tree] = rep.get(serial)
    50     def iterator: Iterator[Results.Entry] = rep.iterator
    51 
    52     def + (entry: Results.Entry): Results =
    53       if (defined(entry._1)) this
    54       else new Results(rep + entry)
    55 
    56     def ++ (other: Results): Results =
    57       if (this eq other) this
    58       else if (rep.isEmpty) other
    59       else (this /: other.iterator)(_ + _)
    60 
    61     override def hashCode: Int = rep.hashCode
    62     override def equals(that: Any): Boolean =
    63       that match {
    64         case other: Results => rep == other.rep
    65         case _ => false
    66       }
    67     override def toString: String = iterator.mkString("Results(", ", ", ")")
    68   }
    69 
    70 
    71   /* markup */
    72 
    73   object Markup_Index
    74   {
    75     val markup: Markup_Index = Markup_Index(false, Symbol.Text_Chunk.Default)
    76   }
    77 
    78   sealed case class Markup_Index(status: Boolean, chunk_name: Symbol.Text_Chunk.Name)
    79 
    80   object Markups
    81   {
    82     val empty: Markups = new Markups(Map.empty)
    83     def init(markup: Markup_Tree): Markups = new Markups(Map(Markup_Index.markup -> markup))
    84     def merge(args: TraversableOnce[Markups]): Markups = (empty /: args)(_ ++ _)
    85 
    86 
    87     /* XML data representation */
    88 
    89     def encode(source_length: Int): XML.Encode.T[Markups] = (markups: Markups) =>
    90     {
    91       import XML.Encode._
    92 
    93       val markup_index: T[Markup_Index] = (index: Markup_Index) =>
    94         pair(bool, Symbol.Text_Chunk.encode_name)(index.status, index.chunk_name)
    95 
    96       val markup_tree: T[Markup_Tree] =
    97         _.to_XML(Text.Range(0, source_length), Symbol.spaces(source_length), Markup.Elements.full)
    98 
    99       list(pair(markup_index, markup_tree))(markups.rep.toList)
   100     }
   101 
   102     val decode: XML.Decode.T[Markups] = (body: XML.Body) =>
   103     {
   104       import XML.Decode._
   105 
   106       val markup_index: T[Markup_Index] = (body: XML.Body) =>
   107       {
   108         val (status, chunk_name) = pair(bool, Symbol.Text_Chunk.decode_name)(body)
   109         Markup_Index(status, chunk_name)
   110       }
   111 
   112       (Markups.empty /: list(pair(markup_index, Markup_Tree.from_XML(_)))(body))(_ + _)
   113     }
   114   }
   115 
   116   final class Markups private(private val rep: Map[Markup_Index, Markup_Tree])
   117   {
   118     def is_empty: Boolean = rep.isEmpty
   119 
   120     def apply(index: Markup_Index): Markup_Tree =
   121       rep.getOrElse(index, Markup_Tree.empty)
   122 
   123     def add(index: Markup_Index, markup: Text.Markup): Markups =
   124       new Markups(rep + (index -> (this(index) + markup)))
   125 
   126     def + (entry: (Markup_Index, Markup_Tree)): Markups =
   127     {
   128       val (index, tree) = entry
   129       new Markups(rep + (index -> (this(index).merge(tree, Text.Range.full, Markup.Elements.full))))
   130     }
   131 
   132     def ++ (other: Markups): Markups =
   133       if (this eq other) this
   134       else if (rep.isEmpty) other
   135       else (this /: other.rep.iterator)(_ + _)
   136 
   137     def redirection_iterator: Iterator[Document_ID.Generic] =
   138       for (Markup_Index(_, Symbol.Text_Chunk.Id(id)) <- rep.keysIterator)
   139         yield id
   140 
   141     def redirect(other_id: Document_ID.Generic): Markups =
   142     {
   143       val rep1 =
   144         (for {
   145           (Markup_Index(status, Symbol.Text_Chunk.Id(id)), markup) <- rep.iterator
   146           if other_id == id
   147         } yield (Markup_Index(status, Symbol.Text_Chunk.Default), markup)).toMap
   148       if (rep1.isEmpty) Markups.empty else new Markups(rep1)
   149     }
   150 
   151     override def hashCode: Int = rep.hashCode
   152     override def equals(that: Any): Boolean =
   153       that match {
   154         case other: Markups => rep == other.rep
   155         case _ => false
   156       }
   157     override def toString: String = rep.iterator.mkString("Markups(", ", ", ")")
   158   }
   159 
   160 
   161   /* state */
   162 
   163   object State
   164   {
   165     def get_result(states: List[State], serial: Long): Option[XML.Tree] =
   166       states.find(st => st.results.defined(serial)).map(st => st.results.get(serial).get)
   167 
   168     def get_result_proper(states: List[State], props: Properties.T): Option[Results.Entry] =
   169       for {
   170         serial <- Markup.Serial.unapply(props)
   171         tree @ XML.Elem(_, body) <- get_result(states, serial)
   172         if body.nonEmpty
   173       } yield (serial -> tree)
   174 
   175     def merge_results(states: List[State]): Results =
   176       Results.merge(states.map(_.results))
   177 
   178     def merge_markups(states: List[State]): Markups =
   179       Markups.merge(states.map(_.markups))
   180 
   181     def merge_markup(states: List[State], index: Markup_Index,
   182         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   183       Markup_Tree.merge(states.map(_.markup(index)), range, elements)
   184 
   185     def merge(command: Command, states: List[State]): State =
   186       State(command, states.flatMap(_.status), merge_results(states), merge_markups(states))
   187 
   188 
   189     /* XML data representation */
   190 
   191     val encode: XML.Encode.T[State] = (st: State) =>
   192     {
   193       import XML.Encode._
   194 
   195       val command = st.command
   196       val blobs_names = command.blobs_names.map(_.node)
   197       val blobs_index = command.blobs_index
   198       require(command.blobs_ok)
   199 
   200       pair(long, pair(string, pair(pair(list(string), int), pair(Command_Span.encode,
   201           pair(list(Markup.encode), pair(Results.encode, Markups.encode(command.source.length)))))))(
   202         (command.id, (command.node_name.node, ((blobs_names, blobs_index), (command.span,
   203           (st.status, (st.results, st.markups)))))))
   204     }
   205 
   206     def decode(node_name: String => Document.Node.Name): XML.Decode.T[State] = (body: XML.Body) =>
   207     {
   208       import XML.Decode._
   209       val (id, (node, ((blobs_names, blobs_index), (span, (status, (results, markups)))))) =
   210         pair(long, pair(string, pair(pair(list(string), int), pair(Command_Span.decode,
   211           pair(list(Markup.decode), pair(Results.decode, Markups.decode))))))(body)
   212 
   213       val blobs_info: Blobs_Info =
   214         (blobs_names.map(name => Exn.Res((node_name(name), None)): Blob), blobs_index)
   215       val command = Command(id, node_name(node), blobs_info, span)
   216       State(command, status, results, markups)
   217     }
   218   }
   219 
   220   sealed case class State(
   221     command: Command,
   222     status: List[Markup] = Nil,
   223     results: Results = Results.empty,
   224     markups: Markups = Markups.empty)
   225   {
   226     lazy val consolidated: Boolean =
   227       status.exists(markup => markup.name == Markup.CONSOLIDATED)
   228 
   229     lazy val protocol_status: Protocol.Status =
   230     {
   231       val warnings =
   232         if (results.iterator.exists(p => Protocol.is_warning(p._2) || Protocol.is_legacy(p._2)))
   233           List(Markup(Markup.WARNING, Nil))
   234         else Nil
   235       val errors =
   236         if (results.iterator.exists(p => Protocol.is_error(p._2)))
   237           List(Markup(Markup.ERROR, Nil))
   238         else Nil
   239       Protocol.Status.make((warnings ::: errors ::: status).iterator)
   240     }
   241 
   242     def markup(index: Markup_Index): Markup_Tree = markups(index)
   243 
   244     def redirect(other_command: Command): Option[State] =
   245     {
   246       val markups1 = markups.redirect(other_command.id)
   247       if (markups1.is_empty) None
   248       else Some(new State(other_command, Nil, Results.empty, markups1))
   249     }
   250 
   251     private def add_status(st: Markup): State =
   252       copy(status = st :: status)
   253 
   254     private def add_markup(
   255       status: Boolean, chunk_name: Symbol.Text_Chunk.Name, m: Text.Markup): State =
   256     {
   257       val markups1 =
   258         if (status || Protocol.liberal_status_elements(m.info.name))
   259           markups.add(Markup_Index(true, chunk_name), m)
   260         else markups
   261       copy(markups = markups1.add(Markup_Index(false, chunk_name), m))
   262     }
   263 
   264     def accumulate(
   265         self_id: Document_ID.Generic => Boolean,
   266         other_id: Document_ID.Generic => Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)],
   267         message: XML.Elem,
   268         xml_cache: XML.Cache): State =
   269       message match {
   270         case XML.Elem(Markup(Markup.STATUS, _), msgs) =>
   271           (this /: msgs)((state, msg) =>
   272             msg match {
   273               case elem @ XML.Elem(markup, Nil) =>
   274                 state.
   275                   add_status(markup).
   276                   add_markup(true, Symbol.Text_Chunk.Default, Text.Info(command.proper_range, elem))
   277               case _ =>
   278                 Output.warning("Ignored status message: " + msg)
   279                 state
   280             })
   281 
   282         case XML.Elem(Markup(Markup.REPORT, _), msgs) =>
   283           (this /: msgs)((state, msg) =>
   284             {
   285               def bad(): Unit = Output.warning("Ignored report message: " + msg)
   286 
   287               msg match {
   288                 case XML.Elem(Markup(name, atts @ Position.Identified(id, chunk_name)), args) =>
   289 
   290                   val target =
   291                     if (self_id(id) && command.chunks.isDefinedAt(chunk_name))
   292                       Some((chunk_name, command.chunks(chunk_name)))
   293                     else if (chunk_name == Symbol.Text_Chunk.Default) other_id(id)
   294                     else None
   295 
   296                   (target, atts) match {
   297                     case (Some((target_name, target_chunk)), Position.Range(symbol_range)) =>
   298                       target_chunk.incorporate(symbol_range) match {
   299                         case Some(range) =>
   300                           val props = Position.purge(atts)
   301                           val elem = xml_cache.elem(XML.Elem(Markup(name, props), args))
   302                           state.add_markup(false, target_name, Text.Info(range, elem))
   303                         case None => bad(); state
   304                       }
   305                     case _ =>
   306                       // silently ignore excessive reports
   307                       state
   308                   }
   309 
   310                 case XML.Elem(Markup(name, atts), args)
   311                 if !atts.exists({ case (a, _) => Markup.POSITION_PROPERTIES(a) }) =>
   312                   val range = command.proper_range
   313                   val props = Position.purge(atts)
   314                   val elem = xml_cache.elem(XML.Elem(Markup(name, props), args))
   315                   state.add_markup(false, Symbol.Text_Chunk.Default, Text.Info(range, elem))
   316 
   317                 case _ => bad(); state
   318               }
   319             })
   320         case XML.Elem(Markup(name, props), body) =>
   321           props match {
   322             case Markup.Serial(i) =>
   323               val markup_message =
   324                 xml_cache.elem(XML.Elem(Markup(Markup.message(name), props), body))
   325               val message_markup =
   326                 xml_cache.elem(XML.elem(Markup(name, props.filter(p => p._1 == Markup.SERIAL))))
   327 
   328               var st = copy(results = results + (i -> markup_message))
   329               if (Protocol.is_inlined(message)) {
   330                 for {
   331                   (chunk_name, chunk) <- command.chunks.iterator
   332                   range <- Protocol_Message.positions(
   333                     self_id, command.span.position, chunk_name, chunk, message)
   334                 } st = st.add_markup(false, chunk_name, Text.Info(range, message_markup))
   335               }
   336               st
   337 
   338             case _ =>
   339               Output.warning("Ignored message without serial number: " + message)
   340               this
   341           }
   342     }
   343   }
   344 
   345 
   346 
   347   /** static content **/
   348 
   349   /* make commands */
   350 
   351   def apply(
   352     id: Document_ID.Command,
   353     node_name: Document.Node.Name,
   354     blobs_info: Blobs_Info,
   355     span: Command_Span.Span): Command =
   356   {
   357     val (source, span1) = span.compact_source
   358     new Command(id, node_name, blobs_info, span1, source, Results.empty, Markup_Tree.empty)
   359   }
   360 
   361   val empty: Command =
   362     Command(Document_ID.none, Document.Node.Name.empty, no_blobs, Command_Span.empty)
   363 
   364   def unparsed(
   365     id: Document_ID.Command,
   366     source: String,
   367     results: Results,
   368     markup: Markup_Tree): Command =
   369   {
   370     val (source1, span1) = Command_Span.unparsed(source).compact_source
   371     new Command(id, Document.Node.Name.empty, no_blobs, span1, source1, results, markup)
   372   }
   373 
   374   def text(source: String): Command =
   375     unparsed(Document_ID.none, source, Results.empty, Markup_Tree.empty)
   376 
   377   def rich_text(id: Document_ID.Command, results: Results, body: XML.Body): Command =
   378   {
   379     val text = XML.content(body)
   380     val markup = Markup_Tree.from_XML(body)
   381     unparsed(id, text, results, markup)
   382   }
   383 
   384 
   385   /* perspective */
   386 
   387   object Perspective
   388   {
   389     val empty: Perspective = Perspective(Nil)
   390   }
   391 
   392   sealed case class Perspective(commands: List[Command])  // visible commands in canonical order
   393   {
   394     def is_empty: Boolean = commands.isEmpty
   395 
   396     def same(that: Perspective): Boolean =
   397     {
   398       val cmds1 = this.commands
   399       val cmds2 = that.commands
   400       require(!cmds1.exists(_.is_undefined))
   401       require(!cmds2.exists(_.is_undefined))
   402       cmds1.length == cmds2.length &&
   403         (cmds1.iterator zip cmds2.iterator).forall({ case (c1, c2) => c1.id == c2.id })
   404     }
   405   }
   406 
   407 
   408   /* blobs: inlined errors and auxiliary files */
   409 
   410   private def clean_tokens(tokens: List[Token]): List[(Token, Int)] =
   411   {
   412     def clean(toks: List[(Token, Int)]): List[(Token, Int)] =
   413       toks match {
   414         case (t1, i1) :: (t2, i2) :: rest =>
   415           if (t1.is_keyword && t1.source == "%" && t2.is_name) clean(rest)
   416           else (t1, i1) :: clean((t2, i2) :: rest)
   417         case _ => toks
   418       }
   419     clean(tokens.zipWithIndex.filter({ case (t, _) => t.is_proper }))
   420   }
   421 
   422   private def find_file(tokens: List[(Token, Int)]): Option[(String, Int)] =
   423     if (tokens.exists({ case (t, _) => t.is_command })) {
   424       tokens.dropWhile({ case (t, _) => !t.is_command }).
   425         collectFirst({ case (t, i) if t.is_embedded => (t.content, i) })
   426     }
   427     else None
   428 
   429   def span_files(syntax: Outer_Syntax, span: Command_Span.Span): (List[String], Int) =
   430     syntax.load_command(span.name) match {
   431       case Some(exts) =>
   432         find_file(clean_tokens(span.content)) match {
   433           case Some((file, i)) =>
   434             if (exts.isEmpty) (List(file), i)
   435             else (exts.map(ext => file + "." + ext), i)
   436           case None => (Nil, -1)
   437         }
   438       case None => (Nil, -1)
   439     }
   440 
   441   def blobs_info(
   442     resources: Resources,
   443     syntax: Outer_Syntax,
   444     get_blob: Document.Node.Name => Option[Document.Blob],
   445     can_import: Document.Node.Name => Boolean,
   446     node_name: Document.Node.Name,
   447     span: Command_Span.Span): Blobs_Info =
   448   {
   449     span.name match {
   450       // inlined errors
   451       case Thy_Header.THEORY =>
   452         val reader = Scan.char_reader(Token.implode(span.content))
   453         val imports = resources.check_thy_reader(node_name, reader).imports
   454         val raw_imports =
   455           try {
   456             val imports1 = Thy_Header.read(reader, Token.Pos.none).imports
   457             if (imports.length == imports1.length) imports1.map(_._1) else error("")
   458           }
   459           catch { case exn: Throwable => List.fill(imports.length)("") }
   460 
   461         val errors =
   462           for { ((import_name, pos), s) <- imports zip raw_imports if !can_import(import_name) }
   463           yield {
   464             val completion =
   465               if (Thy_Header.is_base_name(s)) {
   466                 val completed = Completion.completed(import_name.theory_base_name)
   467                 val qualifier = resources.session_base.theory_qualifier(node_name)
   468                 val dir = node_name.master_dir
   469                 for {
   470                   (_, known_name) <- resources.session_base.known.theories.toList
   471                   if completed(known_name.theory_base_name)
   472                 }
   473                 yield {
   474                   resources.standard_import(
   475                     resources.session_base, qualifier, dir, known_name.theory)
   476                 }
   477               }.sorted
   478               else Nil
   479             val msg =
   480               "Bad theory import " +
   481                 Markup.Path(import_name.node).markup(quote(import_name.toString)) +
   482                 Position.here(pos) + Completion.report_theories(pos, completion)
   483             Exn.Exn(ERROR(msg)): Command.Blob
   484           }
   485         (errors, -1)
   486 
   487       // auxiliary files
   488       case _ =>
   489         val (files, index) = span_files(syntax, span)
   490         val blobs =
   491           files.map(file =>
   492             (Exn.capture {
   493               val name = Document.Node.Name(resources.append(node_name, Path.explode(file)))
   494               val blob = get_blob(name).map(blob => ((blob.bytes.sha1_digest, blob.chunk)))
   495               (name, blob)
   496             }).user_error)
   497         (blobs, index)
   498     }
   499   }
   500 }
   501 
   502 
   503 final class Command private(
   504     val id: Document_ID.Command,
   505     val node_name: Document.Node.Name,
   506     val blobs_info: Command.Blobs_Info,
   507     val span: Command_Span.Span,
   508     val source: String,
   509     val init_results: Command.Results,
   510     val init_markup: Markup_Tree)
   511 {
   512   override def toString: String = id + "/" + span.kind.toString
   513 
   514 
   515   /* classification */
   516 
   517   def is_proper: Boolean = span.kind.isInstanceOf[Command_Span.Command_Span]
   518   def is_ignored: Boolean = span.kind == Command_Span.Ignored_Span
   519 
   520   def is_undefined: Boolean = id == Document_ID.none
   521   val is_unparsed: Boolean = span.content.exists(_.is_unparsed)
   522   val is_unfinished: Boolean = span.content.exists(_.is_unfinished)
   523 
   524 
   525   /* blobs */
   526 
   527   def blobs: List[Command.Blob] = blobs_info._1
   528   def blobs_index: Int = blobs_info._2
   529 
   530   def blobs_ok: Boolean =
   531     blobs.forall({ case Exn.Res(_) => true case _ => false })
   532 
   533   def blobs_names: List[Document.Node.Name] =
   534     for (Exn.Res((name, _)) <- blobs) yield name
   535 
   536   def blobs_undefined: List[Document.Node.Name] =
   537     for (Exn.Res((name, None)) <- blobs) yield name
   538 
   539   def blobs_defined: List[(Document.Node.Name, SHA1.Digest)] =
   540     for (Exn.Res((name, Some((digest, _)))) <- blobs) yield (name, digest)
   541 
   542   def blobs_changed(doc_blobs: Document.Blobs): Boolean =
   543     blobs.exists({ case Exn.Res((name, _)) => doc_blobs.changed(name) case _ => false })
   544 
   545 
   546   /* source chunks */
   547 
   548   val chunk: Symbol.Text_Chunk = Symbol.Text_Chunk(source)
   549 
   550   val chunks: Map[Symbol.Text_Chunk.Name, Symbol.Text_Chunk] =
   551     ((Symbol.Text_Chunk.Default -> chunk) ::
   552       (for (Exn.Res((name, Some((_, file)))) <- blobs)
   553         yield Symbol.Text_Chunk.File(name.node) -> file)).toMap
   554 
   555   def length: Int = source.length
   556   def range: Text.Range = chunk.range
   557 
   558   val proper_range: Text.Range =
   559     Text.Range(0,
   560       (length /: span.content.reverse.iterator.takeWhile(_.is_improper))(_ - _.source.length))
   561 
   562   def source(range: Text.Range): String = range.substring(source)
   563 
   564 
   565   /* accumulated results */
   566 
   567   val init_state: Command.State =
   568     Command.State(this, results = init_results, markups = Command.Markups.init(init_markup))
   569 
   570   val empty_state: Command.State = Command.State(this)
   571 }