parser3.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Wed, 21 Nov 2012 09:04:11 +0000
changeset 70 e6868bd2942b
parent 64 2d625418c011
child 76 373cf55a3ca5
permissions -rw-r--r--
tuned


// parser combinators with input type I and return type T

abstract class Parser[I <% Seq[_], T] {
  def parse(ts: I): Set[(T, I)]

  def parse_all(ts: I) : Set[T] =
    for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head

  def || (right : => Parser[I, T]) : Parser[I, T] = new AltParser(this, right)
  def ==>[S] (f: => T => S) : Parser [I, S] = new FunParser(this, f)
  def ~[S] (right : => Parser[I, S]) : Parser[I, (T, S)] = new SeqParser(this, right)
  def ~>[S] (right : => Parser[I, S]) : Parser[I, S] = this ~ right ==> (_._2)
  def <~[S] (right : => Parser[I, S]) : Parser[I, T] = this ~ right ==> (_._1)
}

class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] {
  def parse(sb: I) = 
    for ((head1, tail1) <- p.parse(sb); 
         (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2)
}

class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] {
  def parse(sb: I) = p.parse(sb) ++ q.parse(sb)   
}

class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] {
  def parse(sb: I) = 
    for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
}