1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use std::fmt::{Display, Formatter, UpperExp};

use polars_core::error::*;

use crate::logical_plan::visitor::{VisitRecursion, Visitor};
use crate::prelude::visitor::AexprNode;
use crate::prelude::*;

/// Hack UpperExpr trait to get a kind of formatting that doesn't traverse the nodes.
/// So we can format with {foo:E}
impl UpperExp for AExpr {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            AExpr::Explode(_) => "explode",
            AExpr::Alias(_, name) => return write!(f, "alias({})", name.as_ref()),
            AExpr::Column(name) => return write!(f, "col({})", name.as_ref()),
            AExpr::Literal(lv) => return write!(f, "lit({lv:?})"),
            AExpr::BinaryExpr { op, .. } => return write!(f, "binary: {}", op),
            AExpr::Cast {
                data_type, strict, ..
            } => {
                return if *strict {
                    write!(f, "strict cast({})", data_type)
                } else {
                    write!(f, "cast({})", data_type)
                }
            },
            AExpr::Sort { options, .. } => {
                return write!(
                    f,
                    "sort: {}{}{}",
                    options.descending as u8, options.nulls_last as u8, options.multithreaded as u8
                )
            },
            AExpr::Gather { .. } => "gather",
            AExpr::SortBy { descending, .. } => {
                write!(f, "sort_by:")?;
                for i in descending {
                    write!(f, "{}", *i as u8)?;
                }
                return Ok(());
            },
            AExpr::Filter { .. } => "filter",
            AExpr::Agg(a) => {
                let s: &str = a.into();
                return write!(f, "{}", s.to_lowercase());
            },
            AExpr::Ternary { .. } => "ternary",
            AExpr::AnonymousFunction { options, .. } => {
                return write!(f, "anonymous_function: {}", options.fmt_str)
            },
            AExpr::Function { function, .. } => return write!(f, "function: {function}"),
            AExpr::Window { .. } => "window",
            AExpr::Wildcard => "*",
            AExpr::Slice { .. } => "slice",
            AExpr::Count => "count",
            AExpr::Nth(v) => return write!(f, "nth({})", v),
        };

        write!(f, "{s}")
    }
}

pub(crate) struct TreeFmtVisitor {
    levels: Vec<Vec<String>>,
    depth: u32,
    width: u32,
}

impl TreeFmtVisitor {
    pub(crate) fn new() -> Self {
        Self {
            levels: vec![],
            depth: 0,
            width: 0,
        }
    }
}

impl Visitor for TreeFmtVisitor {
    type Node = AexprNode;

    /// Invoked before any children of `node` are visited.
    fn pre_visit(&mut self, node: &Self::Node) -> PolarsResult<VisitRecursion> {
        let ae = node.to_aexpr();
        let repr = format!("{:E}", ae);

        if self.levels.len() <= self.depth as usize {
            self.levels.push(vec![])
        }

        // the post-visit ensures the width of this node is known
        let row = self.levels.get_mut(self.depth as usize).unwrap();

        // set default values to ensure we format at the right width
        row.resize(self.width as usize + 1, "".to_string());
        row[self.width as usize] = repr;

        // we will enter depth first, we enter child so depth increases
        self.depth += 1;

        Ok(VisitRecursion::Continue)
    }

    fn post_visit(&mut self, _node: &Self::Node) -> PolarsResult<VisitRecursion> {
        // because we traverse depth first
        // every post-visit increases the width as we finished a depth-first branch
        self.width += 1;

        // we finished this branch so we decrease in depth, back the caller node
        self.depth -= 1;
        Ok(VisitRecursion::Continue)
    }
}

