src/Pure/Thy/thy_syntax.scala
author wenzelm
Mon Aug 11 20:46:56 2014 +0200 (2014-08-11)
changeset 57900 fd03765b06c0
parent 57842 8e4ae2db1849
child 57901 e1abca2527da
permissions -rw-r--r--
clarified modules;
     1 /*  Title:      Pure/Thy/thy_syntax.scala
     2     Author:     Makarius
     3 
     4 Superficial theory syntax: tokens and spans.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import scala.collection.mutable
    11 import scala.annotation.tailrec
    12 
    13 
    14 object Thy_Syntax
    15 {
    16   /** parse spans **/
    17 
    18   def parse_spans(toks: List[Token]): List[List[Token]] =
    19   {
    20     val result = new mutable.ListBuffer[List[Token]]
    21     val span = new mutable.ListBuffer[Token]
    22     val improper = new mutable.ListBuffer[Token]
    23 
    24     def flush()
    25     {
    26       if (!span.isEmpty) { result += span.toList; span.clear }
    27       if (!improper.isEmpty) { result += improper.toList; improper.clear }
    28     }
    29     for (tok <- toks) {
    30       if (tok.is_command) { flush(); span += tok }
    31       else if (tok.is_improper) improper += tok
    32       else { span ++= improper; improper.clear; span += tok }
    33     }
    34     flush()
    35 
    36     result.toList
    37   }
    38 
    39 
    40 
    41   /** perspective **/
    42 
    43   def command_perspective(
    44       node: Document.Node,
    45       perspective: Text.Perspective,
    46       overlays: Document.Node.Overlays): (Command.Perspective, Command.Perspective) =
    47   {
    48     if (perspective.is_empty && overlays.is_empty)
    49       (Command.Perspective.empty, Command.Perspective.empty)
    50     else {
    51       val has_overlay = overlays.commands
    52       val visible = new mutable.ListBuffer[Command]
    53       val visible_overlay = new mutable.ListBuffer[Command]
    54       @tailrec
    55       def check_ranges(ranges: List[Text.Range], commands: Stream[(Command, Text.Offset)])
    56       {
    57         (ranges, commands) match {
    58           case (range :: more_ranges, (command, offset) #:: more_commands) =>
    59             val command_range = command.range + offset
    60             range compare command_range match {
    61               case 0 =>
    62                 visible += command
    63                 visible_overlay += command
    64                 check_ranges(ranges, more_commands)
    65               case c =>
    66                 if (has_overlay(command)) visible_overlay += command
    67 
    68                 if (c < 0) check_ranges(more_ranges, commands)
    69                 else check_ranges(ranges, more_commands)
    70             }
    71 
    72           case (Nil, (command, _) #:: more_commands) =>
    73             if (has_overlay(command)) visible_overlay += command
    74 
    75             check_ranges(Nil, more_commands)
    76 
    77           case _ =>
    78         }
    79       }
    80 
    81       val commands =
    82         (if (overlays.is_empty) node.command_iterator(perspective.range)
    83          else node.command_iterator()).toStream
    84       check_ranges(perspective.ranges, commands)
    85       (Command.Perspective(visible.toList), Command.Perspective(visible_overlay.toList))
    86     }
    87   }
    88 
    89 
    90 
    91   /** header edits: structure and outer syntax **/
    92 
    93   private def header_edits(
    94     resources: Resources,
    95     previous: Document.Version,
    96     edits: List[Document.Edit_Text]):
    97     (Prover.Syntax, Boolean, Boolean, List[Document.Node.Name], Document.Nodes,
    98       List[Document.Edit_Command]) =
    99   {
   100     var updated_imports = false
   101     var updated_keywords = false
   102     var nodes = previous.nodes
   103     val doc_edits = new mutable.ListBuffer[Document.Edit_Command]
   104 
   105     edits foreach {
   106       case (name, Document.Node.Deps(header)) =>
   107         val node = nodes(name)
   108         val update_header =
   109           !node.header.errors.isEmpty || !header.errors.isEmpty || node.header != header
   110         if (update_header) {
   111           val node1 = node.update_header(header)
   112           updated_imports = updated_imports || (node.header.imports != node1.header.imports)
   113           updated_keywords = updated_keywords || (node.header.keywords != node1.header.keywords)
   114           nodes += (name -> node1)
   115           doc_edits += (name -> Document.Node.Deps(header))
   116         }
   117       case _ =>
   118     }
   119 
   120     val (syntax, syntax_changed) =
   121       previous.syntax match {
   122         case Some(syntax) if !updated_keywords =>
   123           (syntax, false)
   124         case _ =>
   125           val syntax =
   126             (resources.base_syntax /: nodes.iterator) {
   127               case (syn, (_, node)) => syn.add_keywords(node.header.keywords)
   128             }
   129           (syntax, true)
   130       }
   131 
   132     val reparse =
   133       if (updated_imports || updated_keywords)
   134         nodes.descendants(doc_edits.iterator.map(_._1).toList)
   135       else Nil
   136 
   137     (syntax, syntax_changed, updated_imports, reparse, nodes, doc_edits.toList)
   138   }
   139 
   140 
   141 
   142   /** text edits **/
   143 
   144   /* edit individual command source */
   145 
   146   @tailrec def edit_text(eds: List[Text.Edit], commands: Linear_Set[Command]): Linear_Set[Command] =
   147   {
   148     eds match {
   149       case e :: es =>
   150         Document.Node.Commands.starts(commands.iterator).find {
   151           case (cmd, cmd_start) =>
   152             e.can_edit(cmd.source, cmd_start) ||
   153               e.is_insert && e.start == cmd_start + cmd.length
   154         } match {
   155           case Some((cmd, cmd_start)) if e.can_edit(cmd.source, cmd_start) =>
   156             val (rest, text) = e.edit(cmd.source, cmd_start)
   157             val new_commands = commands.insert_after(Some(cmd), Command.unparsed(text)) - cmd
   158             edit_text(rest.toList ::: es, new_commands)
   159 
   160           case Some((cmd, cmd_start)) =>
   161             edit_text(es, commands.insert_after(Some(cmd), Command.unparsed(e.text)))
   162 
   163           case None =>
   164             require(e.is_insert && e.start == 0)
   165             edit_text(es, commands.insert_after(None, Command.unparsed(e.text)))
   166         }
   167       case Nil => commands
   168     }
   169   }
   170 
   171 
   172   /* inlined files */
   173 
   174   private def find_file(tokens: List[Token]): Option[String] =
   175   {
   176     def clean(toks: List[Token]): List[Token] =
   177       toks match {
   178         case t :: _ :: ts if t.is_keyword && (t.source == "%" || t.source == "--") => clean(ts)
   179         case t :: ts => t :: clean(ts)
   180         case Nil => Nil
   181       }
   182     clean(tokens.filter(_.is_proper)) match {
   183       case tok :: toks if tok.is_command => toks.find(_.is_name).map(_.content)
   184       case _ => None
   185     }
   186   }
   187 
   188   def span_files(syntax: Prover.Syntax, span: List[Token]): List[String] =
   189     syntax.load(span) match {
   190       case Some(exts) =>
   191         find_file(span) match {
   192           case Some(file) =>
   193             if (exts.isEmpty) List(file)
   194             else exts.map(ext => file + "." + ext)
   195           case None => Nil
   196         }
   197       case None => Nil
   198     }
   199 
   200   def resolve_files(
   201       resources: Resources,
   202       syntax: Prover.Syntax,
   203       node_name: Document.Node.Name,
   204       span: List[Token],
   205       get_blob: Document.Node.Name => Option[Document.Blob])
   206     : List[Command.Blob] =
   207   {
   208     span_files(syntax, span).map(file_name =>
   209       Exn.capture {
   210         val name =
   211           Document.Node.Name(resources.append(node_name.master_dir, Path.explode(file_name)))
   212         val blob = get_blob(name).map(blob => ((blob.bytes.sha1_digest, blob.chunk)))
   213         (name, blob)
   214       })
   215   }
   216 
   217 
   218   /* reparse range of command spans */
   219 
   220   @tailrec private def chop_common(
   221       cmds: List[Command],
   222       blobs_spans: List[(List[Command.Blob], List[Token])])
   223     : (List[Command], List[(List[Command.Blob], List[Token])]) =
   224   {
   225     (cmds, blobs_spans) match {
   226       case (cmd :: cmds, (blobs, span) :: rest) if cmd.blobs == blobs && cmd.span == span =>
   227         chop_common(cmds, rest)
   228       case _ => (cmds, blobs_spans)
   229     }
   230   }
   231 
   232   private def reparse_spans(
   233     resources: Resources,
   234     syntax: Prover.Syntax,
   235     get_blob: Document.Node.Name => Option[Document.Blob],
   236     name: Document.Node.Name,
   237     commands: Linear_Set[Command],
   238     first: Command, last: Command): Linear_Set[Command] =
   239   {
   240     val cmds0 = commands.iterator(first, last).toList
   241     val blobs_spans0 =
   242       parse_spans(syntax.scan(cmds0.iterator.map(_.source).mkString)).
   243         map(span => (resolve_files(resources, syntax, name, span, get_blob), span))
   244 
   245     val (cmds1, blobs_spans1) = chop_common(cmds0, blobs_spans0)
   246 
   247     val (rev_cmds2, rev_blobs_spans2) = chop_common(cmds1.reverse, blobs_spans1.reverse)
   248     val cmds2 = rev_cmds2.reverse
   249     val blobs_spans2 = rev_blobs_spans2.reverse
   250 
   251     cmds2 match {
   252       case Nil =>
   253         assert(blobs_spans2.isEmpty)
   254         commands
   255       case cmd :: _ =>
   256         val hook = commands.prev(cmd)
   257         val inserted =
   258           blobs_spans2.map({ case (blobs, span) => Command(Document_ID.make(), name, blobs, span) })
   259         (commands /: cmds2)(_ - _).append_after(hook, inserted)
   260     }
   261   }
   262 
   263 
   264   /* recover command spans after edits */
   265 
   266   // FIXME somewhat slow
   267   private def recover_spans(
   268     resources: Resources,
   269     syntax: Prover.Syntax,
   270     get_blob: Document.Node.Name => Option[Document.Blob],
   271     name: Document.Node.Name,
   272     perspective: Command.Perspective,
   273     commands: Linear_Set[Command]): Linear_Set[Command] =
   274   {
   275     val visible = perspective.commands.toSet
   276 
   277     def next_invisible_command(cmds: Linear_Set[Command], from: Command): Command =
   278       cmds.iterator(from).dropWhile(cmd => !cmd.is_command || visible(cmd))
   279         .find(_.is_command) getOrElse cmds.last
   280 
   281     @tailrec def recover(cmds: Linear_Set[Command]): Linear_Set[Command] =
   282       cmds.find(_.is_unparsed) match {
   283         case Some(first_unparsed) =>
   284           val first = next_invisible_command(cmds.reverse, first_unparsed)
   285           val last = next_invisible_command(cmds, first_unparsed)
   286           recover(reparse_spans(resources, syntax, get_blob, name, cmds, first, last))
   287         case None => cmds
   288       }
   289     recover(commands)
   290   }
   291 
   292 
   293   /* consolidate unfinished spans */
   294 
   295   private def consolidate_spans(
   296     resources: Resources,
   297     syntax: Prover.Syntax,
   298     get_blob: Document.Node.Name => Option[Document.Blob],
   299     reparse_limit: Int,
   300     name: Document.Node.Name,
   301     perspective: Command.Perspective,
   302     commands: Linear_Set[Command]): Linear_Set[Command] =
   303   {
   304     if (perspective.commands.isEmpty) commands
   305     else {
   306       commands.find(_.is_unfinished) match {
   307         case Some(first_unfinished) =>
   308           val visible = perspective.commands.toSet
   309           commands.reverse.find(visible) match {
   310             case Some(last_visible) =>
   311               val it = commands.iterator(last_visible)
   312               var last = last_visible
   313               var i = 0
   314               while (i < reparse_limit && it.hasNext) {
   315                 last = it.next
   316                 i += last.length
   317               }
   318               reparse_spans(resources, syntax, get_blob, name, commands, first_unfinished, last)
   319             case None => commands
   320           }
   321         case None => commands
   322       }
   323     }
   324   }
   325 
   326 
   327   /* main */
   328 
   329   def diff_commands(old_cmds: Linear_Set[Command], new_cmds: Linear_Set[Command])
   330     : List[Command.Edit] =
   331   {
   332     val removed = old_cmds.iterator.filter(!new_cmds.contains(_)).toList
   333     val inserted = new_cmds.iterator.filter(!old_cmds.contains(_)).toList
   334 
   335     removed.reverse.map(cmd => (old_cmds.prev(cmd), None)) :::
   336     inserted.map(cmd => (new_cmds.prev(cmd), Some(cmd)))
   337   }
   338 
   339   private def text_edit(
   340     resources: Resources,
   341     syntax: Prover.Syntax,
   342     get_blob: Document.Node.Name => Option[Document.Blob],
   343     reparse_limit: Int,
   344     node: Document.Node, edit: Document.Edit_Text): Document.Node =
   345   {
   346     edit match {
   347       case (_, Document.Node.Clear()) => node.clear
   348 
   349       case (_, Document.Node.Blob(blob)) => node.init_blob(blob)
   350 
   351       case (name, Document.Node.Edits(text_edits)) =>
   352         if (name.is_theory) {
   353           val commands0 = node.commands
   354           val commands1 = edit_text(text_edits, commands0)
   355           val commands2 =
   356             recover_spans(resources, syntax, get_blob, name, node.perspective.visible, commands1)
   357           node.update_commands(commands2)
   358         }
   359         else node
   360 
   361       case (_, Document.Node.Deps(_)) => node
   362 
   363       case (name, Document.Node.Perspective(required, text_perspective, overlays)) =>
   364         val (visible, visible_overlay) = command_perspective(node, text_perspective, overlays)
   365         val perspective: Document.Node.Perspective_Command =
   366           Document.Node.Perspective(required, visible_overlay, overlays)
   367         if (node.same_perspective(perspective)) node
   368         else
   369           node.update_perspective(perspective).update_commands(
   370             consolidate_spans(resources, syntax, get_blob, reparse_limit,
   371               name, visible, node.commands))
   372     }
   373   }
   374 
   375   def parse_change(
   376       resources: Resources,
   377       reparse_limit: Int,
   378       previous: Document.Version,
   379       doc_blobs: Document.Blobs,
   380       edits: List[Document.Edit_Text]): Session.Change =
   381   {
   382     def get_blob(name: Document.Node.Name) =
   383       doc_blobs.get(name) orElse previous.nodes(name).get_blob
   384 
   385     val (syntax, syntax_changed, deps_changed, reparse0, nodes0, doc_edits0) =
   386       header_edits(resources, previous, edits)
   387 
   388     val (doc_edits, version) =
   389       if (edits.isEmpty) (Nil, Document.Version.make(Some(syntax), previous.nodes))
   390       else {
   391         val reparse =
   392           (reparse0 /: nodes0.iterator)({
   393             case (reparse, (name, node)) =>
   394               if (node.load_commands.exists(_.blobs_changed(doc_blobs)))
   395                 name :: reparse
   396               else reparse
   397             })
   398         val reparse_set = reparse.toSet
   399 
   400         var nodes = nodes0
   401         val doc_edits = new mutable.ListBuffer[Document.Edit_Command]; doc_edits ++= doc_edits0
   402 
   403         val node_edits =
   404           (edits ::: reparse.map((_, Document.Node.Edits(Nil)))).groupBy(_._1)
   405             .asInstanceOf[Map[Document.Node.Name, List[Document.Edit_Text]]]  // FIXME ???
   406 
   407         node_edits foreach {
   408           case (name, edits) =>
   409             val node = nodes(name)
   410             val commands = node.commands
   411 
   412             val node1 =
   413               if (reparse_set(name) && !commands.isEmpty)
   414                 node.update_commands(
   415                   reparse_spans(resources, syntax, get_blob,
   416                     name, commands, commands.head, commands.last))
   417               else node
   418             val node2 =
   419               (node1 /: edits)(text_edit(resources, syntax, get_blob, reparse_limit, _, _))
   420 
   421             if (!(node.same_perspective(node2.perspective)))
   422               doc_edits += (name -> node2.perspective)
   423 
   424             doc_edits += (name -> Document.Node.Edits(diff_commands(commands, node2.commands)))
   425 
   426             nodes += (name -> node2)
   427         }
   428         (doc_edits.toList.filterNot(_._2.is_void), Document.Version.make(Some(syntax), nodes))
   429       }
   430 
   431     Session.Change(previous, syntax_changed, deps_changed, doc_edits, version)
   432   }
   433 }