File size: 3,423 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{env, sync::Arc};

use hashbrown::HashMap;

use crate::{
    span::{SpanBottomUp, SpanIndex},
    span_ref::SpanRef,
    string_tuple_ref::StringTupleRef,
};

pub struct SpanBottomUpBuilder {
    // These values won't change after creation:
    pub self_spans: Vec<SpanIndex>,
    pub children: HashMap<(String, String), SpanBottomUpBuilder>,
    pub example_span: SpanIndex,
}

impl SpanBottomUpBuilder {
    pub fn new(example_span: SpanIndex) -> Self {
        Self {
            self_spans: vec![],
            children: HashMap::default(),
            example_span,
        }
    }

    pub fn build(self) -> SpanBottomUp {
        SpanBottomUp::new(
            self.self_spans,
            self.example_span,
            self.children
                .into_values()
                .map(|child| Arc::new(child.build()))
                .collect(),
        )
    }
}

pub fn build_bottom_up_graph<'a>(
    spans: impl Iterator<Item = SpanRef<'a>>,
) -> Vec<Arc<SpanBottomUp>> {
    let max_depth = env::var("BOTTOM_UP_DEPTH")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(usize::MAX);
    let mut roots: HashMap<(String, String), SpanBottomUpBuilder> = HashMap::default();

    // unfortunately there is a rustc bug that fails the typechecking here
    // when using Either<impl Iterator, impl Iterator>. This error appears
    // in certain cases when building next-swc.
    //
    // see here: https://github.com/rust-lang/rust/issues/124891
    let mut current_iterators: Vec<Box<dyn Iterator<Item = SpanRef<'_>>>> =
        vec![Box::new(spans.flat_map(|span| span.children()))];

    let mut current_path: Vec<((&'_ str, &'_ str), SpanIndex)> = vec![];
    while let Some(mut iter) = current_iterators.pop() {
        if let Some(child) = iter.next() {
            current_iterators.push(iter);

            let (category, name) = child.group_name();
            let (_, mut bottom_up) = roots
                .raw_entry_mut()
                .from_key(&StringTupleRef(category, name))
                .or_insert_with(|| {
                    (
                        (category.to_string(), name.to_string()),
                        SpanBottomUpBuilder::new(child.index()),
                    )
                });
            bottom_up.self_spans.push(child.index());
            let mut prev = None;
            for &((category, title), example_span) in current_path.iter().rev().take(max_depth) {
                if prev == Some((category, title)) {
                    continue;
                }
                let (_, child_bottom_up) = bottom_up
                    .children
                    .raw_entry_mut()
                    .from_key(&StringTupleRef(category, title))
                    .or_insert_with(|| {
                        (
                            (category.to_string(), title.to_string()),
                            SpanBottomUpBuilder::new(example_span),
                        )
                    });
                child_bottom_up.self_spans.push(child.index());
                bottom_up = child_bottom_up;
                prev = Some((category, title));
            }

            current_path.push((child.group_name(), child.index()));
            current_iterators.push(Box::new(child.children()));
        } else {
            current_path.pop();
        }
    }
    roots.into_values().map(|b| Arc::new(b.build())).collect()
}