Scala AST in Scala [closed]

我只是一个虾纸丫 提交于 2019-11-28 20:41:09
Mitch Blevins

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:

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.

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

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

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!

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