progs/scala/re-annotated2.sc
changeset 360 e752d84225ec
child 361 8bb064045b4e
equal deleted inserted replaced
359:fedc16924b76 360:e752d84225ec
       
     1 // uses bitcode sequences and annotated regular 
       
     2 // expressions
       
     3 //
       
     4 // for basic regular expressions and RECD
       
     5 //
       
     6 // the main difference is that it includes
       
     7 // also character sets
       
     8 //
       
     9 // uses a non-standard extraction method for generating
       
    10 // tokens (this is tail-recursive) 
       
    11 //
       
    12 // can match 200 copies of the fib-program (size 35000)
       
    13 // in about 20 secs
       
    14 
       
    15 
       
    16 import scala.language.implicitConversions    
       
    17 import scala.language.reflectiveCalls
       
    18 import scala.annotation.tailrec   
       
    19 
       
    20 // standard regular expressions
       
    21 abstract class Rexp 
       
    22 case object ZERO extends Rexp
       
    23 case object ONE extends Rexp
       
    24 case class ALT(r1: Rexp, r2: Rexp) extends Rexp 
       
    25 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
       
    26 case class STAR(r: Rexp) extends Rexp 
       
    27 case class RECD(x: String, r: Rexp) extends Rexp
       
    28 case class CHARSET(f: Char => Boolean) extends Rexp
       
    29 
       
    30 //abbreviation for single characters
       
    31 def CHAR(c: Char) = CHARSET(_ == c)
       
    32 
       
    33 // bit-codes with additional information about 
       
    34 // matched characters
       
    35 abstract class Bit
       
    36 case object Z extends Bit
       
    37 case object S extends Bit
       
    38 case class C(c: Char) extends Bit
       
    39 
       
    40 type Bits = List[Bit]
       
    41 
       
    42 // annotated regular expressions
       
    43 abstract class ARexp 
       
    44 case object AZERO extends ARexp
       
    45 case class AONE(bs: Bits) extends ARexp
       
    46 case class AALTS(bs: Bits, rs: List[ARexp]) extends ARexp 
       
    47 case class ASEQ(bs: Bits, r1: ARexp, r2: ARexp) extends ARexp 
       
    48 case class ASTAR(bs: Bits, r: ARexp) extends ARexp 
       
    49 case class ACHARSET(bs: Bits, f: Char => Boolean) extends ARexp
       
    50 
       
    51 // an abbreviation for binary alternatives
       
    52 def AALT(bs: Bits, r1: ARexp, r2: ARexp) = AALTS(bs, List(r1, r2))
       
    53 
       
    54 abstract class Val
       
    55 case object Empty extends Val
       
    56 case class Chr(c: Char) extends Val
       
    57 case class Sequ(v1: Val, v2: Val) extends Val
       
    58 case class Left(v: Val) extends Val
       
    59 case class Right(v: Val) extends Val
       
    60 case class Stars(vs: List[Val]) extends Val
       
    61 case class Recd(x: String, v: Val) extends Val
       
    62    
       
    63 // some convenience for typing in regular expressions
       
    64 def charlist2rexp(s: List[Char]): Rexp = s match {
       
    65   case Nil => ONE
       
    66   case c::Nil => CHAR(c)
       
    67   case c::s => SEQ(CHAR(c), charlist2rexp(s))
       
    68 }
       
    69 implicit def string2rexp(s: String) : Rexp = charlist2rexp(s.toList)
       
    70 
       
    71 implicit def RexpOps(r: Rexp) = new {
       
    72   def | (s: Rexp) = ALT(r, s)
       
    73   def % = STAR(r)
       
    74   def ~ (s: Rexp) = SEQ(r, s)
       
    75 }
       
    76 
       
    77 implicit def stringOps(s: String) = new {
       
    78   def | (r: Rexp) = ALT(s, r)
       
    79   def | (r: String) = ALT(s, r)
       
    80   def % = STAR(s)
       
    81   def ~ (r: Rexp) = SEQ(s, r)
       
    82   def ~ (r: String) = SEQ(s, r)
       
    83   def $ (r: Rexp) = RECD(s, r)
       
    84 }
       
    85 
       
    86 def size(r: Rexp) : Int = r match {
       
    87   case ZERO => 1
       
    88   case ONE => 1
       
    89   case ALT(r1, r2) => 1 + size(r1) + size(r2)
       
    90   case SEQ(r1, r2) => 1 + size(r1) + size(r2)
       
    91   case STAR(r) => 1 + size(r)
       
    92   case RECD(_, r) => 1 + size(r)
       
    93   case CHARSET(_) => 1
       
    94 }
       
    95 
       
    96 
       
    97 
       
    98 // Bitcoded + Annotation
       
    99 //=======================
       
   100 
       
   101 //erase function: extracts the Rexp from ARexp
       
   102 def erase(r:ARexp): Rexp = r match{
       
   103   case AZERO => ZERO
       
   104   case AONE(_) => ONE
       
   105   case AALTS(bs, Nil) => ZERO
       
   106   case AALTS(bs, r::Nil) => erase(r)
       
   107   case AALTS(bs, r::rs) => ALT(erase(r), erase(AALTS(bs, rs)))
       
   108   case ASEQ(bs, r1, r2) => SEQ (erase(r1), erase(r2))
       
   109   case ASTAR(cs, r)=> STAR(erase(r))
       
   110   case ACHARSET(bs, f) => CHARSET(f)
       
   111 }
       
   112 
       
   113 def fuse(bs: Bits, r: ARexp) : ARexp = r match {
       
   114   case AZERO => AZERO
       
   115   case AONE(cs) => AONE(bs ++ cs)
       
   116   case AALTS(cs, rs) => AALTS(bs ++ cs, rs)
       
   117   case ASEQ(cs, r1, r2) => ASEQ(bs ++ cs, r1, r2)
       
   118   case ASTAR(cs, r) => ASTAR(bs ++ cs, r)
       
   119   case ACHARSET(cs, f) => ACHARSET(bs ++ cs, f)
       
   120 }
       
   121 
       
   122 def internalise(r: Rexp) : ARexp = r match {
       
   123   case ZERO => AZERO
       
   124   case ONE => AONE(Nil)
       
   125   case ALT(r1, r2) => 
       
   126     AALT(Nil, fuse(List(Z), internalise(r1)), fuse(List(S), internalise(r2)))
       
   127   case SEQ(r1, r2) => ASEQ(Nil, internalise(r1), internalise(r2))
       
   128   case STAR(r) => ASTAR(Nil, internalise(r))
       
   129   case RECD(_, r) => internalise(r)
       
   130   case CHARSET(f) => ACHARSET(Nil, f)
       
   131 }
       
   132 
       
   133 // example
       
   134 // internalise(("a" | "ab") ~ ("b" | ""))
       
   135 
       
   136 
       
   137 // decoding of a value from a bitsequence
       
   138 // (this is not tail-recursive and therefore a potential bottleneck)
       
   139 def vdecode_aux(r: Rexp, bs: Bits) : (Val, Bits) = (r, bs) match {
       
   140   case (ONE, bs) => (Empty, bs)
       
   141   case (ALT(r1, r2), Z::bs) => {
       
   142     val (v, bs1) = vdecode_aux(r1, bs)
       
   143     (Left(v), bs1)
       
   144   }
       
   145   case (ALT(r1, r2), S::bs) => {
       
   146     val (v, bs1) = vdecode_aux(r2, bs)
       
   147     (Right(v), bs1)
       
   148   }
       
   149   case (SEQ(r1, r2), bs) => {
       
   150     val (v1, bs1) = vdecode_aux(r1, bs)
       
   151     val (v2, bs2) = vdecode_aux(r2, bs1)
       
   152     (Sequ(v1, v2), bs2)
       
   153   }
       
   154   case (STAR(r1), Z::bs) => {
       
   155     val (v, bs1) = vdecode_aux(r1, bs)
       
   156     val (Stars(vs), bs2) = vdecode_aux(STAR(r1), bs1)
       
   157     (Stars(v::vs), bs2)
       
   158   }
       
   159   case (STAR(_), S::bs) => (Stars(Nil), bs)
       
   160   case (RECD(s, r1), bs) => 
       
   161     val (v, bs1) = vdecode_aux(r1, bs)
       
   162     (Recd(s, v), bs1)
       
   163   case (CHARSET(_), C(c)::bs) => (Chr(c), bs)
       
   164 }
       
   165 
       
   166 def vdecode(r: Rexp, bs: Bits) = vdecode_aux(r, bs) match {
       
   167   case (v, Nil) => v
       
   168   case _ => throw new Exception("Not decodable")
       
   169 }
       
   170 
       
   171 // decoding of sequence of string tokens from a bitsequence
       
   172 // tail-recursive version using an accumulator (alternative for 
       
   173 // vdecode)
       
   174 @tailrec
       
   175 def sdecode_aux(rs: List[Rexp], bs: Bits, acc: List[String]) : List[String] = (rs, bs) match {
       
   176   case (Nil, _) => acc
       
   177   case (_, Nil) => acc
       
   178   case (ONE::rest, bs) => sdecode_aux(rest, bs, acc)
       
   179   case (ALT(r1, r2)::rest, Z::bs) => sdecode_aux(r1::rest, bs, acc)
       
   180   case (ALT(r1, r2)::rest, S::bs) => sdecode_aux(r2::rest, bs, acc)
       
   181   case (SEQ(r1, r2)::rest, bs) => sdecode_aux(r1::r2::rest, bs, acc)
       
   182   case (STAR(r1)::rest, Z::bs) => sdecode_aux(r1::STAR(r1)::rest, bs, acc)
       
   183   case (STAR(_)::rest, S::bs) => sdecode_aux(rest, bs, acc)
       
   184   case (RECD(s, r1)::rest, bs) => sdecode_aux(r1::rest, bs, s"$s:"::acc)
       
   185   case (CHARSET(_)::rest, C(c)::bs) => 
       
   186     sdecode_aux(rest, bs, (acc.head :+ c)::acc.tail)
       
   187 }
       
   188 
       
   189 def sdecode(r: Rexp, bs: Bits) : List[String] = 
       
   190   sdecode_aux(List(r), bs, List("")).reverse.tail
       
   191 
       
   192 
       
   193 
       
   194 // nullable function: tests whether the a (annotated) 
       
   195 // regular expression can recognise the empty string
       
   196 def bnullable (r: ARexp) : Boolean = r match {
       
   197   case AZERO => false
       
   198   case AONE(_) => true
       
   199   case AALTS(_, rs) => rs.exists(bnullable)
       
   200   case ASEQ(_, r1, r2) => bnullable(r1) && bnullable(r2)
       
   201   case ASTAR(_, _) => true
       
   202   case ACHARSET(_, _) => false
       
   203 }
       
   204 
       
   205 def bmkeps(r: ARexp) : Bits = r match {
       
   206   case AONE(bs) => bs
       
   207   case AALTS(bs, r::Nil) => bs ++ bmkeps(r) 
       
   208   case AALTS(bs, r::rs) => 
       
   209     if (bnullable(r)) bs ++ bmkeps(r) else bmkeps(AALTS(bs, rs))  
       
   210   case ASEQ(bs, r1, r2) => bs ++ bmkeps(r1) ++ bmkeps(r2)
       
   211   case ASTAR(bs, r) => bs ++ List(S)
       
   212   case _ => throw new Exception("trying to bmkeps from non-nullable regex")
       
   213 }
       
   214 
       
   215 // derivative of a regular expression w.r.t. a character
       
   216 def bder(c: Char, r: ARexp) : ARexp = r match {
       
   217   case AZERO => AZERO
       
   218   case AONE(_) => AZERO
       
   219   case AALTS(bs, rs) => AALTS(bs, rs.map(bder(c, _)))
       
   220   case ASEQ(bs, r1, r2) => 
       
   221     if (bnullable(r1)) AALT(bs, ASEQ(Nil, bder(c, r1), r2), fuse(bmkeps(r1), bder(c, r2)))
       
   222     else ASEQ(bs, bder(c, r1), r2)
       
   223   case ASTAR(bs, r) => ASEQ(bs, fuse(List(Z), bder(c, r)), ASTAR(Nil, r))
       
   224   case ACHARSET(bs, f) => if(f(c)) AONE(bs :+ C(c)) else AZERO
       
   225 }
       
   226 
       
   227 // derivative w.r.t. a string (iterates bder)
       
   228 @tailrec
       
   229 def bders (s: List[Char], r: ARexp) : ARexp = s match {
       
   230   case Nil => r
       
   231   case c::s => bders(s, bder(c, r))
       
   232 }
       
   233 
       
   234 // main unsimplified lexing function (produces a bitsequence)
       
   235 def blex(r: ARexp, s: List[Char]) : Bits = s match {
       
   236   case Nil => if (bnullable(r)) bmkeps(r) else throw new Exception("Not matched")
       
   237   case c::cs => blex(bder(c, r), cs)
       
   238 }
       
   239 
       
   240 // calls blex and decodes the value
       
   241 def blexing(r: Rexp, s: String) : Val = 
       
   242   vdecode(r, blex(internalise(r), s.toList))
       
   243 
       
   244 
       
   245 // example by Tudor
       
   246 //val reg = (STAR("a") ~ ("b" | "c")).%
       
   247 
       
   248 //println(blexing(reg, "aab"))
       
   249 
       
   250 
       
   251 //=======================
       
   252 // simplification 
       
   253 //
       
   254 
       
   255 def flts(rs: List[ARexp]) : List[ARexp] = rs match {
       
   256   case Nil => Nil
       
   257   case AZERO :: rs => flts(rs)
       
   258   case AALTS(bs, rs1) :: rs => rs1.map(fuse(bs, _)) ++ flts(rs)
       
   259   case r1 :: rs => r1 :: flts(rs)
       
   260 }
       
   261 
       
   262 def bsimp(r: ARexp): ARexp = r match {
       
   263   case ASEQ(bs1, r1, r2) => (bsimp(r1), bsimp(r2)) match {
       
   264       case (AZERO, _) => AZERO
       
   265       case (_, AZERO) => AZERO
       
   266       case (AONE(bs2), r2s) => fuse(bs1 ++ bs2, r2s)
       
   267       // needed in order to keep the size down
       
   268       case (AALTS(bs, rs), r2) => AALTS(bs1 ++ bs, rs.map(ASEQ(Nil, _, r2)))
       
   269       case (r1s, r2s) => ASEQ(bs1, r1s, r2s)
       
   270   }
       
   271   // distinctBy deletes copies of the same  "erased" regex
       
   272   case AALTS(bs1, rs) => (flts(rs.map(bsimp))).distinctBy(erase) match {
       
   273       case Nil => AZERO
       
   274       case r::Nil => fuse(bs1, r)
       
   275       case rs => AALTS(bs1, rs)
       
   276   }
       
   277   case r => r
       
   278 }
       
   279 
       
   280 def blex_simp(r: ARexp, s: List[Char]) : Bits = s match {
       
   281   case Nil => if (bnullable(r)) bmkeps(r) 
       
   282               else throw new Exception("Not matched")
       
   283   case c::cs => blex_simp(bsimp(bder(c, r)), cs)
       
   284 }
       
   285 
       
   286 // blexing_simp decodes a value from the bitsequence (potentially slow)
       
   287 // blexing2_simp decodes a string-list from the bitsequence
       
   288 def blexing_simp(r: Rexp, s: String) : Val = 
       
   289   vdecode(r, blex_simp(internalise(r), s.toList))
       
   290 
       
   291 def blexing2_simp(r: Rexp, s: String) : List[String] = 
       
   292   sdecode(r, blex_simp(internalise(r), s.toList))
       
   293 
       
   294 
       
   295 //println(blexing_simp(reg, "aab"))
       
   296 
       
   297 
       
   298 // extracts a string from value
       
   299 def flatten(v: Val) : String = v match {
       
   300   case Empty => ""
       
   301   case Chr(c) => c.toString
       
   302   case Left(v) => flatten(v)
       
   303   case Right(v) => flatten(v)
       
   304   case Sequ(v1, v2) => flatten(v1) + flatten(v2)
       
   305   case Stars(vs) => vs.map(flatten).mkString
       
   306 }
       
   307 
       
   308 // extracts an environment from a value
       
   309 def env(v: Val) : List[(String, String)] = v match {
       
   310   case Empty => Nil
       
   311   case Chr(c) => Nil
       
   312   case Left(v) => env(v)
       
   313   case Right(v) => env(v)
       
   314   case Sequ(v1, v2) => env(v1) ::: env(v2)
       
   315   case Stars(vs) => vs.flatMap(env)
       
   316   case Recd(x, v) => (x, flatten(v))::env(v)
       
   317 }
       
   318 
       
   319 def bsize(a: ARexp) = size(erase(a))
       
   320 
       
   321 // Some Tests
       
   322 //============
       
   323 
       
   324 
       
   325 def time_needed[T](i: Int, code: => T) = {
       
   326   val start = System.nanoTime()
       
   327   for (j <- 1 to i) code
       
   328   val end = System.nanoTime()
       
   329   (end - start)/(i * 1.0e9)
       
   330 }
       
   331 
       
   332 val evil1 = STAR(STAR("a")) ~ "b"
       
   333 val evil2 = STAR(STAR(STAR("a"))) ~ "b"
       
   334 val evil3 = STAR("aa" | "a")
       
   335 
       
   336 /*
       
   337 println("evil1")
       
   338 for(i <- 0 to 10000 by 1000) {
       
   339     println(time_needed(1, blexing2_simp(evil1, "a"*i ++ "b")))
       
   340 }
       
   341 */
       
   342 
       
   343 /*
       
   344 println("evil2")
       
   345 for(i <- 0 to 10000 by 1000) {
       
   346     println(time_needed(1, blexing2_simp(evil2, "a"*i ++ "b")))
       
   347 }
       
   348 */
       
   349 
       
   350 /*
       
   351 println("evil3")
       
   352 for(i <- 0 to 10000 by 1000) {
       
   353     println(time_needed(1, blexing2_simp(evil3, "a"*i)))
       
   354 }
       
   355 */
       
   356 
       
   357 // WHILE LANGUAGE
       
   358 //================
       
   359 def PLUS(r: Rexp) = r ~ r.%
       
   360 def RANGE(s: String) = CHARSET(s.toSet)
       
   361 
       
   362 val SYM = RANGE("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz_")
       
   363 val DIGIT = RANGE("0123456789")
       
   364 val ID = SYM ~ (SYM | DIGIT).% 
       
   365 val NUM = PLUS(DIGIT)
       
   366 val KEYWORD : Rexp = "skip" | "while" | "do" | "if" | "then" | "else" | "read" | "write" 
       
   367 val SEMI: Rexp = ";"
       
   368 val OP: Rexp = ":=" | "=" | "-" | "+" | "*" | "!=" | "<" | ">"
       
   369 val WHITESPACE = PLUS(" " | "\n" | "\t")
       
   370 val RPAREN: Rexp = "{"
       
   371 val LPAREN: Rexp = "}"
       
   372 val STRING: Rexp = "\"" ~ SYM.% ~ "\""
       
   373 
       
   374 
       
   375 val WHILE_REGS = (("k" $ KEYWORD) | 
       
   376                   ("i" $ ID) | 
       
   377                   ("o" $ OP) | 
       
   378                   ("n" $ NUM) | 
       
   379                   ("s" $ SEMI) | 
       
   380                   ("str" $ STRING) |
       
   381                   ("p" $ (LPAREN | RPAREN)) | 
       
   382                   ("w" $ WHITESPACE)).%
       
   383 
       
   384 
       
   385 // Some Simple While Tests
       
   386 //========================
       
   387 
       
   388 val prog0 = """read n"""
       
   389 println(s"test: $prog0")
       
   390 println(env(blexing_simp(WHILE_REGS, prog0)))
       
   391 println(blexing2_simp(WHILE_REGS, prog0))
       
   392 
       
   393 val prog1 = """read  n; write n"""  
       
   394 println(s"test: $prog1")
       
   395 println(env(blexing_simp(WHILE_REGS, prog1)))
       
   396 println(blexing2_simp(WHILE_REGS, prog1))
       
   397 
       
   398 val prog2 = """
       
   399 write "Fib";
       
   400 read n;
       
   401 minus1 := 0;
       
   402 minus2 := 1;
       
   403 while n > 0 do {
       
   404   temp := minus2;
       
   405   minus2 := minus1 + minus2;
       
   406   minus1 := temp;
       
   407   n := n - 1
       
   408 };
       
   409 write "Result";
       
   410 write minus2
       
   411 """
       
   412 
       
   413 println("lexing fib program (once)")
       
   414 println(blexing2_simp(WHILE_REGS, prog2).filter(s => s == "" || !s.startsWith("w")))
       
   415 
       
   416 val n = 200
       
   417 println(s"lexing fib program ($n times, size ${prog2.length * n})")
       
   418 println(time_needed(1, blexing2_simp(WHILE_REGS, prog2 * n)))