display_tree: A crate for automatically pretty-printing tree structures!

48 points skadoodledo

Hey all:) I just finished my first major rust project that I'd love to share. It allows you to display your types nicely formatted as trees, as shown below. And its super easy to use.

Some examples of what it can do

It uses a derive macro to automatically implement this functionality through the DisplayTree trait. Here is the enum that is used in the examples above, representing a simple expression:

#[derive(DisplayTree)]
enum Expr {
    Integer(i32),
    Plus(#[tree] Box<Self>, #[tree] Box<Self>),
    Minus(#[tree] Box<Self>, #[tree] Box<Self>),
    Times(#[tree] Box<Self>, #[tree] Box<Self>),
    Divided(#[tree] Box<Self>, #[tree] Box<Self>),
    Negative(#[tree] Box<Self>),
}

And how you might print it:

// `expr` declaration omitted
println_tree!(expr);

It can be derived for both structs and enums. The fields will be the leaves of the tree, and the name of the struct, or the name of the variant if it's an enum, will be the root.

It's also highly customizable. The derived implementation can be customized with helper attributes (one example seen above is the #[tree] attribute, which marks a field that should be displayed as a subtree). And the way it is styled when you print it can also be controlled.

In the future I might work on adding entirely different ways of formatting the tree, like a classic top-down version.

Links:

Thanks for reading:)