|      1 package object parser { |         | 
|      2  |         | 
|      3 // parser combinators  |         | 
|      4 // with input type I and return type T |         | 
|      5 // |         | 
|      6 // needs to be compiled with scalac parser3.scala |         | 
|      7  |         | 
|      8 abstract class Parser[I <% Seq[_], T] { |         | 
|      9   def parse(ts: I): Set[(T, I)] |         | 
|     10  |         | 
|     11   def parse_all(ts: I) : Set[T] = |         | 
|     12     for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head |         | 
|     13  |         | 
|     14   def parse_single(ts: I) : T = parse_all(ts).toList match { |         | 
|     15     case t::Nil => t |         | 
|     16     case _ => { println ("Parse Error") ; sys.exit(-1) } |         | 
|     17   } |         | 
|     18      |         | 
|     19   def || (right : => Parser[I, T]) : Parser[I, T] = new AltParser(this, right) |         | 
|     20   def ==>[S] (f: => T => S) : Parser [I, S] = new FunParser(this, f) |         | 
|     21   def ~[S] (right : => Parser[I, S]) : Parser[I, (T, S)] = new SeqParser(this, right) |         | 
|     22   def ~>[S] (right : => Parser[I, S]) : Parser[I, S] = this ~ right ==> (_._2) |         | 
|     23   def <~[S] (right : => Parser[I, S]) : Parser[I, T] = this ~ right ==> (_._1) |         | 
|     24 } |         | 
|     25  |         | 
|     26 class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] { |         | 
|     27   def parse(sb: I) =  |         | 
|     28     for ((head1, tail1) <- p.parse(sb);  |         | 
|     29          (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2) |         | 
|     30 } |         | 
|     31  |         | 
|     32 class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] { |         | 
|     33   def parse(sb: I) = p.parse(sb) ++ q.parse(sb)    |         | 
|     34 } |         | 
|     35  |         | 
|     36 class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] { |         | 
|     37   def parse(sb: I) =  |         | 
|     38     for ((head, tail) <- p.parse(sb)) yield (f(head), tail) |         | 
|     39 } |         | 
|     40  |         | 
|     41 } |         |