/
LiteralMatchers.scala
43 lines (37 loc) · 1.35 KB
/
LiteralMatchers.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package eu.timepit.refined.macros
import macrocompat.bundle
import scala.reflect.macros.blackbox
@bundle
trait LiteralMatchers {
val c: blackbox.Context
import c.universe._
private[macros] object BigIntMatcher {
def unapply(expr: c.Tree): Option[BigInt] = expr match {
case q"scala.`package`.BigInt.apply(${lit: Literal})" =>
lit.value.value match {
case i: Int => Some(BigInt(i))
case l: Long => Some(BigInt(l))
case s: String => scala.util.Try(BigInt(s)).toOption
case _ => None
}
case _ => None
}
}
private[macros] object BigDecimalMatcher {
def unapply(expr: c.Tree): Option[BigDecimal] = {
val constant = expr match {
case q"scala.`package`.BigDecimal.apply(${lit: Literal})" => Some(lit.value.value)
case q"scala.`package`.BigDecimal.exact(${lit: Literal})" => Some(lit.value.value)
case q"scala.`package`.BigDecimal.valueOf(${lit: Literal})" => Some(lit.value.value)
case _ => None
}
constant.flatMap {
case i: Int => Some(BigDecimal(i))
case l: Long => Some(BigDecimal(l))
case d: Double => Some(BigDecimal(d))
case s: String => scala.util.Try(BigDecimal(s)).toOption
case _ => None
}
}
}
}