1 /* Title: Pure/General/scan.scala
4 Efficient scanning of keywords and tokens.
10 import scala.collection.{IndexedSeq, TraversableOnce}
11 import scala.collection.immutable.PagedSeq
12 import scala.util.parsing.input.{OffsetPosition, Position => InputPosition, Reader}
13 import scala.util.parsing.combinator.RegexParsers
15 import java.io.{File, BufferedInputStream, FileInputStream}
20 /** context of partial scans **/
22 sealed abstract class Context
23 case object Finished extends Context
24 case class Quoted(quote: String) extends Context
25 case object Verbatim extends Context
26 case class Comment(depth: Int) extends Context
30 /** Lexicon -- position tree **/
36 sealed case class Tree(val branches: Map[Char, (String, Tree)])
37 private val empty_tree = Tree(Map())
39 val empty: Lexicon = new Lexicon(empty_tree)
40 def apply(elems: String*): Lexicon = empty ++ elems
43 final class Lexicon private(main_tree: Lexicon.Tree) extends RegexParsers
48 /* auxiliary operations */
50 private def content(tree: Tree, result: List[String]): List[String] =
51 (result /: tree.branches.toList) ((res, entry) =>
52 entry match { case (_, (s, tr)) =>
53 if (s.isEmpty) content(tr, res) else content(tr, s :: res) })
55 private def lookup(str: CharSequence): Option[(Boolean, Tree)] =
58 def look(tree: Tree, tip: Boolean, i: Int): Option[(Boolean, Tree)] =
61 tree.branches.get(str.charAt(i)) match {
62 case Some((s, tr)) => look(tr, !s.isEmpty, i + 1)
65 } else Some(tip, tree)
67 look(main_tree, false, 0)
70 def completions(str: CharSequence): List[String] =
72 case Some((true, tree)) => content(tree, List(str.toString))
73 case Some((false, tree)) => content(tree, Nil)
78 /* pseudo Set methods */
80 def iterator: Iterator[String] = content(main_tree, Nil).sorted.iterator
82 override def toString: String = iterator.mkString("Lexicon(", ", ", ")")
84 def empty: Lexicon = Lexicon.empty
85 def isEmpty: Boolean = main_tree.branches.isEmpty
87 def contains(elem: String): Boolean =
89 case Some((tip, _)) => tip
96 def + (elem: String): Lexicon =
97 if (contains(elem)) this
100 def extend(tree: Tree, i: Int): Tree =
102 val c = elem.charAt(i)
103 val end = (i + 1 == len)
104 tree.branches.get(c) match {
105 case Some((s, tr)) =>
107 (c -> (if (end) elem else s, extend(tr, i + 1))))
110 (c -> (if (end) elem else "", extend(Lexicon.empty_tree, i + 1))))
114 new Lexicon(extend(main_tree, 0))
117 def ++ (elems: TraversableOnce[String]): Lexicon = (this /: elems)(_ + _)
121 /** RegexParsers methods **/
123 override val whiteSpace = "".r
126 /* optional termination */
128 def opt_term[T](p: => Parser[T]): Parser[Option[T]] =
129 p ^^ (x => Some(x)) | """\z""".r ^^ (_ => None)
132 /* keywords from lexicon */
134 def keyword: Parser[String] = new Parser[String]
136 def apply(in: Input) =
138 val source = in.source
139 val offset = in.offset
140 val len = source.length - offset
142 def scan(tree: Tree, result: String, i: Int): String =
145 tree.branches.get(source.charAt(offset + i)) match {
146 case Some((s, tr)) => scan(tr, if (s.isEmpty) result else s, i + 1)
152 val result = scan(main_tree, "", 0)
153 if (result.isEmpty) Failure("keyword expected", in)
154 else Success(result, in.drop(result.length))
161 def symbol_range(pred: Symbol.Symbol => Boolean, min_count: Int, max_count: Int): Parser[String] =
164 def apply(in: Input) =
166 val start = in.offset
167 val end = in.source.length
168 val matcher = new Symbol.Matcher(in.source)
174 if (i < end && count < max_count) {
175 val n = matcher(i, end)
176 val sym = in.source.subSequence(i, i + n).toString
177 if (pred(sym)) { i += n; count += 1 }
182 if (count < min_count) Failure("bad input", in)
183 else Success(in.source.subSequence(start, i).toString, in.drop(i - start))
185 }.named("symbol_range")
187 def one(pred: Symbol.Symbol => Boolean): Parser[String] =
188 symbol_range(pred, 1, 1)
190 def many(pred: Symbol.Symbol => Boolean): Parser[String] =
191 symbol_range(pred, 0, Integer.MAX_VALUE)
193 def many1(pred: Symbol.Symbol => Boolean): Parser[String] =
194 symbol_range(pred, 1, Integer.MAX_VALUE)
199 private def quoted_body(quote: Symbol.Symbol): Parser[String] =
201 rep(many1(sym => sym != quote && sym != "\\") | "\\" + quote | "\\\\" |
202 (("""\\\d\d\d""".r) ^? { case x if x.substring(1, 4).toInt <= 255 => x })) ^^ (_.mkString)
205 private def quoted(quote: Symbol.Symbol): Parser[String] =
207 quote ~ quoted_body(quote) ~ quote ^^ { case x ~ y ~ z => x + y + z }
210 def quoted_content(quote: Symbol.Symbol, source: String): String =
212 require(parseAll(quoted(quote), source).successful)
213 val body = source.substring(1, source.length - 1)
214 if (body.exists(_ == '\\')) {
216 rep(many1(sym => sym != quote && sym != "\\") |
217 "\\" ~> (quote | "\\" | """\d\d\d""".r ^^ { case x => x.toInt.toChar.toString }))
218 parseAll(content ^^ (_.mkString), body).get
223 def quoted_context(quote: Symbol.Symbol, ctxt: Context): Parser[(String, Context)] =
227 quote ~ quoted_body(quote) ~ opt_term(quote) ^^
228 { case x ~ y ~ Some(z) => (x + y + z, Finished)
229 case x ~ y ~ None => (x + y, Quoted(quote)) }
230 case Quoted(q) if q == quote =>
231 quoted_body(quote) ~ opt_term(quote) ^^
232 { case x ~ Some(y) => (x + y, Finished)
233 case x ~ None => (x, ctxt) }
234 case _ => failure("")
236 }.named("quoted_context")
241 private def verbatim_body: Parser[String] =
242 rep(many1(sym => sym != "*") | """\*(?!\})""".r) ^^ (_.mkString)
244 private def verbatim: Parser[String] =
246 "{*" ~ verbatim_body ~ "*}" ^^ { case x ~ y ~ z => x + y + z }
249 def verbatim_content(source: String): String =
251 require(parseAll(verbatim, source).successful)
252 source.substring(2, source.length - 2)
255 def verbatim_context(ctxt: Context): Parser[(String, Context)] =
259 "{*" ~ verbatim_body ~ opt_term("*}") ^^
260 { case x ~ y ~ Some(z) => (x + y + z, Finished)
261 case x ~ y ~ None => (x + y, Verbatim) }
263 verbatim_body ~ opt_term("*}") ^^
264 { case x ~ Some(y) => (x + y, Finished)
265 case x ~ None => (x, Verbatim) }
266 case _ => failure("")
268 }.named("verbatim_context")
271 /* nested comments */
273 private def comment_depth(depth: Int): Parser[(String, Int)] = new Parser[(String, Int)]
278 rep1(many1(sym => sym != "*" && sym != "(") | """\*(?!\))|\((?!\*)""".r)
280 def apply(in: Input) =
283 def try_parse[A](p: Parser[A]): Boolean =
285 parse(p ^^^ (), rest) match {
286 case Success(_, next) => { rest = next; true }
293 if (try_parse("(*")) d += 1
294 else if (d > 0 && try_parse("*)")) d -= 1
295 else if (d == 0 || !try_parse(comment_text)) finished = true
297 if (in.offset < rest.offset)
298 Success((in.source.subSequence(in.offset, rest.offset).toString, d), rest)
299 else Failure("comment expected", in)
301 }.named("comment_depth")
303 def comment: Parser[String] =
304 comment_depth(0) ^? { case (x, d) if d == 0 => x }
306 def comment_context(ctxt: Context): Parser[(String, Context)] =
315 comment_depth(depth) ^^
316 { case (x, 0) => (x, Finished)
317 case (x, d) => (x, Comment(d)) }
321 def comment_content(source: String): String =
323 require(parseAll(comment, source).successful)
324 source.substring(2, source.length - 2)
328 /* outer syntax tokens */
330 private def delimited_token: Parser[Token] =
332 val string = quoted("\"") ^^ (x => Token(Token.Kind.STRING, x))
333 val alt_string = quoted("`") ^^ (x => Token(Token.Kind.ALT_STRING, x))
334 val verb = verbatim ^^ (x => Token(Token.Kind.VERBATIM, x))
335 val cmt = comment ^^ (x => Token(Token.Kind.COMMENT, x))
337 string | (alt_string | (verb | cmt))
340 private def other_token(is_command: String => Boolean)
343 val id = one(Symbol.is_letter) ~ many(Symbol.is_letdig) ^^ { case x ~ y => x + y }
344 val nat = many1(Symbol.is_digit)
345 val natdot = nat ~ "." ~ nat ^^ { case x ~ y ~ z => x + y + z }
346 val id_nat = id ~ opt("." ~ nat) ^^ { case x ~ Some(y ~ z) => x + y + z case x ~ None => x }
348 val ident = id ~ rep("." ~> id) ^^
349 { case x ~ Nil => Token(Token.Kind.IDENT, x)
350 case x ~ ys => Token(Token.Kind.LONG_IDENT, (x :: ys).mkString(".")) }
352 val var_ = "?" ~ id_nat ^^ { case x ~ y => Token(Token.Kind.VAR, x + y) }
353 val type_ident = "'" ~ id ^^ { case x ~ y => Token(Token.Kind.TYPE_IDENT, x + y) }
354 val type_var = "?'" ~ id_nat ^^ { case x ~ y => Token(Token.Kind.TYPE_VAR, x + y) }
355 val nat_ = nat ^^ (x => Token(Token.Kind.NAT, x))
357 ("-" ~ natdot ^^ { case x ~ y => x + y } | natdot) ^^ (x => Token(Token.Kind.FLOAT, x))
360 (many1(Symbol.is_symbolic_char) | one(sym => Symbol.is_symbolic(sym))) ^^
361 (x => Token(Token.Kind.SYM_IDENT, x))
363 val space = many1(Symbol.is_blank) ^^ (x => Token(Token.Kind.SPACE, x))
366 val junk = many(sym => !(Symbol.is_blank(sym)))
367 val junk1 = many1(sym => !(Symbol.is_blank(sym)))
370 ("\"" | "`" | "{*" | "(*") ~ junk ^^ { case x ~ y => Token(Token.Kind.UNPARSED, x + y) }
371 val bad = junk1 ^^ (x => Token(Token.Kind.UNPARSED, x))
373 val command_keyword =
374 keyword ^^ (x => Token(if (is_command(x)) Token.Kind.COMMAND else Token.Kind.KEYWORD, x))
376 space | (bad_delimiter |
377 (((ident | (var_ | (type_ident | (type_var | (float | (nat_ | sym_ident)))))) |||
378 command_keyword) | bad))
381 def token(is_command: String => Boolean): Parser[Token] =
382 delimited_token | other_token(is_command)
384 def token_context(is_command: String => Boolean, ctxt: Context): Parser[(Token, Context)] =
387 quoted_context("\"", ctxt) ^^ { case (x, c) => (Token(Token.Kind.STRING, x), c) }
389 quoted_context("`", ctxt) ^^ { case (x, c) => (Token(Token.Kind.ALT_STRING, x), c) }
390 val verb = verbatim_context(ctxt) ^^ { case (x, c) => (Token(Token.Kind.VERBATIM, x), c) }
391 val cmt = comment_context(ctxt) ^^ { case (x, c) => (Token(Token.Kind.COMMENT, x), c) }
392 val other = other_token(is_command) ^^ { case x => (x, Finished) }
394 string | (alt_string | (verb | (cmt | other)))
400 /** read file without decoding -- enables efficient length operation **/
402 private class Restricted_Seq(seq: IndexedSeq[Char], start: Int, end: Int)
405 def charAt(i: Int): Char =
406 if (0 <= i && i < length) seq(start + i)
407 else throw new IndexOutOfBoundsException
409 def length: Int = end - start // avoid potentially expensive seq.length
411 def subSequence(i: Int, j: Int): CharSequence =
412 if (0 <= i && i <= j && j <= length) new Restricted_Seq(seq, start + i, start + j)
413 else throw new IndexOutOfBoundsException
415 override def toString: String =
417 val buf = new StringBuilder(length)
418 for (offset <- start until end) buf.append(seq(offset))
423 abstract class Byte_Reader extends Reader[Char] { def close: Unit }
425 def byte_reader(file: File): Byte_Reader =
427 val stream = new BufferedInputStream(new FileInputStream(file))
428 val seq = new PagedSeq(
429 (buf: Array[Char], offset: Int, length: Int) =>
434 while (!eof && i < length) {
436 if (c == -1) eof = true
437 else { buf(offset + i) = c.toChar; i += 1 }
441 val restricted_seq = new Restricted_Seq(seq, 0, file.length.toInt)
443 class Paged_Reader(override val offset: Int) extends Byte_Reader
445 override lazy val source: CharSequence = restricted_seq
446 def first: Char = if (seq.isDefinedAt(offset)) seq(offset) else '\032'
447 def rest: Paged_Reader = if (seq.isDefinedAt(offset)) new Paged_Reader(offset + 1) else this
448 def pos: InputPosition = new OffsetPosition(source, offset)
449 def atEnd: Boolean = !seq.isDefinedAt(offset)
450 override def drop(n: Int): Paged_Reader = new Paged_Reader(offset + n)
451 def close { stream.close }