Is there a Scala library that parses Scala and creates an Abstract Syntax Tree (AST)?
Ideally I am interested in a Scala library. Plan B would be a Java library.
(I know I could leverage the EBNF from the Scala Syntax Summary.)
Is there a Scala library that parses Scala and creates an Abstract Syntax Tree (AST)?
Ideally I am interested in a Scala library. Plan B would be a Java library.
(I know I could leverage the EBNF from the Scala Syntax Summary.)
I would think the best way to access the AST is with a compiler plugin. You should read a soft introduction before diving in deep.
A few existing parsers:
PsiBuilder
API.Be cautious if using the EBNF from the spec, there are apparently:
"mismatches between the appendix and the inline grammar, and mismatches between the language compiled by scalac (and utilized in the scala sources) and the language claimed by the grammar" -- Scala Trac bug #1826.
You can't build an AST for Scala from the grammar alone. There's implicits to consider, and, to consider them, there is the type inferencer to consider.
You can, however, call the compiler itself -- it is just a jar file, after all. Scala 2.8, in particular, has quite a few hooks for other programs to latch on -- work of Miles Sabin, who is doing this precisely so that the Eclipse plugin for Scala can leverage the compiler in such way.
I suggest you go to the Scala Tools mailing list, and get in contact with people there.
Here is a project by one of the compiler committers http://github.com/paulp/scala-lang-combinators
If you want to generate AST of a piece of code. You could use scala reflection:
showRaw(reify{
//your code here like:
print(2)
})
The code above will generate an AST:
Expr(Apply(Select(Ident(scala.Predef), TermName("print")), List(Literal(Constant(2)))))
Reference:
http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
Not sure about the pure scala solutions, but if you find yourself needing to implement plan B, you can start by checking out ANTLR or Rats!