Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching inside scala 2.10 ASTs

What's the best way to recursively search for an element in scala 2.10 ASTs?

The trees might be a result of power.trees(code) or mirror.mkToolBox().parseExpr(code) Edit. In 2.10.0-RC1 parseExpr has been renamed to parse.

The concrete use-case that I have is extracting the code of a method from a given class/object code by method name, but I assume that the question would be more relevant for others if formulated in a more generic way.

like image 693
Sagie Davidovich Avatar asked Aug 25 '12 15:08

Sagie Davidovich


1 Answers

Maybe you should have a look at https://github.com/scala/scala/blob/2.10.x/src/reflect/scala/reflect/api/Trees.scala#L606, especially at the classes Traverser, Transformer and the methods for substitution (Tree.substituteSymbols, Tree.substituteTypes or Tree.substituteThis). If you want to extract a method from a tree, you can use a Traverser and override the traverse method. In the traverse method, you check whether the node matches the method you want. If so, you are done. If not, you call super.traverse.

like image 68
Kim Stebel Avatar answered Oct 03 '22 01:10

Kim Stebel