Scala.meta: get branch, ast, leaf annotations from Tree instance

#1

Is there a way to determine annotation (@branch, @ast, @leaf) of instance of Tree at runtime?

The code as follows shows that the instance has no annotations:

  def main(args: Array[String]): Unit = {
    val tree: Tree = q"val a: Int = 2"
    // `tree.getClass` has type `class scala.meta.Defn$Val$DefnValImpl`
    val annots = tree.getClass.getAnnotations
    // annots: Array is empty
  }
#2

With scala reflection:

import scala.reflect.runtime.universe._
runtimeMirror(getClass.getClassLoader).reflect(tree).symbol.annotations

But I’m not sure if that makes sense when you’re already using scala.meta.

1 Like
#3

There is an internal scala.meta API that provides all sorts of introspection services for ast and adt classes. Here are some examples: https://github.com/scalameta/scalameta/blob/v1.7.0/scalameta/scalameta/jvm/src/test/scala/scala/meta/tests/ast/ReflectionSuite.scala.

1 Like