progs/parser3.scala
author Christian Urban <urbanc@in.tum.de>
Wed, 28 Jun 2017 12:46:23 +0100
changeset 497 c498cb53a9a8
parent 93 4794759139ea
permissions -rw-r--r--
updated

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)
}

}