Extraction of Tuple1 in comparison of quasi-quasotes

Suppose I want a macro that takes an expression and returns arity if it is a string literal. Something like this works for tuples, but returns Some(1)

instead None

for everything else:

import scala.reflect.macros.blackbox.Context

class ArityMacros(val c: Context) {
  import c.universe._

  def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
    case q"(..$xs)" => q"_root_.scala.Some(${ xs.size })"
    case _ => q"_root_.scala.None"
  }
}

import scala.language.experimental.macros

def arity[A](a: A): Option[Int] = macro ArityMacros.arity[A]

      

I know I can do something like this:

class ArityMacros(val c: Context) {
  import c.universe._

  def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
    case q"scala.Tuple1.apply[$_]($_)" => q"_root_.scala.Some(1)"
    case q"(..$xs)" if xs.size > 1     => q"_root_.scala.Some(${ xs.size })"
    case other                         => q"_root_.scala.None"
  }
}

      

But feel like there must be a better way to distinguish between cases Tuple1

and non-tuples (and maybe I've used it in the past?).

+3
macros scala tuples scala-macros scala-quasiquotes


source to share


No one has answered this question yet

Check out similar questions:

272
How to Use Shapeless in Quasiquote?
25
Corresponding function literals with quasi-quarters in Scala
8
Quasi-quarters for multiple parameters and parameter lists
3
What is the type of quasi-quasi that matches the type parameters of the collation?
3
How do I handle defaults idiomatically in Scala?
3
Scala custom unauthorized use with generics
3
How do you determine if an expression passed to a macro will always have the same value?
1
Convert one case class to another, which is similar to an extra parameter in Scala
1
Reliability of Pattern Matching Trees with Quasi-Quarters
0
How can I use Scala macros to create new partial functions or transform them?



All Articles
Loading...
X
Show
Funny
Dev
Pics