
import scala.language.implicitConversions    
import scala.language.reflectiveCalls
import scala.annotation.tailrec   
import scala.util.Try

def escape(raw: String) : String = {
  import scala.reflect.runtime.universe._
  Literal(Constant(raw)).toString
}

def esc2(r: (String, String)) = (escape(r._1), escape(r._2))



// usual regular expressions
abstract class Rexp 
case object ZERO extends Rexp
case object ONE extends Rexp
case class CHAR(c: Char) extends Rexp
case class ALTS(rs: List[Rexp]) extends Rexp 
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
case class STAR(r: Rexp) extends Rexp 
case class RECD(x: String, r: Rexp) extends Rexp

// abbreviations
def ALT(r1: Rexp, r2: Rexp) = ALTS(List(r1, r2))

// values
abstract class Val
case object Empty extends Val
case class Chr(c: Char) extends Val
case class Sequ(v1: Val, v2: Val) extends Val
case class Left(v: Val) extends Val
case class Right(v: Val) extends Val
case class Stars(vs: List[Val]) extends Val
case class Rec(x: String, v: Val) extends Val



// some convenience for typing in regular expressions
def charlist2rexp(s : List[Char]): Rexp = s match {
  case Nil => ONE
  case c::Nil => CHAR(c)
  case c::s => SEQ(CHAR(c), charlist2rexp(s))
}
implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList)

implicit def RexpOps(r: Rexp) = new {
  def | (s: Rexp) = ALT(r, s)
  def % = STAR(r)
  def ~ (s: Rexp) = SEQ(r, s)
}

implicit def stringOps(s: String) = new {
  def | (r: Rexp) = ALT(s, r)
  def | (r: String) = ALT(s, r)
  def % = STAR(s)
  def ~ (r: Rexp) = SEQ(s, r)
  def ~ (r: String) = SEQ(s, r)
  def $ (r: Rexp) = RECD(s, r)
}


// string of a regular expressions - for testing purposes
def string(r: Rexp): String = r match {
  case ZERO => "0"
  case ONE => "1"
  case CHAR(c) => c.toString
  case ALTS(rs) => rs.map(string).mkString("[", "|", "]")
  case SEQ(r1, r2) => s"(${string(r1)} ~ ${string(r2)})"
  case STAR(r) => s"{${string(r)}}*"
  case RECD(x, r) => s"(${x}! ${string(r)})"
}


//--------------------------------------------------------------
// START OF NON-BITCODE PART
//

// nullable function: tests whether the regular 
// expression can recognise the empty string
def nullable (r: Rexp) : Boolean = r match {
  case ZERO => false
  case ONE => true
  case CHAR(_) => false
  case ALTS(rs) => rs.exists(nullable)
  case SEQ(r1, r2) => nullable(r1) && nullable(r2)
  case STAR(_) => true
  case RECD(_, r) => nullable(r)
}

// derivative of a regular expression w.r.t. a character
def der (c: Char, r: Rexp) : Rexp = r match {
  case ZERO => ZERO
  case ONE => ZERO
  case CHAR(d) => if (c == d) ONE else ZERO
  case ALTS(List(r1, r2)) => ALTS(List(der(c, r1), der(c, r2)))
  case SEQ(r1, r2) => 
    if (nullable(r1)) ALTS(List(SEQ(der(c, r1), r2), der(c, r2)))
    else SEQ(der(c, r1), r2)
  case STAR(r) => SEQ(der(c, r), STAR(r))
  case RECD(_, r1) => der(c, r1)
}


def flatten(v: Val) : String = v match {
  case Empty => ""
  case Chr(c) => c.toString
  case Left(v) => flatten(v)
  case Right(v) => flatten(v)
  case Sequ(v1, v2) => flatten(v1) + flatten(v2)
  case Stars(vs) => vs.map(flatten).mkString
  case Rec(_, v) => flatten(v)
}

// extracts an environment from a value
def env(v: Val) : List[(String, String)] = v match {
  case Empty => Nil
  case Chr(c) => Nil
  case Left(v) => env(v)
  case Right(v) => env(v)
  case Sequ(v1, v2) => env(v1) ::: env(v2)
  case Stars(vs) => vs.flatMap(env)
  case Rec(x, v) => (x, flatten(v))::env(v)
}


// injection part
def mkeps(r: Rexp) : Val = r match {
  case ONE => Empty
  case ALTS(List(r1, r2)) => 
    if (nullable(r1)) Left(mkeps(r1)) else Right(mkeps(r2))
  case SEQ(r1, r2) => Sequ(mkeps(r1), mkeps(r2))
  case STAR(r) => Stars(Nil)
  case RECD(x, r) => Rec(x, mkeps(r))
}

