src/Pure/Thy/thy_header.scala
author wenzelm
Sun, 27 Dec 2009 22:36:47 +0100
changeset 34190 dfcf667bbfed
parent 34188 fbfc18be1f8c
child 34192 619552fe8d7f
permissions -rw-r--r--
read header by scanning/parsing file;
     1 /*  Title:      Pure/Thy/thy_header.scala
     2     Author:     Makarius
     3 
     4 Theory headers -- independent of outer syntax.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import scala.collection.mutable
    11 import scala.util.parsing.input.{Reader, CharSequenceReader}
    12 
    13 import java.io.File
    14 
    15 
    16 object Thy_Header
    17 {
    18   val HEADER = "header"
    19   val THEORY = "theory"
    20   val IMPORTS = "imports"
    21   val USES = "uses"
    22   val BEGIN = "begin"
    23 
    24   val lexicon = Scan.Lexicon("%", "(", ")", ";", BEGIN, HEADER, IMPORTS, THEORY, USES)
    25 
    26   sealed case class Header(val name: String, val imports: List[String], val uses: List[String])
    27 }
    28 
    29 
    30 class Thy_Header(symbols: Symbol.Interpretation) extends Outer_Parse.Parser
    31 {
    32   import Thy_Header._
    33 
    34 
    35   /* header */
    36 
    37   val header: Parser[Header] =
    38   {
    39     val file_name = atom("file name", _.is_name)
    40     val theory_name = atom("theory name", _.is_name)
    41 
    42     val file =
    43       keyword("(") ~! (file_name ~ keyword(")")) ^^ { case _ ~ (x ~ _) => x } | file_name
    44 
    45     val uses = opt(keyword(USES) ~! (rep1(file))) ^^ { case None => Nil case Some(_ ~ xs) => xs }
    46 
    47     val args =
    48       theory_name ~ (keyword(IMPORTS) ~! (rep1(theory_name) ~ uses ~ keyword(BEGIN))) ^^
    49         { case x ~ (_ ~ (ys ~ zs ~ _)) => Header(x, ys, zs) }
    50 
    51     (keyword(HEADER) ~ tags) ~!
    52       ((doc_source ~ rep(keyword(";")) ~ keyword(THEORY) ~ tags) ~> args) ^^ { case _ ~ x => x } |
    53     (keyword(THEORY) ~ tags) ~! args ^^ { case _ ~ x => x }
    54   }
    55 
    56 
    57   /* read -- lazy scanning */
    58 
    59   def read(file: File): Header =
    60   {
    61     val token = lexicon.token(symbols, _ => false)
    62     val toks = new mutable.ListBuffer[Outer_Lex.Token]
    63 
    64     def scan_to_begin(in: Reader[Char])
    65     {
    66       token(in) match {
    67         case lexicon.Success(tok, rest) =>
    68           toks += tok
    69           if (!(tok.kind == Outer_Lex.Token_Kind.KEYWORD && tok.content == BEGIN))
    70             scan_to_begin(rest)
    71         case _ =>
    72       }
    73     }
    74     val reader = Scan.byte_reader(file)
    75     try { scan_to_begin(reader) } finally { reader.close }
    76 
    77     parse(commit(header), Outer_Lex.reader(toks.toList)) match {
    78       case Success(result, _) => result
    79       case bad => error(bad.toString)
    80     }
    81   }
    82 }