4

Within an annotation Macro, I'm enumerating members of a class and want the types of the methods that I find.

So I happily iterate over the body of the class, and collect all the DefDef members.

... which I can't typecheck.

For each DefDef I've tried wrapping it in an Expr and using actualType. I've tried duplicating the thing and transplanting it into an ad-hoc class (via quasiquotes). I've tried everything else I can think of :)

The best I can get is either NoType or Any, depending on the technique used. The worst I get is to have an exception thrown at me.

These are simple methods, of the form def foo(i: String) = i, so the return type needs to be inferred, but there's no external information required. There are no abstract types, or type params, or other members of the class involved here. I'd like to handle more advanced cases later, but want to have these trivial examples working first.

In a plugin, this would be simple. I'd just typecheck the entire unit with errors suppressed and get at what I want through the symbols, then reset the tree attributes for subsequent processing. As a macro... I'm stumped.

What am I missing?

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155

1 Answers1

2

In a macro it's the same. Instead of typed as in plugins, you call c.typeCheck, but have to be careful not to fall into a trap (https://github.com/scalamacros/paradise/issues/1) that is supposed to be fixed in 2.10.5 and 2.11.0. After a successful return from a c.typeCheck, you can get access to the symbol and do all the usual stuff.

Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
  • I'm already on 2.11.0-M8, so I'll have to see if RC1 helps any. That and try the `Block` wrapper of course :) It's also just struck me that I might have some luck in typechecking the entire enclosing context. – Kevin Wright Mar 13 '14 at 17:47
  • This is deceptive :) I upgraded to RC1 and that removed the occasional error I got when not checking silently, but the returned Tree from c.typecheck was *still* `NoType`. Getting `.symbol.info` did the trick though, I could clearly see the expected types. – Kevin Wright Mar 17 '14 at 09:09
  • 1
    Here's a link to the follow-up question: http://stackoverflow.com/questions/22451181/why-does-typecheck-return-notype-even-when-its-calculated-a-valid-symbol – Eugene Burmako Mar 17 '14 at 10:19