def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match {
  case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs)
  case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2)
  case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2)
  case (SEQ(r1, r2), Right(v2)) => Sequ(mkeps(r1), inj(r2, c, v2))
  case (ALTS(List(r1, r2)), Left(v1)) => Left(inj(r1, c, v1))
  case (ALTS(List(r1, r2)), Right(v2)) => Right(inj(r2, c, v2))
  case (CHAR(_), Empty) => Chr(c) 
  case (RECD(x, r1), _) => Rec(x, inj(r1, c, v))
}

// lexing without simplification
def lex(r: Rexp, s: List[Char]) : Val = s match {
  case Nil => if (nullable(r)) mkeps(r) else throw new Exception("Not matched")
  case c::cs => inj(r, c, lex(der(c, r), cs))
}

def lexing(r: Rexp, s: String) : Val = lex(r, s.toList)

//println(lexing(("ab" | "ab") ~ ("b" | ONE), "ab"))

// some "rectification" functions for simplification
def F_ID(v: Val): Val = v
def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v))
def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v))
def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
  case Right(v) => Right(f2(v))
  case Left(v) => Left(f1(v))
}
def F_SEQ(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
  case Sequ(v1, v2) => Sequ(f1(v1), f2(v2))
}
def F_SEQ_Empty1(f1: Val => Val, f2: Val => Val) = 
  (v:Val) => Sequ(f1(Empty), f2(v))
def F_SEQ_Empty2(f1: Val => Val, f2: Val => Val) = 
  (v:Val) => Sequ(f1(v), f2(Empty))
def F_RECD(f: Val => Val) = (v:Val) => v match {
  case Rec(x, v) => Rec(x, f(v))
}
def F_ERROR(v: Val): Val = throw new Exception("error")

// simplification of regular expressions returning also an
// rectification function; no simplification under STAR 
def simp(r: Rexp): (Rexp, Val => Val) = r match {
  case ALTS(List(r1, r2)) => {
    val (r1s, f1s) = simp(r1)
    val (r2s, f2s) = simp(r2)
    (r1s, r2s) match {
      case (ZERO, _) => (r2s, F_RIGHT(f2s))
      case (_, ZERO) => (r1s, F_LEFT(f1s))
      case _ => if (r1s == r2s) (r1s, F_LEFT(f1s))
                else (ALTS(List(r1s, r2s)), F_ALT(f1s, f2s)) 
    }
  }
  case SEQ(r1, r2) => {
    val (r1s, f1s) = simp(r1)
    val (r2s, f2s) = simp(r2)
    (r1s, r2s) match {
      case (ZERO, _) => (ZERO, F_ERROR)
      case (_, ZERO) => (ZERO, F_ERROR)
      case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s))
      case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s))
      case _ => (SEQ(r1s,r2s), F_SEQ(f1s, f2s))
    }
  }
  case RECD(x, r1) => {
    val (r1s, f1s) = simp(r1)
    (RECD(x, r1s), F_RECD(f1s))
  }
  case r => (r, F_ID)
}

def ders_simp(s: List[Char], r: Rexp) : Rexp = s match {
  case Nil => r
  case c::s => ders_simp(s, simp(der(c, r))._1)
}


def lex_simp(r: Rexp, s: List[Char]) : Val = s match {
  case Nil => if (nullable(r)) mkeps(r) else throw new Exception("Not matched")
  case c::cs => {
    val (r_simp, f_simp) = simp(der(c, r))
    inj(r, c, f_simp(lex_simp(r_simp, cs)))
  }
}

def lexing_simp(r: Rexp, s: String) : Val = lex_simp(r, s.toList)

//println(lexing_simp(("a" | "ab") ~ ("b" | ""), "ab"))


def tokenise_simp(r: Rexp, s: String) = 
  env(lexing_simp(r, s)).map(esc2)

//--------------------------------------------------------------------
// Partial Derivatives


def pder(c: Char, r: Rexp): Set[Rexp] = r match {
  case ZERO => Set()
  case ONE => Set()
  case CHAR(d) => if (c == d) Set(ONE) else Set()
  case ALTS(rs) => rs.toSet.flatMap(pder(c, _))
  case SEQ(r1, r2) =>
    (for (pr1 <- pder(c, r1)) yield SEQ(pr1, r2)) ++
    (if (nullable(r1)) pder(c, r2) else Set())
  case STAR(r1) =>
    for (pr1 <- pder(c, r1)) yield SEQ(pr1, STAR(r1))
  case RECD(_, r1) => pder(c, r1)
}

