我正在尝试使用scala宏编写一个使用给定值填充数组的函数。例如,致电:
val ary = Array( 0, 1, 2 )
fill3( ary, 50+25 )
应扩展为:
val ary = Array(0, 1, 2 )
{
val $value = 50+25
ary(0) = $value
ary(1) = $value
ary(2) = $value
}
这是我的第一次尝试:
def fill3( ary: Array[Int], x: Int ) = macro fill_impl3
def fill_impl3( c: Context )
( ary: c.Expr[Array[Int]], x: c.Expr[Int]): c.Expr[Unit] = {
import c.universe._
def const(x:Int) = Literal(Constant(x))
//Precompute x
val valName = newTermName("$value")
val valdef = ValDef( Modifiers(), valName, TypeTree(typeOf[Int]), x.tree )
val updates = List.tabulate( 3 ){
i => Apply( Select( ary.tree, "update"), List( const(i), ??? ) )
}
val insts = valdef :: updates
c.Expr[Unit](Block(insts:_*))
}
但在这里,我有两个原因:
$value
)fill3
,fill4
,{{ 1}}等等。有没有正确的方法继续进行?我怎样才能解决我的两个问题?
编辑:我意识到我最初的问题是愚蠢的,因为在编译时必须知道大小......
答案 0 :(得分:2)
def fill(size:Int, ary: Array[Int], x: Int ) = macro fill_impl
def fill_impl( c: Context )
(size:c.Expr[Int], ary: c.Expr[Array[Int]], x: c.Expr[Int]): c.Expr[Unit] = {
import c.universe._
def const(x:Int) = Literal(Constant(x))
val Literal(Constant(arySize:Int)) = size.tree
//Precompute x
val valName = newTermName("$value")
val valdef = ValDef( Modifiers(), valName, TypeTree(typeOf[Int]), x.tree )
val updates = List.tabulate( arySize ){
i => Apply( Select( ary.tree, "update"), List( const(i), Ident(valName) ) )
}
val insts = valdef :: updates
c.Expr[Unit](Block(insts:_*))
}
答案 1 :(得分:0)
您可以尝试使用reify
并打印其结果的原始树来解决这个问题:
def fill_impl3( c: Context )
( ary: c.Expr[Array[Int]], x: c.Expr[Int]): c.Expr[Unit] = {
import c.universe._
val r = reify {
val $value = x.splice
val $arr = ary.splice
$arr(0) = $value
$arr(1) = $value
$arr(2) = $value
}
println( showRaw( r.tree ))
r
}
这给出了类似
的内容val vt = newTermName("$value")
val at = newTermName("$arr")
val ut = newTermName("update")
Block(List(
ValDef(Modifiers(), vt, TypeTree(), ...),
ValDef(Modifiers(), at, TypeTree(), ...),
Apply(Select(Ident(at), ut), List(Literal(Constant(0)), Ident(vt))),
Apply(Select(Ident(at), ut), List(Literal(Constant(1)), Ident(vt)))),
Apply(Select(Ident(at), ut), List(Literal(Constant(2)), Ident(vt)))
)