Skip to content

Instantly share code, notes, and snippets.

@eed3si9n
Forked from xuwei-k/Macros.scala
Last active December 13, 2015 23:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eed3si9n/4992129 to your computer and use it in GitHub Desktop.
Save eed3si9n/4992129 to your computer and use it in GitHub Desktop.
import scala.reflect.macros.Context
import scala.util.matching.Regex
import java.util.regex.PatternSyntaxException
object Macros {
implicit class RegexContext(val c: String) {
def regex(): Regex = macro regexImpl
}
def regexImpl(c: Context)(): c.Expr[Regex] = {
import c.universe._
c.prefix.tree match {
case Apply(Select(_, _), List(Literal(Constant(str: String)))) =>
try{
str.r
}catch{
case e: PatternSyntaxException => c.abort(c.enclosingPosition, e.toString)
}
val Apply(fun, _) = reify(new Regex("")).tree
c.Expr[Regex](Apply.apply(fun, c.literal(str).tree :: Nil))
}
}
}
import Macros._
object Main extends App{
println("foo|bar".regex) // compile success !
println("[foo".regex) // compile error !
println("foo$".regex)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment