Pretty Print Tree Data Structures in Ruby

I am working on creating a compiler, and in this I will generate a tree representing the source program that is being passed. I want to show that this tree is like a mod, so I can display the structure of the program to everyone who is interested,

Now I just print the tree on one line:

ProgramNode -> 'Math' BlockNode -> DeclarationNode -> ConstantDeclarationNode -> const ConstantListNode -> [m := 7, ConstantANode -> [n := StringLiteralNode -> ""TEST"" ]] ; 

What I would like is something like this:

  ProgramNode / \ 'Math' BlockNode | DeclarationNode | ConstantDeclarationNode ------------------------------ / \ | const ConstantListNode | / | \ \ | m := 7 ConstantANode | / | \ | n := StringLiteralNode | / | \ | " TEST " ; 

I really didn't work with trees in Ruby, how are they usually represented?

Any help would be appreciated.

+7
source share
2 answers

This pretty printed print requires a lot of math. In addition, it is unclear what should happen if the tree is too large for the console window. I do not know of any existing libraries that will do this. I personally use awesome_print .

 tree = {'ConstantDeclarationNode' => ['const', 'ConstantListNode' => ['m', ':=', '7']]} require 'awesome_print' ap tree # >> { # >> "ConstantDeclarationNode" => [ # >> [0] "const", # >> [1] { # >> "ConstantListNode" => [ # >> [0] "m", # >> [1] ":=", # >> [2] "7" # >> ] # >> } # >> ] # >> } 

It has tons of options, check it out!

+3
source

You need to check the graph gem. It's amazing and wonderful to just work. You can choose the direction of your tree and the shape of the nodes, as well as colors and much more. I first found out about this in Rubyconf last year and was blown away.

It is as simple as:

 digraph do edge "Programnode", "Blocknode" edge "Programnode", "Math" edge "Blocknode", "DeclarationNode" end 

Obviously, you want to programmatically enter the edges :)

Below is a link to pdf , which will give additional information about this:

There is also a video about Confreaks if you are interested.

Cheers, Sean

+2
source

All Articles