I would like to use the built in macro(AST) to create a representation for crystal code

Hi, I have looked for resources around how to get to generate an ast tree output as a string.
I found a GitHub issue about it 8 years ago but that code isn’t compatible with today’s crystal: What is the interface to get an AST representation for a given crystal code? · Issue #65 · crystal-lang/crystal (github.com)

I am a little bit unsure how to get this to work since the ast module is quite undocumented.
If some one can help me to do a similar script as in the issue but compatible with crystal 1.6.2 so would I be very thankful.

Hi @meatball133 , the following works:

require "compiler/crystal/syntax/*"

include Crystal

parser = Parser.new "
  def foo

  def bar

nodes = parser.parse

puts "Before:"
puts nodes

As you can see, the location of the parser changed at some point. And this could serve as a warning: unlike with the stdlib, the compiler is subject to change without warning. I don’t know what you’re trying to do, but have this into consideration.

1 Like

Hi, thanks for the replay.

I am working on the crystal track on the learning platform Exercism.
I have rebuilt some tooling already thanks to some wonderful people here on the forum.

Exercism has a feature called “representer” which is creating a represented code of users’ solutions to problems.
The point of having a representer is to be able to give standardized feedback on solutions with particular ways of solving problems.
To be able to do this standardized feedback we have to make the solutions more standardized.

Therefore a solution that other languages have done on the platform is to use a built-in ast library to convert the code to an ast tree.

1 Like

What’s the main difference between source code and the standardized solution? Is it whitespace? Is it comments removal? Variable names?

The representer format, remove comment and variable names.

There is more detail of what the representer does: Representers

1 Like