fn format_levels(f: &mut Formatter<'_>, levels: &[Vec<String>]) -> std::fmt::Result {
    let n_cols = levels.iter().map(|v| v.len()).max().unwrap();

    let mut col_widths = vec![0usize; n_cols];

    let row_idx_width = levels.len().to_string().len() + 1;
    let col_idx_width = n_cols.to_string().len();
    let space = " ";
    let dash = "─";

    for (i, col_width) in col_widths.iter_mut().enumerate() {
        *col_width = levels
            .iter()
            .map(|row| row.get(i).map(|s| s.as_str()).unwrap_or("").chars().count())
            .max()
            .map(|n| if n < col_idx_width { col_idx_width } else { n })
            .unwrap();
    }

    const COL_SPACING: usize = 2;

    for (row_count, row) in levels.iter().enumerate() {
        if row_count == 0 {
            // write the col numbers
            writeln!(f)?;
            write!(f, "{space:>row_idx_width$}  ")?;
            for (col_i, (_, col_width)) in
                levels.last().unwrap().iter().zip(&col_widths).enumerate()
            {
                let mut col_spacing = COL_SPACING;
                if col_i > 0 {
                    col_spacing *= 2;
                }
                let half = (col_spacing + 4) / 2;
                let remaining = col_spacing + 4 - half;

                // left_half
                write!(f, "{space:^half$}")?;
                // col num
                write!(f, "{col_i:^col_width$}")?;

                write!(f, "{space:^remaining$}")?;
            }
            writeln!(f)?;

            // write the horizontal line
            write!(f, "{space:>row_idx_width$} ┌")?;
            for (col_i, (_, col_width)) in
                levels.last().unwrap().iter().zip(&col_widths).enumerate()
            {
                let mut col_spacing = COL_SPACING;
                if col_i > 0 {
                    col_spacing *= 2;
                }
                write!(f, "{dash:─^width$}", width = col_width + col_spacing + 4)?;
            }
            write!(f, "\n{space:>row_idx_width$} │\n")?;
        } else {
            // write connecting lines
            write!(f, "{space:>row_idx_width$} │")?;
            let mut last_empty = true;
            let mut before = "";
            for ((col_i, col_name), col_width) in row.iter().enumerate().zip(&col_widths) {
                let mut col_spacing = COL_SPACING;
                if col_i > 0 {
                    col_spacing *= 2;
                }

                let half = (*col_width + col_spacing + 4) / 2;
                let remaining = col_width + col_spacing + 4 - half - 1;
                if last_empty {
                    // left_half
                    write!(f, "{space:^half$}")?;
                    // bar
                    if col_name.is_empty() {
                        write!(f, " ")?;
                    } else {
                        write!(f, "│")?;
                        last_empty = false;
                        before = "│";
                    }
                } else {
                    // left_half
                    write!(f, "{dash:─^half$}")?;
                    // bar
                    write!(f, "╮")?;
                    before = "╮"
                }
                if (col_i == row.len() - 1) | col_name.is_empty() {
                    write!(f, "{space:^remaining$}")?;
                } else {
                    if before == "│" {
                        write!(f, " ╰")?;
                    } else {
                        write!(f, "──")?;
                    }
                    write!(f, "{dash:─^width$}", width = remaining - 2)?;
                }
            }
            writeln!(f)?;
            // write vertical bars x 2
            for _ in 0..2 {
                write!(f, "{space:>row_idx_width$} │")?;
                for ((col_i, col_name), col_width) in row.iter().enumerate().zip(&col_widths) {
                    let mut col_spacing = COL_SPACING;
                    if col_i > 0 {
                        col_spacing *= 2;
                    }

                    let half = (*col_width + col_spacing + 4) / 2;
                    let remaining = col_width + col_spacing + 4 - half - 1;

                    // left_half
                    write!(f, "{space:^half$}")?;
                    // bar
                    let val = if col_name.is_empty() { ' ' } else { '│' };
                    write!(f, "{}", val)?;

                    write!(f, "{space:^remaining$}")?;
                }
                writeln!(f)?;
            }
        }

        // write the top of the boxes
        write!(f, "{space:>row_idx_width$} │")?;
        for (col_i, (col_repr, col_width)) in row.iter().zip(&col_widths).enumerate() {
            let mut col_spacing = COL_SPACING;
            if col_i > 0 {
                col_spacing *= 2;
            }
            let char_count = col_repr.chars().count() + 4;
            let half = (*col_width + col_spacing + 4 - char_count) / 2;
            let remaining = col_width + col_spacing + 4 - half - char_count;

            write!(f, "{space:^half$}")?;

            if !col_repr.is_empty() {
                write!(f, "╭")?;
                write!(f, "{dash:─^width$}", width = char_count - 2)?;
                write!(f, "╮")?;
            } else {
                write!(f, "    ")?;
            }
            write!(f, "{space:^remaining$}")?;
        }
        writeln!(f)?;

        // write column names and spacing
        write!(f, "{row_count:>row_idx_width$} │")?;
        for (col_i, (col_repr, col_width)) in row.iter().zip(&col_widths).enumerate() {
            let mut col_spacing = COL_SPACING;
            if col_i > 0 {
                col_spacing *= 2;
            }
            let char_count = col_repr.chars().count() + 4;
            let half = (*col_width + col_spacing + 4 - char_count) / 2;
            let remaining = col_width + col_spacing + 4 - half - char_count;

            write!(f, "{space:^half$}")?;

            if !col_repr.is_empty() {
                write!(f, "│ {} │", col_repr)?;
            } else {
                write!(f, "    ")?;
            }
            write!(f, "{space:^remaining$}")?;
        }
        writeln!(f)?;

        // write the bottom of the boxes
        write!(f, "{space:>row_idx_width$} │")?;
        for (col_i, (col_repr, col_width)) in row.iter().zip(&col_widths).enumerate() {
            let mut col_spacing = COL_SPACING;
            if col_i > 0 {
                col_spacing *= 2;
            }
            let char_count = col_repr.chars().count() + 4;
            let half = (*col_width + col_spacing + 4 - char_count) / 2;
            let remaining = col_width + col_spacing + 4 - half - char_count;

            write!(f, "{space:^half$}")?;

            if !col_repr.is_empty() {
                write!(f, "╰")?;
                write!(f, "{dash:─^width$}", width = char_count - 2)?;
                write!(f, "╯")?;
            } else {
                write!(f, "    ")?;
            }
            write!(f, "{space:^remaining$}")?;
        }
        writeln!(f)?;
    }

    Ok(())
}

impl Display for TreeFmtVisitor {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        format_levels(f, &self.levels)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::logical_plan::visitor::TreeWalker;

    #[test]
    fn test_tree_fmt_visit() {
        let e = (col("foo") * lit(2) + lit(3) + lit(43)).sum();
        let mut arena = Default::default();
        let node = to_aexpr(e, &mut arena);

        let mut visitor = TreeFmtVisitor::new();

        AexprNode::with_context(node, &mut arena, |ae_node| ae_node.visit(&mut visitor)).unwrap();
        let expected: &[&[&str]] = &[
            &["sum"],
            &["binary: +"],
            &["lit(43)", "binary: +"],
            &["", "lit(3)", "binary: *"],
            &["", "", "lit(2)", "col(foo)"],
        ];

        assert_eq!(visitor.levels, expected);
    }
}