scala/parser3.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Sat, 15 Jun 2013 09:11:11 -0400
changeset 92 e85600529ca5
parent 85 parser3.scala@1a4065f965fb
permissions -rw-r--r--
moved scala files

package object parser {

// parser combinators 
// with input type I and return type T
//
// needs to be compiled with scalac parser3.scala

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 parse_single(ts: I) : T = parse_all(ts).toList match {
    case t::Nil => t
    case _ => { println ("Parse Error") ; sys.exit(-1) }
  }
    
  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)
}

}