progs/parser-combinators/comb1.sc
changeset 732 c7bdd7eac4cb
child 742 b5b5583a3a08
equal deleted inserted replaced
731:90946a2eb48a 732:c7bdd7eac4cb
       
     1 // Parser Combinators: Simple Version
       
     2 //====================================
       
     3 
       
     4 /* 
       
     5   Note, in the lectures I did not show the implicit type constraint
       
     6   I : IsSeq, which means that the input type 'I' needs to be
       
     7   a sequence. 
       
     8 */
       
     9 
       
    10 type IsSeq[A] = A => Seq[_]
       
    11 
       
    12 abstract class Parser[I : IsSeq, T]{
       
    13   def parse(in: I): Set[(T, I)]
       
    14 
       
    15   def parse_all(in: I) : Set[T] =
       
    16     for ((hd, tl) <- parse(in); 
       
    17         if tl.isEmpty) yield hd
       
    18 }
       
    19 
       
    20 // parser combinators
       
    21 
       
    22 // sequence parser
       
    23 class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], 
       
    24                                  q: => Parser[I, S]) extends Parser[I, (T, S)] {
       
    25   def parse(in: I) = 
       
    26     for ((hd1, tl1) <- p.parse(in); 
       
    27          (hd2, tl2) <- q.parse(tl1)) yield ((hd1, hd2), tl2)
       
    28 }
       
    29 
       
    30 // alternative parser
       
    31 class AltParser[I : IsSeq, T](p: => Parser[I, T], 
       
    32                               q: => Parser[I, T]) extends Parser[I, T] {
       
    33   def parse(in: I) = p.parse(in) ++ q.parse(in)   
       
    34 }
       
    35 
       
    36 // parser map
       
    37 class MapParser[I : IsSeq, T, S](p: => Parser[I, T], 
       
    38                                  f: T => S) extends Parser[I, S] {
       
    39   def parse(in: I) = for ((hd, tl) <- p.parse(in)) yield (f(hd), tl)
       
    40 }
       
    41 
       
    42 // an example of an atomic parser for characters
       
    43 case class CharParser(c: Char) extends Parser[String, Char] {
       
    44   def parse(in: String) = 
       
    45     if (in != "" && in.head == c) Set((c, in.tail)) else Set()
       
    46 }
       
    47 
       
    48 // an atomic parser for parsing strings according to a regex
       
    49 import scala.util.matching.Regex
       
    50 
       
    51 case class RegexParser(reg: Regex) extends Parser[String, String] {
       
    52   def parse(in: String) = reg.findPrefixMatchOf(in) match {
       
    53     case None => Set()
       
    54     case Some(m) => Set((m.matched, m.after.toString))  
       
    55   }
       
    56 }
       
    57 
       
    58 // atomic parsers for numbers and "verbatim" strings 
       
    59 val NumParser = RegexParser("[0-9]+".r)
       
    60 def StrParser(s: String) = RegexParser(Regex.quote(s).r)
       
    61 
       
    62 // NumParserInt transforms a "string integer" into a propper Int
       
    63 // (needs "new" because MapParser is not a case class)
       
    64 
       
    65 val NumParserInt = new MapParser(NumParser, (s: String) => s.toInt)
       
    66 
       
    67 
       
    68 // the following string interpolation allows us to write 
       
    69 // StrParser(_some_string_) more conveniently as 
       
    70 //
       
    71 // p"<_some_string_>" 
       
    72 
       
    73 implicit def parser_interpolation(sc: StringContext) = new {
       
    74   def p(args: Any*) = StrParser(sc.s(args:_*))
       
    75 }
       
    76 
       
    77 // more convenient syntax for parser combinators
       
    78 implicit def ParserOps[I : IsSeq, T](p: Parser[I, T]) = new {
       
    79   def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q)
       
    80   def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
       
    81   def map[S](f: => T => S) = new MapParser[I, T, S](p, f)
       
    82 }
       
    83 
       
    84 // these implicits allow us to use an infix notation for
       
    85 // sequences and alternatives; we also can write the usual
       
    86 // map for a MapParser
       
    87 
       
    88 
       
    89 // with this NumParserInt can now be written more conveniently
       
    90 // as:
       
    91 
       
    92 val NumParserInt2 = NumParser.map(s => s.toInt)
       
    93 
       
    94 
       
    95 // A parser for palindromes (just returns them as string)
       
    96 lazy val Pal : Parser[String, String] = {
       
    97   (p"a" ~ Pal ~ p"a").map{ case ((x, y), z) => s"$x$y$z" } || 
       
    98   (p"b" ~ Pal ~ p"b").map{ case ((x, y), z) => s"$x$y$z" } || 
       
    99   p"a" || p"b" || p""
       
   100 }  
       
   101 
       
   102 // examples
       
   103 Pal.parse_all("abaaaba")
       
   104 Pal.parse("abaaaba")
       
   105 
       
   106 println("Palindrome: " + Pal.parse_all("abaaaba"))
       
   107 
       
   108 // A parser for wellnested parentheses (transforms '(' -> '{' , ')' -> '}' )
       
   109 lazy val P : Parser[String, String] = 
       
   110   (p"(" ~ P ~ p")" ~ P).map{ case (((_, x), _), y) => "{" + x + "}" + y } || p""
       
   111 
       
   112 println(P.parse_all("(((()()))())"))
       
   113 println(P.parse_all("(((()()))()))"))
       
   114 println(P.parse_all(")("))
       
   115 println(P.parse_all("()"))
       
   116 
       
   117 // A parser for arithmetic expressions (Terms and Factors)
       
   118 
       
   119 lazy val E: Parser[String, Int] = 
       
   120   (T ~ p"+" ~ E).map{ case ((x, _), z) => x + z } ||
       
   121   (T ~ p"-" ~ E).map{ case ((x, _), z) => x - z } || T 
       
   122 lazy val T: Parser[String, Int] = 
       
   123   (F ~ p"*" ~ T).map{ case ((x, _), z) => x * z } || F
       
   124 lazy val F: Parser[String, Int] = 
       
   125   (p"(" ~ E ~ p")").map{ case ((_, y), _) => y } || NumParserInt
       
   126 
       
   127 /* same parser but producing a string
       
   128 lazy val E: Parser[String, String] = 
       
   129   (T ~ "+" ~ E).map{ case x ~ y ~ z => "(" + x + ")+(" + z + ")"} || T 
       
   130 lazy val T: Parser[String, String] = 
       
   131   (F ~ "*" ~ T).map{ case x ~ y ~ z => "(" + x + ")*("+ z + ")"} || F
       
   132 lazy val F: Parser[String, String] = 
       
   133   ("(" ~ E ~ ")").map{ case x ~ y ~ z => y } || NumParser
       
   134 */
       
   135 
       
   136 println(E.parse_all("1+3+4"))
       
   137 println(E.parse("1+3+4"))
       
   138 println(E.parse_all("4*2+3"))
       
   139 println(E.parse_all("4*(2+3)"))
       
   140 println(E.parse_all("(4)*((2+3))"))
       
   141 println(E.parse_all("4/2+3"))
       
   142 println(E.parse("1 + 2 * 3"))
       
   143 println(E.parse_all("(1+2)+3"))
       
   144 println(E.parse_all("1+2+3"))  
       
   145 
       
   146 
       
   147 // with parser combinators (and other parsing algorithms)
       
   148 // no left-recursion is allowed, otherwise the will loop
       
   149 
       
   150 lazy val EL: Parser[String, Int] = 
       
   151   ((EL ~ p"+" ~ EL).map{ case ((x, y), z) => x + z} || 
       
   152    (EL ~ p"*" ~ EL).map{ case ((x, y), z) => x * z} ||
       
   153    (p"(" ~ EL ~ p")").map{ case ((x, y), z) => y} ||
       
   154    NumParserInt)
       
   155 
       
   156 // this will run forever:
       
   157 //println(EL.parse_all("1+2+3"))
       
   158 
       
   159 
       
   160 // non-ambiguous vs ambiguous grammars
       
   161 
       
   162 // ambiguous
       
   163 lazy val S : Parser[String, String] =
       
   164   (p"1" ~ S ~ S).map{ case ((x, y), z) => x + y + z } || p""
       
   165 
       
   166 println(time(S.parse("1" * 10)))
       
   167 println(time(S.parse_all("1" * 10)))
       
   168 
       
   169 // non-ambiguous
       
   170 lazy val U : Parser[String, String] =
       
   171   (p"1" ~ U).map{ case (x, y) => x + y } || p""
       
   172 
       
   173 println(time(U.parse("1" * 10)))
       
   174 println(time(U.parse_all("1" * 10)))
       
   175 println(U.parse("1" * 25))
       
   176 
       
   177 U.parse("11")
       
   178 U.parse("11111")
       
   179 U.parse("11011")
       
   180 
       
   181 U.parse_all("1" * 100)
       
   182 U.parse_all("1" * 100 + "0")
       
   183 
       
   184 // you can see the difference in second example
       
   185 //S.parse_all("1" * 100)         // succeeds
       
   186 //S.parse_all("1" * 100 + "0")   // fails
       
   187 
       
   188 
       
   189 // A variant which counts how many 1s are parsed
       
   190 lazy val UCount : Parser[String, Int] =
       
   191   (p"1" ~ UCount).map[Int]{ case (_, y) => y + 1 } || p"".map[Int]{ _ => 0 }
       
   192 
       
   193 println(UCount.parse("11111"))
       
   194 println(UCount.parse_all("11111"))
       
   195 
       
   196 // Two single character parsers
       
   197 lazy val One : Parser[String, String] = p"a"
       
   198 lazy val Two : Parser[String, String] = p"b"
       
   199 
       
   200 One.parse("a")
       
   201 One.parse("aaa")
       
   202 
       
   203 // note how the pairs nest to the left with sequence parsers
       
   204 (One ~ One).parse("aaa")
       
   205 (One ~ One ~ One).parse("aaa")
       
   206 (One ~ One ~ One ~ One).parse("aaaa")
       
   207 
       
   208 (One || Two).parse("aaa")
       
   209 
       
   210 
       
   211 
       
   212 // a problem with the arithmetic expression parser: it 
       
   213 // gets vert slow with deeply nested parentheses
       
   214 
       
   215 println("Runtime problem")
       
   216 println(E.parse("1"))
       
   217 println(E.parse("(1)"))
       
   218 println(E.parse("((1))"))
       
   219 //println(E.parse("(((1)))"))
       
   220 //println(E.parse("((((1))))"))
       
   221 //println(E.parse("((((((1))))))"))
       
   222 //println(E.parse("(((((((1)))))))"))
       
   223 //println(E.parse("((((((((1)))))))"))