Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active September 11, 2019 08:36

Revisions

  1. xuwei-k revised this gist Feb 20, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion README.md
    Original file line number Diff line number Diff line change
    @@ -1,2 +1,2 @@
    - inspired [macrocosm](https://github.com/retronym/macrocosm/blob/521dfc0bcd1/src/main/scala/com/github/retronym/macrocosm/Macrocosm.scala#L102-L128) and [inkytonik's blog post](http://hootenannylas.blogspot.com.au/2013/02/syntax-checking-in-scala-string.html)
    - inspired by [macrocosm](https://github.com/retronym/macrocosm/blob/521dfc0bcd1/src/main/scala/com/github/retronym/macrocosm/Macrocosm.scala#L102-L128) and [inkytonik's blog post](http://hootenannylas.blogspot.com.au/2013/02/syntax-checking-in-scala-string.html)
    - Can not use if `$` character contains. Does anyone have a solution? :(
  2. xuwei-k created this gist Feb 20, 2013.
    25 changes: 25 additions & 0 deletions Macros.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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))
    }
    }

    }
    7 changes: 7 additions & 0 deletions Main.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    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
    }
    2 changes: 2 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    - inspired [macrocosm](https://github.com/retronym/macrocosm/blob/521dfc0bcd1/src/main/scala/com/github/retronym/macrocosm/Macrocosm.scala#L102-L128) and [inkytonik's blog post](http://hootenannylas.blogspot.com.au/2013/02/syntax-checking-in-scala-string.html)
    - Can not use if `$` character contains. Does anyone have a solution? :(