src/Pure/PIDE/command.scala
author wenzelm
Tue Jan 16 11:27:52 2018 +0100 (19 months ago ago)
changeset 67446 1f4d167b6ac9
parent 66966 f3f9a492bee6
child 67824 661cd25304ae
permissions -rw-r--r--
discontinued old form of marginal comments;
     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 merge_results(states: List[State]): Results =
   166       Results.merge(states.map(_.results))
   167 
   168     def merge_markups(states: List[State]): Markups =
   169       Markups.merge(states.map(_.markups))
   170 
   171     def merge_markup(states: List[State], index: Markup_Index,
   172         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   173       Markup_Tree.merge(states.map(_.markup(index)), range, elements)
   174 
   175     def merge(command: Command, states: List[State]): State =
   176       State(command, states.flatMap(_.status), merge_results(states), merge_markups(states))
   177 
   178 
   179     /* XML data representation */
   180 
   181     val encode: XML.Encode.T[State] = (st: State) =>
   182     {
   183       import XML.Encode._
   184 
   185       val command = st.command
   186       val blobs_names = command.blobs_names.map(_.node)
   187       val blobs_index = command.blobs_index
   188       require(command.blobs_ok)
   189 
   190       pair(long, pair(string, pair(pair(list(string), int), pair(Command_Span.encode,
   191           pair(list(Markup.encode), pair(Results.encode, Markups.encode(command.source.length)))))))(
   192         (command.id, (command.node_name.node, ((blobs_names, blobs_index), (command.span,
   193           (st.status, (st.results, st.markups)))))))
   194     }
   195 
   196     def decode(node_name: String => Document.Node.Name): XML.Decode.T[State] = (body: XML.Body) =>
   197     {
   198       import XML.Decode._
   199       val (id, (node, ((blobs_names, blobs_index), (span, (status, (results, markups)))))) =
   200         pair(long, pair(string, pair(pair(list(string), int), pair(Command_Span.decode,
   201           pair(list(Markup.decode), pair(Results.decode, Markups.decode))))))(body)
   202 
   203       val blobs_info: Blobs_Info =
   204         (blobs_names.map(name => Exn.Res((node_name(name), None)): Blob), blobs_index)
   205       val command = Command(id, node_name(node), blobs_info, span)
   206       State(command, status, results, markups)
   207     }
   208   }
   209 
   210   sealed case class State(
   211     command: Command,
   212     status: List[Markup] = Nil,
   213     results: Results = Results.empty,
   214     markups: Markups = Markups.empty)
   215   {
   216     lazy val consolidated: Boolean =
   217       status.exists(markup => markup.name == Markup.CONSOLIDATED)
   218 
   219     lazy val protocol_status: Protocol.Status =
   220     {
   221       val warnings =
   222         if (results.iterator.exists(p => Protocol.is_warning(p._2) || Protocol.is_legacy(p._2)))
   223           List(Markup(Markup.WARNING, Nil))
   224         else Nil
   225       val errors =
   226         if (results.iterator.exists(p => Protocol.is_error(p._2)))
   227           List(Markup(Markup.ERROR, Nil))
   228         else Nil
   229       Protocol.Status.make((warnings ::: errors ::: status).iterator)
   230     }
   231 
   232     def markup(index: Markup_Index): Markup_Tree = markups(index)
   233 
   234     def redirect(other_command: Command): Option[State] =
   235     {
   236       val markups1 = markups.redirect(other_command.id)
   237       if (markups1.is_empty) None
   238       else Some(new State(other_command, Nil, Results.empty, markups1))
   239     }
   240 
   241     private def add_status(st: Markup): State =
   242       copy(status = st :: status)
   243 
   244     private def add_markup(
   245       status: Boolean, chunk_name: Symbol.Text_Chunk.Name, m: Text.Markup): State =
   246     {
   247       val markups1 =
   248         if (status || Protocol.liberal_status_elements(m.info.name))
   249           markups.add(Markup_Index(true, chunk_name), m)
   250         else markups
   251       copy(markups = markups1.add(Markup_Index(false, chunk_name), m))
   252     }
   253 
   254     def accumulate(
   255         self_id: Document_ID.Generic => Boolean,
   256         other_id: Document_ID.Generic => Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)],
   257         message: XML.Elem): State =
   258       message match {
   259         case XML.Elem(Markup(Markup.STATUS, _), msgs) =>
   260           (this /: msgs)((state, msg) =>
   261             msg match {
   262               case elem @ XML.Elem(markup, Nil) =>
   263                 state.
   264                   add_status(markup).
   265                   add_markup(true, Symbol.Text_Chunk.Default, Text.Info(command.proper_range, elem))
   266               case _ =>
   267                 Output.warning("Ignored status message: " + msg)
   268                 state
   269             })
   270 
   271         case XML.Elem(Markup(Markup.REPORT, _), msgs) =>
   272           (this /: msgs)((state, msg) =>
   273             {
   274               def bad(): Unit = Output.warning("Ignored report message: " + msg)
   275 
   276               msg match {
   277                 case XML.Elem(Markup(name, atts @ Position.Identified(id, chunk_name)), args) =>
   278 
   279                   val target =
   280                     if (self_id(id) && command.chunks.isDefinedAt(chunk_name))
   281                       Some((chunk_name, command.chunks(chunk_name)))
   282                     else if (chunk_name == Symbol.Text_Chunk.Default) other_id(id)
   283                     else None
   284 
   285                   (target, atts) match {
   286                     case (Some((target_name, target_chunk)), Position.Range(symbol_range)) =>
   287                       target_chunk.incorporate(symbol_range) match {
   288                         case Some(range) =>
   289                           val props = Position.purge(atts)
   290                           val info = Text.Info(range, XML.Elem(Markup(name, props), args))
   291                           state.add_markup(false, target_name, info)
   292                         case None => bad(); state
   293                       }
   294                     case _ =>
   295                       // silently ignore excessive reports
   296                       state
   297                   }
   298 
   299                 case XML.Elem(Markup(name, atts), args)
   300                 if !atts.exists({ case (a, _) => Markup.POSITION_PROPERTIES(a) }) =>
   301                   val range = command.proper_range
   302                   val props = Position.purge(atts)
   303                   val info: Text.Markup = Text.Info(range, XML.Elem(Markup(name, props), args))
   304                   state.add_markup(false, Symbol.Text_Chunk.Default, info)
   305 
   306                 case _ => bad(); state
   307               }
   308             })
   309         case XML.Elem(Markup(name, props), body) =>
   310           props match {
   311             case Markup.Serial(i) =>
   312               val message1 = XML.Elem(Markup(Markup.message(name), props), body)
   313               val message2 = XML.Elem(Markup(name, props), body)
   314 
   315               var st = copy(results = results + (i -> message1))
   316               if (Protocol.is_inlined(message)) {
   317                 for {
   318                   (chunk_name, chunk) <- command.chunks.iterator
   319                   range <- Protocol_Message.positions(
   320                     self_id, command.span.position, chunk_name, chunk, message)
   321                 } st = st.add_markup(false, chunk_name, Text.Info(range, message2))
   322               }
   323               st
   324 
   325             case _ =>
   326               Output.warning("Ignored message without serial number: " + message)
   327               this
   328           }
   329     }
   330   }
   331 
   332 
   333 
   334   /** static content **/
   335 
   336   /* make commands */
   337 
   338   def apply(
   339     id: Document_ID.Command,
   340     node_name: Document.Node.Name,
   341     blobs_info: Blobs_Info,
   342     span: Command_Span.Span): Command =
   343   {
   344     val (source, span1) = span.compact_source
   345     new Command(id, node_name, blobs_info, span1, source, Results.empty, Markup_Tree.empty)
   346   }
   347 
   348   val empty: Command =
   349     Command(Document_ID.none, Document.Node.Name.empty, no_blobs, Command_Span.empty)
   350 
   351   def unparsed(
   352     id: Document_ID.Command,
   353     source: String,
   354     results: Results,
   355     markup: Markup_Tree): Command =
   356   {
   357     val (source1, span1) = Command_Span.unparsed(source).compact_source
   358     new Command(id, Document.Node.Name.empty, no_blobs, span1, source1, results, markup)
   359   }
   360 
   361   def text(source: String): Command =
   362     unparsed(Document_ID.none, source, Results.empty, Markup_Tree.empty)
   363 
   364   def rich_text(id: Document_ID.Command, results: Results, body: XML.Body): Command =
   365   {
   366     val text = XML.content(body)
   367     val markup = Markup_Tree.from_XML(body)
   368     unparsed(id, text, results, markup)
   369   }
   370 
   371 
   372   /* perspective */
   373 
   374   object Perspective
   375   {
   376     val empty: Perspective = Perspective(Nil)
   377   }
   378 
   379   sealed case class Perspective(commands: List[Command])  // visible commands in canonical order
   380   {
   381     def is_empty: Boolean = commands.isEmpty
   382 
   383     def same(that: Perspective): Boolean =
   384     {
   385       val cmds1 = this.commands
   386       val cmds2 = that.commands
   387       require(!cmds1.exists(_.is_undefined))
   388       require(!cmds2.exists(_.is_undefined))
   389       cmds1.length == cmds2.length &&
   390         (cmds1.iterator zip cmds2.iterator).forall({ case (c1, c2) => c1.id == c2.id })
   391     }
   392   }
   393 
   394 
   395   /* blobs: inlined errors and auxiliary files */
   396 
   397   private def clean_tokens(tokens: List[Token]): List[(Token, Int)] =
   398   {
   399     def clean(toks: List[(Token, Int)]): List[(Token, Int)] =
   400       toks match {
   401         case (t1, i1) :: (t2, i2) :: rest =>
   402           if (t1.is_keyword && t1.source == "%" && t2.is_name) clean(rest)
   403           else (t1, i1) :: clean((t2, i2) :: rest)
   404         case _ => toks
   405       }
   406     clean(tokens.zipWithIndex.filter({ case (t, _) => t.is_proper }))
   407   }
   408 
   409   private def find_file(tokens: List[(Token, Int)]): Option[(String, Int)] =
   410     if (tokens.exists({ case (t, _) => t.is_command })) {
   411       tokens.dropWhile({ case (t, _) => !t.is_command }).
   412         collectFirst({ case (t, i) if t.is_embedded => (t.content, i) })
   413     }
   414     else None
   415 
   416   def span_files(syntax: Outer_Syntax, span: Command_Span.Span): (List[String], Int) =
   417     syntax.load_command(span.name) match {
   418       case Some(exts) =>
   419         find_file(clean_tokens(span.content)) match {
   420           case Some((file, i)) =>
   421             if (exts.isEmpty) (List(file), i)
   422             else (exts.map(ext => file + "." + ext), i)
   423           case None => (Nil, -1)
   424         }
   425       case None => (Nil, -1)
   426     }
   427 
   428   def blobs_info(
   429     resources: Resources,
   430     syntax: Outer_Syntax,
   431     get_blob: Document.Node.Name => Option[Document.Blob],
   432     can_import: Document.Node.Name => Boolean,
   433     node_name: Document.Node.Name,
   434     span: Command_Span.Span): Blobs_Info =
   435   {
   436     span.name match {
   437       // inlined errors
   438       case Thy_Header.THEORY =>
   439         val reader = Scan.char_reader(Token.implode(span.content))
   440         val imports = resources.check_thy_reader(node_name, reader).imports
   441         val raw_imports =
   442           try {
   443             val imports1 = Thy_Header.read(reader, Token.Pos.none).imports
   444             if (imports.length == imports1.length) imports1.map(_._1) else error("")
   445           }
   446           catch { case exn: Throwable => List.fill(imports.length)("") }
   447 
   448         val errors =
   449           for { ((import_name, pos), s) <- imports zip raw_imports if !can_import(import_name) }
   450           yield {
   451             val completion =
   452               if (Thy_Header.is_base_name(s)) {
   453                 val completed = Completion.completed(import_name.theory_base_name)
   454                 val qualifier = resources.session_base.theory_qualifier(node_name)
   455                 val dir = node_name.master_dir
   456                 for {
   457                   (_, known_name) <- resources.session_base.known.theories.toList
   458                   if completed(known_name.theory_base_name)
   459                 }
   460                 yield {
   461                   resources.standard_import(
   462                     resources.session_base, qualifier, dir, known_name.theory)
   463                 }
   464               }.sorted
   465               else Nil
   466             val msg =
   467               "Bad theory import " +
   468                 Markup.Path(import_name.node).markup(quote(import_name.toString)) +
   469                 Position.here(pos) + Completion.report_theories(pos, completion)
   470             Exn.Exn(ERROR(msg)): Command.Blob
   471           }
   472         (errors, -1)
   473 
   474       // auxiliary files
   475       case _ =>
   476         val (files, index) = span_files(syntax, span)
   477         val blobs =
   478           files.map(file =>
   479             (Exn.capture {
   480               val name = Document.Node.Name(resources.append(node_name, Path.explode(file)))
   481               val blob = get_blob(name).map(blob => ((blob.bytes.sha1_digest, blob.chunk)))
   482               (name, blob)
   483             }).user_error)
   484         (blobs, index)
   485     }
   486   }
   487 }
   488 
   489 
   490 final class Command private(
   491     val id: Document_ID.Command,
   492     val node_name: Document.Node.Name,
   493     val blobs_info: Command.Blobs_Info,
   494     val span: Command_Span.Span,
   495     val source: String,
   496     val init_results: Command.Results,
   497     val init_markup: Markup_Tree)
   498 {
   499   override def toString: String = id + "/" + span.kind.toString
   500 
   501 
   502   /* classification */
   503 
   504   def is_proper: Boolean = span.kind.isInstanceOf[Command_Span.Command_Span]
   505   def is_ignored: Boolean = span.kind == Command_Span.Ignored_Span
   506 
   507   def is_undefined: Boolean = id == Document_ID.none
   508   val is_unparsed: Boolean = span.content.exists(_.is_unparsed)
   509   val is_unfinished: Boolean = span.content.exists(_.is_unfinished)
   510 
   511 
   512   /* blobs */
   513 
   514   def blobs: List[Command.Blob] = blobs_info._1
   515   def blobs_index: Int = blobs_info._2
   516 
   517   def blobs_ok: Boolean =
   518     blobs.forall({ case Exn.Res(_) => true case _ => false })
   519 
   520   def blobs_names: List[Document.Node.Name] =
   521     for (Exn.Res((name, _)) <- blobs) yield name
   522 
   523   def blobs_undefined: List[Document.Node.Name] =
   524     for (Exn.Res((name, None)) <- blobs) yield name
   525 
   526   def blobs_defined: List[(Document.Node.Name, SHA1.Digest)] =
   527     for (Exn.Res((name, Some((digest, _)))) <- blobs) yield (name, digest)
   528 
   529   def blobs_changed(doc_blobs: Document.Blobs): Boolean =
   530     blobs.exists({ case Exn.Res((name, _)) => doc_blobs.changed(name) case _ => false })
   531 
   532 
   533   /* source chunks */
   534 
   535   val chunk: Symbol.Text_Chunk = Symbol.Text_Chunk(source)
   536 
   537   val chunks: Map[Symbol.Text_Chunk.Name, Symbol.Text_Chunk] =
   538     ((Symbol.Text_Chunk.Default -> chunk) ::
   539       (for (Exn.Res((name, Some((_, file)))) <- blobs)
   540         yield Symbol.Text_Chunk.File(name.node) -> file)).toMap
   541 
   542   def length: Int = source.length
   543   def range: Text.Range = chunk.range
   544 
   545   val proper_range: Text.Range =
   546     Text.Range(0,
   547       (length /: span.content.reverse.iterator.takeWhile(_.is_improper))(_ - _.source.length))
   548 
   549   def source(range: Text.Range): String = range.substring(source)
   550 
   551 
   552   /* accumulated results */
   553 
   554   val init_state: Command.State =
   555     Command.State(this, results = init_results, markups = Command.Markups.init(init_markup))
   556 
   557   val empty_state: Command.State = Command.State(this)
   558 }