Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active September 11, 2019 08:36
Show Gist options
  • Save xuwei-k/4991805 to your computer and use it in GitHub Desktop.
Save xuwei-k/4991805 to your computer and use it in GitHub Desktop.
compile time regex check and string interpolators
import scala.reflect.macros.Context
import scala.util.matching.Regex
import java.util.regex.PatternSyntaxException
object Macros{
implicit class RegexContext(val c: StringContext) {
def r(): Regex = macro regexImpl
}
def regexImpl(c: Context)(): c.Expr[Regex] = {
import c.universe._
c.prefix.tree match {
case Apply(_,List(Apply(_,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(r"foo|bar") // compile success !
println(r"[foo") // compile error !
println(r"foo$") // error: invalid string interpolation: `$$', `$'ident or `$'BlockExpr expected
}
@acjay
Copy link

acjay commented May 6, 2017

Would this be even simpler with quasiquotes? Also, any solution for the $ problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment