Print tree type in scala macro

Inside the macro, how can I ask the compiler to infer the type of the constructed tree? I found only Context.typeCheck, but checks only those types, but does not return a result.

+4
source share
2 answers

If you checked the type of tree, you can simply use its tpe method:

 scala> def impl(c: Context) = c.literal(c.typeCheck(c parse "1+1").tpe.toString) impl: (c: scala.reflect.macros.Context)c.Expr[String] scala> def mac = macro impl mac: String scala> println(mac) Int(2) 

You could also wrap it in an expression, of course, but not necessary if you just want a type.

+7
source

I realized this, and I hope that this will save someone else from the hassle

 import reflect.macros.Context import language.experimental.macros def impl(c: Context) = { val tree = c.parse("1+1") val expr = c.Expr[Any](c.typeCheck(tree)) println(expr.staticType) println(expr.actualType) c.literalUnit } def mac = macro impl 

By packing in Expr you get the opportunity to request the actual type. Any of these must provide a legal upper bound. Without this, the inferred type would be Expr [Nothing], and you would have problems. The trick is to wrap the tree returned from c.typeCheck, otherwise the Type will just be null.

The mac method simply returns () bu, it prints Any top and Int(2) is the actual type.

+2
source

Source: https://habr.com/ru/post/1488991/


All Articles