Skip to main content

renderdag/pipeline/
graph_to_row_shape.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::collections::BTreeMap;
9use std::ops::Range;
10
11use crate::column::Column;
12use crate::column::ColumnsExt;
13use crate::pipeline::types::Ancestor;
14use crate::pipeline::types::DashStyle;
15use crate::pipeline::types::GraphRowShape;
16use crate::pipeline::types::GraphRowShapeOptions;
17use crate::pipeline::types::LinkLine;
18use crate::pipeline::types::NodeLine;
19use crate::pipeline::types::PadLine;
20
21/// Stateful renderer for the first pipeline stage.
22///
23/// It consumes a stream of `(node, parents)` entries and produces one
24/// [`GraphRowShape`] per node. The output is purely structural: it describes
25/// column placement and abstract edge shapes, without choosing glyph characters
26/// or attaching message text.
27pub struct GraphRowShaper<N> {
28    columns: Vec<Column<N>>,
29    options: GraphRowShapeOptions,
30    previous_node_column: Option<usize>,
31}
32
33impl<N> GraphRowShaper<N>
34where
35    N: Clone + Eq,
36{
37    /// Create a renderer with default graph-shape options.
38    pub fn new() -> Self {
39        Self::with_options(Default::default())
40    }
41
42    /// Create a renderer with explicit graph-shape options.
43    pub fn with_options(options: GraphRowShapeOptions) -> Self {
44        Self {
45            columns: Vec::new(),
46            options,
47            previous_node_column: None,
48        }
49    }
50
51    /// Return the graph-shape options used by this renderer.
52    pub fn options(&self) -> &GraphRowShapeOptions {
53        &self.options
54    }
55
56    /// Return mutable graph-shape options used by this renderer.
57    pub fn options_mut(&mut self) -> &mut GraphRowShapeOptions {
58        &mut self.options
59    }
60
61    /// Reserve a column for a node before it is rendered.
62    pub fn reserve(&mut self, node: N) {
63        if self.columns.find(&node).is_none() {
64            if let Some(index) = self.columns.first_empty() {
65                self.columns[index] = Column::Reserved(node);
66            } else {
67                self.columns.push(Column::Reserved(node));
68            }
69        }
70    }
71
72    /// Return the number of graph columns needed after optionally considering
73    /// the next node and its parents.
74    pub fn width(&self, node: Option<&N>, parents: Option<&Vec<Ancestor<N>>>) -> u64 {
75        self.width_with_options(node, parents, self.options)
76    }
77
78    /// Return the number of graph columns needed with explicit graph-shape
79    /// options.
80    pub fn width_with_options(
81        &self,
82        node: Option<&N>,
83        parents: Option<&Vec<Ancestor<N>>>,
84        options: GraphRowShapeOptions,
85    ) -> u64 {
86        let mut width = self.columns.len();
87        let mut empty_columns = self
88            .columns
89            .iter()
90            .filter(|&column| column == &Column::Empty)
91            .count();
92        if let Some(node) = node {
93            // If the node is not already allocated, and there is no
94            // space for the node, then adding the new node would create
95            // a new column.
96            if self.columns.find(node).is_none() {
97                if options.min_row_height <= 1 && options.stagger_consecutive_disconnected_nodes {
98                    if let Some(previous_node_column) = self.previous_node_column {
99                        if self.columns.get(previous_node_column) == Some(&Column::Empty) {
100                            // Dense stagger mode cannot use the previous node's column for an
101                            // unallocated node, so do not count that empty column as available.
102                            empty_columns = empty_columns.saturating_sub(1);
103                        } else if previous_node_column == self.columns.len() {
104                            // The previous node's column was trimmed from the end of the column
105                            // list. To keep the new node out of that column, rendering it requires
106                            // a blank placeholder column plus a new column for the node.
107                            width += 1;
108                        }
109                    }
110                }
111                if empty_columns == 0 {
112                    width += 1;
113                } else {
114                    empty_columns = empty_columns.saturating_sub(1);
115                }
116            }
117        }
118        if let Some(parents) = parents {
119            // Non-allocated parents will also need a new column (except
120            // for one, which can take the place of the node, and any that could be allocated to
121            // empty columns).
122            let unallocated_parents = parents
123                .iter()
124                .filter(|parent| {
125                    ancestor_id(parent).is_none_or(|parent| self.columns.find(parent).is_none())
126                })
127                .count()
128                .saturating_sub(empty_columns);
129            width += unallocated_parents.saturating_sub(1);
130        }
131        width as u64
132    }
133
134    /// Render the next node into an abstract graph row shape.
135    pub fn next_row_shape(&mut self, node: N, parents: Vec<Ancestor<N>>) -> GraphRowShape<N> {
136        let existing_column = self.columns.find(&node);
137        let column = existing_column.unwrap_or_else(|| self.find_column_for_unallocated_node());
138        let is_head = existing_column
139            .is_none_or(|index| matches!(self.columns.get(index), Some(Column::Reserved(_))));
140        let is_root = parents.is_empty();
141        self.columns[column] = Column::Empty;
142
143        let merge = parents.len() > 1;
144
145        let mut node_line: Vec<_> = self.columns.iter().map(column_to_node_line).collect();
146        node_line[column] = NodeLine::Node;
147
148        let mut link_line: Vec<_> = self.columns.iter().map(column_to_link_line).collect();
149        let mut link_line_from_node: Vec<_> =
150            self.columns.iter().map(|_| LinkLine::default()).collect();
151        let mut need_link_line = false;
152
153        let mut term_line: Vec<_> = self.columns.iter().map(|_| false).collect();
154        let mut need_term_line = false;
155
156        let mut ancestry_line: Vec<_> = self.columns.iter().map(column_to_pad_line).collect();
157
158        let mut parent_columns = BTreeMap::new();
159        for parent in parents.iter() {
160            if let Some(parent_id) = ancestor_id(parent) {
161                if let Some(index) = self.columns.find(parent_id) {
162                    self.columns[index].merge(&ancestor_to_column(parent));
163                    parent_columns.insert(index, parent);
164                    continue;
165                }
166            }
167
168            if let Some(index) = self.columns.find_empty(column) {
169                self.columns[index].merge(&ancestor_to_column(parent));
170                parent_columns.insert(index, parent);
171                continue;
172            }
173
174            parent_columns.insert(self.columns.len(), parent);
175            node_line.push(NodeLine::Blank);
176            ancestry_line.push(PadLine::Blank);
177            link_line.push(LinkLine::default());
178            link_line_from_node.push(LinkLine::default());
179            term_line.push(false);
180            self.columns.push(ancestor_to_column(parent));
181        }
182
183        for (index, parent) in parent_columns.iter() {
184            if ancestor_id(parent).is_none() {
185                term_line[*index] = true;
186                need_term_line = true;
187            }
188        }
189
190        let separator_line = existing_column.is_none()
191            && self.options.min_row_height <= 1
192            && !self.options.stagger_consecutive_disconnected_nodes
193            && Some(column) == self.previous_node_column
194            && !need_term_line;
195
196        if parents.len() == 1 {
197            if let Some((&parent_column, _)) = parent_columns.iter().next() {
198                if parent_column > column {
199                    self.columns.swap(column, parent_column);
200                    if let Some(parent) = parent_columns.remove(&parent_column) {
201                        parent_columns.insert(column, parent);
202                    }
203
204                    let was_direct = link_line[parent_column].contains(LinkLine::VERT_PARENT);
205                    link_both(
206                        &mut link_line,
207                        &mut link_line_from_node,
208                        column,
209                        if was_direct {
210                            LinkLine::RIGHT_FORK_PARENT
211                        } else {
212                            LinkLine::RIGHT_FORK_ANCESTOR
213                        },
214                    );
215                    #[allow(clippy::needless_range_loop)]
216                    for i in column + 1..parent_column {
217                        link_both(
218                            &mut link_line,
219                            &mut link_line_from_node,
220                            i,
221                            if was_direct {
222                                LinkLine::HORIZ_PARENT
223                            } else {
224                                LinkLine::HORIZ_ANCESTOR
225                            },
226                        );
227                    }
228                    let value = if was_direct {
229                        LinkLine::LEFT_MERGE_PARENT
230                    } else {
231                        LinkLine::LEFT_MERGE_ANCESTOR
232                    };
233                    link_line[parent_column] = value;
234                    link_line_from_node[parent_column] |= value;
235                    need_link_line = true;
236                    ancestry_line[parent_column] = PadLine::Blank;
237                }
238            }
239        }
240
241        if let Some(bounds) = AncestorColumnBounds::new(&parent_columns, column) {
242            for i in bounds.range() {
243                link_both(
244                    &mut link_line,
245                    &mut link_line_from_node,
246                    i,
247                    bounds.horizontal_line(i),
248                );
249                need_link_line = true;
250            }
251
252            if bounds.max_parent > column {
253                link_both(
254                    &mut link_line,
255                    &mut link_line_from_node,
256                    column,
257                    LinkLine::RIGHT_MERGE_PARENT,
258                );
259                need_link_line = true;
260            } else if bounds.max_ancestor > column {
261                link_both(
262                    &mut link_line,
263                    &mut link_line_from_node,
264                    column,
265                    LinkLine::RIGHT_MERGE_ANCESTOR,
266                );
267                need_link_line = true;
268            }
269
270            if bounds.min_parent < column {
271                link_both(
272                    &mut link_line,
273                    &mut link_line_from_node,
274                    column,
275                    LinkLine::LEFT_MERGE_PARENT,
276                );
277                need_link_line = true;
278            } else if bounds.min_ancestor < column {
279                link_both(
280                    &mut link_line,
281                    &mut link_line_from_node,
282                    column,
283                    LinkLine::LEFT_MERGE_ANCESTOR,
284                );
285                need_link_line = true;
286            }
287
288            #[allow(clippy::comparison_chain)]
289            for (&index, parent) in parent_columns.iter() {
290                ancestry_line[index] = column_to_pad_line(&self.columns[index]);
291                if index < column {
292                    link_both(
293                        &mut link_line,
294                        &mut link_line_from_node,
295                        index,
296                        ancestor_to_link_line(
297                            parent,
298                            LinkLine::RIGHT_FORK_PARENT,
299                            LinkLine::RIGHT_FORK_ANCESTOR,
300                        ),
301                    );
302                } else if index == column {
303                    link_both(
304                        &mut link_line,
305                        &mut link_line_from_node,
306                        index,
307                        LinkLine::CHILD
308                            | ancestor_to_link_line(
309                                parent,
310                                LinkLine::VERT_PARENT,
311                                LinkLine::VERT_ANCESTOR,
312                            ),
313                    );
314                } else {
315                    link_both(
316                        &mut link_line,
317                        &mut link_line_from_node,
318                        index,
319                        ancestor_to_link_line(
320                            parent,
321                            LinkLine::LEFT_FORK_PARENT,
322                            LinkLine::LEFT_FORK_ANCESTOR,
323                        ),
324                    );
325                }
326            }
327        }
328
329        if self.options.graph_row_shape_style.dash_style == DashStyle::Once {
330            self.columns.convert_ancestor_to_parent();
331        }
332        self.columns.reset();
333        self.previous_node_column = Some(column);
334
335        GraphRowShape {
336            node,
337            merge,
338            is_head,
339            is_root,
340            style: self.options.graph_row_shape_style,
341            node_column: column,
342            parent_columns: parent_columns.keys().copied().collect(),
343            node_line,
344            link_line: Some(link_line).filter(|_| need_link_line),
345            link_line_from_node: Some(link_line_from_node).filter(|_| need_link_line),
346            term_line: Some(term_line).filter(|_| need_term_line),
347            ancestry_line,
348            separator_line,
349        }
350    }
351
352    fn find_column_for_unallocated_node(&mut self) -> usize {
353        if self.options.min_row_height <= 1 && self.options.stagger_consecutive_disconnected_nodes {
354            if let Some(index) = self.columns.iter().enumerate().find_map(|(index, column)| {
355                (*column == Column::Empty && Some(index) != self.previous_node_column)
356                    .then_some(index)
357            }) {
358                index
359            } else {
360                if self.previous_node_column == Some(self.columns.len()) {
361                    self.columns.push(Column::Empty);
362                }
363                self.columns.new_empty()
364            }
365        } else {
366            self.columns
367                .first_empty()
368                .unwrap_or_else(|| self.columns.new_empty())
369        }
370    }
371}
372
373impl<N> Default for GraphRowShaper<N>
374where
375    N: Clone + Eq,
376{
377    fn default() -> Self {
378        Self::new()
379    }
380}
381
382struct AncestorColumnBounds {
383    target: usize,
384    min_ancestor: usize,
385    min_parent: usize,
386    max_parent: usize,
387    max_ancestor: usize,
388}
389
390impl AncestorColumnBounds {
391    fn new<N>(columns: &BTreeMap<usize, &Ancestor<N>>, target: usize) -> Option<Self> {
392        if columns.is_empty() {
393            return None;
394        }
395        let min_ancestor = columns
396            .iter()
397            .next()
398            .map_or(target, |(index, _)| *index)
399            .min(target);
400        let max_ancestor = columns
401            .iter()
402            .next_back()
403            .map_or(target, |(index, _)| *index)
404            .max(target);
405        let min_parent = columns
406            .iter()
407            .find(|(_, ancestor)| ancestor_is_direct(ancestor))
408            .map_or(target, |(index, _)| *index)
409            .min(target);
410        let max_parent = columns
411            .iter()
412            .rev()
413            .find(|(_, ancestor)| ancestor_is_direct(ancestor))
414            .map_or(target, |(index, _)| *index)
415            .max(target);
416        Some(Self {
417            target,
418            min_ancestor,
419            min_parent,
420            max_parent,
421            max_ancestor,
422        })
423    }
424
425    fn range(&self) -> Range<usize> {
426        if self.min_ancestor < self.max_ancestor {
427            self.min_ancestor + 1..self.max_ancestor
428        } else {
429            Default::default()
430        }
431    }
432
433    fn horizontal_line(&self, index: usize) -> LinkLine {
434        if index == self.target {
435            LinkLine::empty()
436        } else if index > self.min_parent && index < self.max_parent {
437            LinkLine::HORIZ_PARENT
438        } else if index > self.min_ancestor && index < self.max_ancestor {
439            LinkLine::HORIZ_ANCESTOR
440        } else {
441            LinkLine::empty()
442        }
443    }
444}
445
446// Update both link_line and link_line_from_node.
447fn link_both(
448    link_line: &mut [LinkLine],
449    link_line_from_node: &mut [LinkLine],
450    index: usize,
451    value: LinkLine,
452) {
453    link_line[index] |= value;
454    link_line_from_node[index] |= value;
455}
456
457fn ancestor_to_column<N>(ancestor: &Ancestor<N>) -> Column<N>
458where
459    N: Clone,
460{
461    match ancestor {
462        Ancestor::Ancestor(node) => Column::Ancestor(node.clone()),
463        Ancestor::Parent(node) => Column::Parent(node.clone()),
464        Ancestor::Anonymous => Column::Blocked,
465    }
466}
467
468fn ancestor_id<N>(ancestor: &Ancestor<N>) -> Option<&N> {
469    match ancestor {
470        Ancestor::Ancestor(node) => Some(node),
471        Ancestor::Parent(node) => Some(node),
472        Ancestor::Anonymous => None,
473    }
474}
475
476fn ancestor_is_direct<N>(ancestor: &Ancestor<N>) -> bool {
477    match ancestor {
478        Ancestor::Ancestor(_) => false,
479        Ancestor::Parent(_) => true,
480        Ancestor::Anonymous => true,
481    }
482}
483
484fn ancestor_to_link_line<N>(
485    ancestor: &Ancestor<N>,
486    direct: LinkLine,
487    indirect: LinkLine,
488) -> LinkLine {
489    if ancestor_is_direct(ancestor) {
490        direct
491    } else {
492        indirect
493    }
494}
495
496fn column_to_node_line<N>(column: &Column<N>) -> NodeLine {
497    match column {
498        Column::Ancestor(_) => NodeLine::Ancestor,
499        Column::Parent(_) => NodeLine::Parent,
500        _ => NodeLine::Blank,
501    }
502}
503
504fn column_to_link_line<N>(column: &Column<N>) -> LinkLine {
505    match column {
506        Column::Ancestor(_) => LinkLine::VERT_ANCESTOR,
507        Column::Parent(_) => LinkLine::VERT_PARENT,
508        _ => LinkLine::empty(),
509    }
510}
511
512fn column_to_pad_line<N>(column: &Column<N>) -> PadLine {
513    match column {
514        Column::Ancestor(_) => PadLine::Ancestor,
515        Column::Parent(_) => PadLine::Parent,
516        _ => PadLine::Blank,
517    }
518}