parser3.scala
changeset 64 2d625418c011
child 76 373cf55a3ca5
equal deleted inserted replaced
63:dff4b062a8a9 64:2d625418c011
       
     1 
       
     2 // parser combinators with input type I and return type T
       
     3 
       
     4 abstract class Parser[I <% Seq[_], T] {
       
     5   def parse(ts: I): Set[(T, I)]
       
     6 
       
     7   def parse_all(ts: I) : Set[T] =
       
     8     for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
       
     9 
       
    10   def || (right : => Parser[I, T]) : Parser[I, T] = new AltParser(this, right)
       
    11   def ==>[S] (f: => T => S) : Parser [I, S] = new FunParser(this, f)
       
    12   def ~[S] (right : => Parser[I, S]) : Parser[I, (T, S)] = new SeqParser(this, right)
       
    13   def ~>[S] (right : => Parser[I, S]) : Parser[I, S] = this ~ right ==> (_._2)
       
    14   def <~[S] (right : => Parser[I, S]) : Parser[I, T] = this ~ right ==> (_._1)
       
    15 }
       
    16 
       
    17 class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] {
       
    18   def parse(sb: I) = 
       
    19     for ((head1, tail1) <- p.parse(sb); 
       
    20          (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2)
       
    21 }
       
    22 
       
    23 class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] {
       
    24   def parse(sb: I) = p.parse(sb) ++ q.parse(sb)   
       
    25 }
       
    26 
       
    27 class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] {
       
    28   def parse(sb: I) = 
       
    29     for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
       
    30 }
       
    31 
       
    32