Trait Prettier

Source
pub trait Prettier: Display {
    // Provided methods
    fn pretty(&self, level: usize, max: usize) -> String { ... }
    fn format(&self, level: usize, _max: usize) -> String { ... }
    fn needs_split(&self, max: usize) -> bool { ... }
}
Expand description

§Approach

When a PromQL query is parsed, it is converted into PromQL AST, which is a nested structure of nodes. Each node has a depth/level (distance from the root), that is passed by its parent.

While prettifying, a Node considers 2 things:

  1. Did the current Node’s parent add a new line?
  2. Does the current Node needs to be prettified?

The level of a Node determines if it should be indented or not. The answer to the 1 is NO if the level passed is 0. This means, the parent Node did not apply a new line, so the current Node must not apply any indentation as prefix. If level > 1, a new line is applied by the parent. So, the current Node should prefix an indentation before writing any of its content. This indentation will be ([level/depth of current Node] * “ “).

The answer to 2 is YES if the normalized length of the current Node exceeds the [MAX_CHARACTERS_PER_LINE] limit. Hence, it applies the indentation equal to its depth and increments the level by 1 before passing down the child. If the answer is NO, the current Node returns the normalized string value of itself.

Provided Methods§

Source

fn pretty(&self, level: usize, max: usize) -> String

max param is short for max_characters_per_line.

Source

fn format(&self, level: usize, _max: usize) -> String

override format if expr needs to be split into multiple lines

Source

fn needs_split(&self, max: usize) -> bool

override needs_split to return false, in order not to split multiple lines

Implementors§