Scala AST in Scala [closed]

匆匆过客 提交于 2019-11-27 13:04:08

问题


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.)


回答1:


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.




回答2:


A few existing parsers:

  • The offical Scala compiler.
  • The IntelliJ IDEA Scala plugin has a parser written in Scala against IntelliJ's PsiBuilder API.
  • The Scala Netbeans plugin used a parser implemented in Rats! (which generates Java code), but "replaced these parser and analyzer by Scala's native compiler".
  • The Scala-rules project, written in Scala.

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.




回答3:


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.




回答4:


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




回答5:


Here is a project by one of the compiler committers http://github.com/paulp/scala-lang-combinators




回答6:


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!



来源:https://stackoverflow.com/questions/1788627/scala-ast-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!