Pretty Printing a tree data structure in Ruby
abstract-syntax-tree, expression-trees, ruby
Solution
This kind of pretty printing requires quite a bit of math. Besides, it's unclear what should happen if the tree grows too wide for the console window. I don't know of any existing libraries that'll 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!
Problem
I am working on a building a compiler and within that I generate a tree that represents the source program that is passed in. I want to display this is a tree like fashion so I can display the structure of the program to anyone interested. Right now I just have the tree printing on a single line like this: ``` 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 haven't really worked with trees in Ruby, how are they usually represented? Any help would be appreciated.