def pders(cs: List[Char], r: Rexp): Set[Rexp] = cs match {
  case Nil => Set(r)
  case c::cs => pder(c, r).flatMap(pders(cs, _))
}

def pders_simp(cs: List[Char], r: Rexp): Set[Rexp] = cs match {
  case Nil => Set(r)
  case c::cs => pder(c, r).flatMap(pders_simp(cs, _)).map(simp(_)._1)
}

def psize(rs: Set[Rexp])  = 
  rs.map(size).sum


// A simple parser for regexes

case class Parser(s: String) {
  var i = 0
  
  def peek() = s(i)
  def eat(c: Char) = 
    if (c == s(i)) i = i + 1 else throw new Exception("Expected " + c + " got " + s(i))
  def next() = { i = i + 1; s(i - 1) }
  def more() = s.length - i > 0

  def Regex() : Rexp = {
    val t = Term();
    if (more() && peek() == '|') {
      eat ('|') ; 
      ALT(t, Regex()) 
    } 
    else t
  }

  def Term() : Rexp = {
    var f : Rexp = 
      if (more() && peek() != ')' && peek() != '|') Factor() else ONE;
    while (more() && peek() != ')' && peek() != '|') {
      f = SEQ(f, Factor()) ;
    }
    f
  }

  def Factor() : Rexp = {
    var b = Base();
    while (more() && peek() == '*') {
      eat('*') ;
      b = STAR(b) ;
    }
    while (more() && peek() == '?') {
      eat('?') ;
      b = ALT(b, ONE) ;
    }
    while (more() && peek() == '+') {
      eat('+') ;
      b = SEQ(b, STAR(b)) ;
    }
    b
  }

  def Base() : Rexp = {
    peek() match {
      case '(' => { eat('(') ; val r = Regex(); eat(')') ; r }   // if groups should be groups RECD("",r) }
      case _ => CHAR(next())
    }
  }
}

// two simple examples for the regex parser

println("two simple examples for the regex parser")

println(string(Parser("a|(bc)*").Regex()))
println(string(Parser("(a|b)*(babab(a|b)*bab|bba(a|b)*bab)(a|b)*").Regex()))



//System.exit(0)

//   Testing
//============

def time[T](code: => T) = {
  val start = System.nanoTime()
  val result = code
  val end = System.nanoTime()
  ((end - start)/1.0e9).toString
  //result
}

def timeR[T](code: => T) = {
  val start = System.nanoTime()
  for (i <- 1 to 10) code
  val result = code
  val end = System.nanoTime()
  (result, (end - start))
}

//size: of a Aregx for testing purposes 
def size(r: Rexp) : Int = r match {
  case ZERO => 1
  case ONE => 1
  case CHAR(_) => 1
  case SEQ(r1, r2) => 1 + size(r1) + size(r2)
  case ALTS(rs) => 1 + rs.map(size).sum
  case STAR(r) => 1 + size(r)
  case RECD(_, r) => size(r)
}

//enumerates strings of length n over alphabet cs
def strs(n: Int, cs: String) : Set[String] = {
  if (n == 0) Set("")
  else {
    val ss = strs(n - 1, cs)
    ss ++
    (for (s <- ss; c <- cs.toList) yield c + s)
  }
}

def enum(n: Int, s: String) : Stream[Rexp] = n match {
  case 0 => ZERO #:: ONE #:: s.toStream.map(CHAR)
  case n => {  
    val rs = enum(n - 1, s)
    rs #:::
    (for (r1 <- rs; r2 <- rs) yield ALT(r1, r2)) #:::
    (for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) #:::
    (for (r1 <- rs) yield STAR(r1))
  }
}




println("Antimirov Example 5.5")

val antimirov = Parser("(a|b)*(babab(a|b)*bab|bba(a|b)*bab)(a|b)*").Regex()
val strings = strs(6, "ab")
val pds = strings.flatMap(s => pders(s.toList, antimirov))
val pds_simplified = pds.map(simp(_)._1)


println("Unsimplified set")
println(pds.map(string).mkString("\n"))
println("Number of pds  " +  pds.size)
println("\nSimplified set")
println(pds_simplified.map(string).mkString("\n"))
println("Number of pds  " +  pds_simplified.size)




def fact(n: Int) : Int = 
  if (n == 0) 1 else n *  fact(n - 1)
