Skip to main content

layout/table/
construct.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::iter::repeat_n;
6
7use atomic_refcell::AtomicRef;
8use layout_api::LayoutNode;
9use log::warn;
10use servo_arc::Arc;
11use style::properties::ComputedValues;
12use style::properties::style_structs::Font;
13use style::selector_parser::PseudoElement;
14use style::str::char_is_whitespace;
15
16use super::{
17    Table, TableCaption, TableLevelBox, TableSlot, TableSlotCell, TableSlotCoordinates,
18    TableSlotOffset, TableTrack, TableTrackGroup, TableTrackGroupType,
19};
20use crate::cell::ArcRefCell;
21use crate::context::LayoutContext;
22use crate::dom::{BoxSlot, LayoutBox, NodeExt};
23use crate::dom_traversal::{
24    BoxTreeString, Contents, NodeAndStyleInfo, NonReplacedContents, TraversalHandler,
25};
26use crate::flow::inline::SharedInlineStyles;
27use crate::flow::{BlockContainerBuilder, BlockFormattingContext};
28use crate::formatting_contexts::{
29    IndependentFormattingContext, IndependentFormattingContextContents,
30};
31use crate::fragment_tree::BaseFragmentInfo;
32use crate::layout_box_base::LayoutBoxBase;
33use crate::style_ext::{DisplayGeneratingBox, DisplayLayoutInternal};
34use crate::{PropagatedBoxTreeData, SharedStyle};
35
36/// A reference to a slot and its coordinates in the table
37#[derive(Debug)]
38pub(super) struct ResolvedSlotAndLocation<'a> {
39    pub cell: AtomicRef<'a, TableSlotCell>,
40    pub coords: TableSlotCoordinates,
41}
42
43impl ResolvedSlotAndLocation<'_> {
44    fn covers_cell_at(&self, coords: TableSlotCoordinates) -> bool {
45        let covered_in_x =
46            coords.x >= self.coords.x && coords.x < self.coords.x + self.cell.colspan;
47        let covered_in_y = coords.y >= self.coords.y &&
48            (self.cell.rowspan == 0 || coords.y < self.coords.y + self.cell.rowspan);
49        covered_in_x && covered_in_y
50    }
51}
52
53pub(crate) struct AnonymousTableContentElement<'dom> {
54    pub(crate) info: NodeAndStyleInfo<'dom>,
55    pub(crate) display: DisplayGeneratingBox,
56    pub(crate) contents: Contents,
57    pub(crate) box_slot: BoxSlot<'dom>,
58}
59
60pub(crate) enum AnonymousTableContent<'dom> {
61    Text(NodeAndStyleInfo<'dom>, BoxTreeString<'dom>),
62    EnterDisplayContents(SharedInlineStyles),
63    LeaveDisplayContents,
64    Element(Box<AnonymousTableContentElement<'dom>>),
65}
66
67impl AnonymousTableContent<'_> {
68    fn is_whitespace_only(&self) -> bool {
69        match self {
70            Self::Element { .. } => false,
71            Self::Text(_, text) => text.chars().all(char_is_whitespace),
72            Self::EnterDisplayContents(_) | Self::LeaveDisplayContents => true,
73        }
74    }
75
76    // If all contents are whitespace only, it removes them except for unclosed
77    // EnterDisplayContents, and returns true. Otherwise, it returns false.
78    fn remove_whitespace_only(contents: &mut Vec<Self>) -> bool {
79        if !contents.iter().all(Self::is_whitespace_only) {
80            return false;
81        }
82        let mut enter_display_contents = vec![];
83        for content in contents.drain(..) {
84            match content {
85                AnonymousTableContent::EnterDisplayContents(_) => {
86                    enter_display_contents.push(content);
87                },
88                AnonymousTableContent::LeaveDisplayContents => {
89                    enter_display_contents.pop();
90                },
91                _ => {},
92            }
93        }
94        std::mem::swap(contents, &mut enter_display_contents);
95        true
96    }
97}
98
99impl Table {
100    pub(crate) fn construct(
101        context: &LayoutContext,
102        info: &NodeAndStyleInfo,
103        grid_style: Arc<ComputedValues>,
104        contents: NonReplacedContents,
105        propagated_data: PropagatedBoxTreeData,
106    ) -> Self {
107        let mut traversal = TableBuilderTraversal::new(context, info, grid_style, propagated_data);
108        contents.traverse(context, info, &mut traversal);
109        traversal.finish()
110    }
111
112    pub(crate) fn construct_anonymous<'dom>(
113        context: &LayoutContext,
114        parent: &mut impl TraversalHandler<'dom>,
115        parent_info: &NodeAndStyleInfo<'dom>,
116        contents: Vec<AnonymousTableContent<'dom>>,
117        propagated_data: PropagatedBoxTreeData,
118    ) -> (NodeAndStyleInfo<'dom>, IndependentFormattingContext) {
119        let table_info = parent_info
120            .with_pseudo_element(context, PseudoElement::ServoAnonymousTable)
121            .expect("Should never fail to create anonymous table info.");
122        let table_style = table_info.style.clone();
123        let mut table_builder =
124            TableBuilderTraversal::new(context, &table_info, table_style.clone(), propagated_data);
125
126        for content in contents {
127            match content {
128                AnonymousTableContent::Element(element) => {
129                    table_builder.handle_element(
130                        &element.info,
131                        element.display,
132                        element.contents,
133                        element.box_slot,
134                    );
135                },
136                AnonymousTableContent::Text(..) => {
137                    // This only happens if there was whitespace between our internal table elements.
138                    // We only collect that whitespace in case we need to re-emit trailing whitespace
139                    // after we've added our anonymous table.
140                },
141                // Since the table builder skips text, we don't have to handle `display: contents` there.
142                // But we need to handle it for the parent builder, because it may contain trailing
143                // whitespace which won't be placed inside the table.
144                AnonymousTableContent::EnterDisplayContents(styles) => {
145                    parent.enter_display_contents(styles)
146                },
147                AnonymousTableContent::LeaveDisplayContents => parent.leave_display_contents(),
148            }
149        }
150
151        let mut table = table_builder.finish();
152        table.anonymous = true;
153
154        let ifc = IndependentFormattingContext::new(
155            LayoutBoxBase::new((&table_info).into(), table_style),
156            IndependentFormattingContextContents::Table(table),
157            propagated_data,
158        );
159
160        (table_info, ifc)
161    }
162
163    /// Push a new slot into the last row of this table.
164    fn push_new_slot_to_last_row(&mut self, slot: TableSlot) {
165        let last_row = match self.slots.last_mut() {
166            Some(row) => row,
167            None => {
168                unreachable!("Should have some rows before calling `push_new_slot_to_last_row`")
169            },
170        };
171
172        self.size.width = self.size.width.max(last_row.len() + 1);
173        last_row.push(slot);
174    }
175
176    /// Find [`ResolvedSlotAndLocation`] of all the slots that cover the slot at the given
177    /// coordinates. This recursively resolves all of the [`TableSlotCell`]s that cover
178    /// the target and returns a [`ResolvedSlotAndLocation`] for each of them. If there is
179    /// no slot at the given coordinates or that slot is an empty space, an empty vector
180    /// is returned.
181    pub(super) fn resolve_slot_at(
182        &self,
183        coords: TableSlotCoordinates,
184    ) -> Vec<ResolvedSlotAndLocation<'_>> {
185        let slot = self.get_slot(coords);
186        match slot {
187            Some(TableSlot::Cell(cell)) => vec![ResolvedSlotAndLocation {
188                cell: cell.borrow(),
189                coords,
190            }],
191            Some(TableSlot::Spanned(offsets)) => offsets
192                .iter()
193                .flat_map(|offset| self.resolve_slot_at(coords - *offset))
194                .collect(),
195            Some(TableSlot::Empty) | None => {
196                warn!("Tried to resolve an empty or nonexistant slot!");
197                vec![]
198            },
199        }
200    }
201}
202
203impl TableSlot {
204    /// Merge a TableSlot::Spanned(x, y) with this (only for model errors)
205    pub fn push_spanned(&mut self, new_offset: TableSlotOffset) {
206        match *self {
207            TableSlot::Cell { .. } => {
208                panic!(
209                    "Should never have a table model error with an originating cell slot overlapping a spanned slot"
210                )
211            },
212            TableSlot::Spanned(ref mut vec) => vec.insert(0, new_offset),
213            TableSlot::Empty => {
214                panic!("Should never have a table model error with an empty slot");
215            },
216        }
217    }
218}
219
220pub struct TableBuilder {
221    /// The table that we are building.
222    table: Table,
223
224    /// An incoming rowspan is a value indicating that a cell in a row above the current row,
225    /// had a rowspan value other than 1. The values in this array indicate how many more
226    /// rows the cell should span. For example, a value of 0 at an index before `current_x()`
227    /// indicates that the cell on that column will not span into the next row, and at an index
228    /// after `current_x()` it indicates that the cell will not span into the current row.
229    /// A negative value means that the cell will span all remaining rows in the row group.
230    ///
231    /// As each column in a row is processed, the values in this vector are updated for the
232    /// next row.
233    pub incoming_rowspans: Vec<isize>,
234}
235
236impl TableBuilder {
237    pub(super) fn new(
238        style: Arc<ComputedValues>,
239        grid_style: Arc<ComputedValues>,
240        base_fragment_info: BaseFragmentInfo,
241        percentage_columns_allowed_for_inline_content_sizes: bool,
242    ) -> Self {
243        Self {
244            table: Table::new(
245                style,
246                grid_style,
247                base_fragment_info,
248                percentage_columns_allowed_for_inline_content_sizes,
249            ),
250            incoming_rowspans: Vec::new(),
251        }
252    }
253
254    pub fn new_for_tests() -> Self {
255        let testing_style =
256            ComputedValues::initial_values_with_font_override(Font::initial_values());
257        Self::new(
258            testing_style.clone(),
259            testing_style,
260            BaseFragmentInfo::anonymous(),
261            true, /* percentage_columns_allowed_for_inline_content_sizes */
262        )
263    }
264
265    pub fn last_row_index_in_row_group_at_row_n(&self, n: usize) -> usize {
266        // TODO: This is just a linear search, because the idea is that there are
267        // generally less than or equal to three row groups, but if we notice a lot
268        // of web content with more, we can consider a binary search here.
269        for row_group in self.table.row_groups.iter() {
270            let row_group = row_group.borrow();
271            if row_group.track_range.start > n {
272                return row_group.track_range.start - 1;
273            }
274        }
275        self.table.size.height - 1
276    }
277
278    pub fn finish(mut self) -> Table {
279        self.adjust_table_geometry_for_columns_and_colgroups();
280        self.do_missing_cells_fixup();
281        self.reorder_first_thead_and_tfoot();
282        self.do_final_rowspan_calculation();
283        self.table
284    }
285
286    /// Do <https://drafts.csswg.org/css-tables/#missing-cells-fixup> which ensures
287    /// that every row has the same number of cells.
288    fn do_missing_cells_fixup(&mut self) {
289        for row in self.table.slots.iter_mut() {
290            row.resize_with(self.table.size.width, || TableSlot::Empty);
291        }
292    }
293
294    /// It's possible to define more table columns via `<colgroup>` and `<col>` elements
295    /// than actually exist in the table. In that case, increase the size of the table.
296    ///
297    /// However, if the table has no row nor row group, remove the extra columns instead.
298    /// This matches WebKit, and some tests require it, but Gecko and Blink don't do it.
299    fn adjust_table_geometry_for_columns_and_colgroups(&mut self) {
300        if self.table.rows.is_empty() && self.table.row_groups.is_empty() {
301            self.table.columns.clear();
302            self.table.column_groups.clear();
303        } else {
304            self.table.size.width = self.table.size.width.max(self.table.columns.len());
305        }
306    }
307
308    /// Reorder the first `<thead>` and `<tbody>` to be the first and last row groups respectively.
309    /// This requires fixing up all row group indices.
310    /// See <https://drafts.csswg.org/css-tables/#table-header-group> and
311    /// <https://drafts.csswg.org/css-tables/#table-footer-group>.
312    fn reorder_first_thead_and_tfoot(&mut self) {
313        let mut thead_index = None;
314        let mut tfoot_index = None;
315        for (row_group_index, row_group) in self.table.row_groups.iter().enumerate() {
316            let row_group = row_group.borrow();
317            if thead_index.is_none() && row_group.group_type == TableTrackGroupType::HeaderGroup {
318                thead_index = Some(row_group_index);
319            }
320            if tfoot_index.is_none() && row_group.group_type == TableTrackGroupType::FooterGroup {
321                tfoot_index = Some(row_group_index);
322            }
323            if thead_index.is_some() && tfoot_index.is_some() {
324                break;
325            }
326        }
327
328        if let Some(thead_index) = thead_index {
329            self.move_row_group_to_front(thead_index)
330        }
331
332        if let Some(mut tfoot_index) = tfoot_index {
333            // We may have moved a `<thead>` which means the original index we
334            // we found for this this <tfoot>` also needs to be updated!
335            if thead_index.unwrap_or(0) > tfoot_index {
336                tfoot_index += 1;
337            }
338            self.move_row_group_to_end(tfoot_index)
339        }
340    }
341
342    fn regenerate_track_ranges(&mut self) {
343        // Now update all track group ranges.
344        let mut current_row_group_index = None;
345        for (row_index, row) in self.table.rows.iter().enumerate() {
346            let row = row.borrow();
347            if current_row_group_index == row.group_index {
348                continue;
349            }
350
351            // Finish any row group that is currently being processed.
352            if let Some(current_group_index) = current_row_group_index {
353                self.table.row_groups[current_group_index]
354                    .borrow_mut()
355                    .track_range
356                    .end = row_index;
357            }
358
359            // Start processing this new row group and update its starting index.
360            current_row_group_index = row.group_index;
361            if let Some(current_group_index) = current_row_group_index {
362                self.table.row_groups[current_group_index]
363                    .borrow_mut()
364                    .track_range
365                    .start = row_index;
366            }
367        }
368
369        // Finish the last row group.
370        if let Some(current_group_index) = current_row_group_index {
371            self.table.row_groups[current_group_index]
372                .borrow_mut()
373                .track_range
374                .end = self.table.rows.len();
375        }
376    }
377
378    fn move_row_group_to_front(&mut self, index_to_move: usize) {
379        // Move the group itself.
380        if index_to_move > 0 {
381            let removed_row_group = self.table.row_groups.remove(index_to_move);
382            self.table.row_groups.insert(0, removed_row_group);
383
384            for row in self.table.rows.iter_mut() {
385                let mut row = row.borrow_mut();
386                match row.group_index.as_mut() {
387                    Some(group_index) if *group_index < index_to_move => *group_index += 1,
388                    Some(group_index) if *group_index == index_to_move => *group_index = 0,
389                    _ => {},
390                }
391            }
392        }
393
394        let row_range = self.table.row_groups[0].borrow().track_range.clone();
395        if row_range.start > 0 {
396            // Move the slots associated with the moved group.
397            let removed_slots: Vec<Vec<TableSlot>> = self
398                .table
399                .slots
400                .splice(row_range.clone(), std::iter::empty())
401                .collect();
402            self.table.slots.splice(0..0, removed_slots);
403
404            // Move the rows associated with the moved group.
405            let removed_rows: Vec<_> = self
406                .table
407                .rows
408                .splice(row_range, std::iter::empty())
409                .collect();
410            self.table.rows.splice(0..0, removed_rows);
411
412            // Do this now, rather than after possibly moving a `<tfoot>` row group to the end,
413            // because moving row groups depends on an accurate `track_range` in every group.
414            self.regenerate_track_ranges();
415        }
416    }
417
418    fn move_row_group_to_end(&mut self, index_to_move: usize) {
419        let last_row_group_index = self.table.row_groups.len() - 1;
420
421        // Move the group itself.
422        if index_to_move < last_row_group_index {
423            let removed_row_group = self.table.row_groups.remove(index_to_move);
424            self.table.row_groups.push(removed_row_group);
425
426            for row in self.table.rows.iter_mut() {
427                let mut row = row.borrow_mut();
428                match row.group_index.as_mut() {
429                    Some(group_index) if *group_index > index_to_move => *group_index -= 1,
430                    Some(group_index) if *group_index == index_to_move => {
431                        *group_index = last_row_group_index
432                    },
433                    _ => {},
434                }
435            }
436        }
437
438        let row_range = self.table.row_groups[last_row_group_index]
439            .borrow()
440            .track_range
441            .clone();
442        if row_range.end < self.table.rows.len() {
443            // Move the slots associated with the moved group.
444            let removed_slots: Vec<Vec<TableSlot>> = self
445                .table
446                .slots
447                .splice(row_range.clone(), std::iter::empty())
448                .collect();
449            self.table.slots.extend(removed_slots);
450
451            // Move the rows associated with the moved group.
452            let removed_rows: Vec<_> = self
453                .table
454                .rows
455                .splice(row_range, std::iter::empty())
456                .collect();
457            self.table.rows.extend(removed_rows);
458
459            self.regenerate_track_ranges();
460        }
461    }
462
463    /// Turn all rowspan=0 rows into the real value to avoid having to make the calculation
464    /// continually during layout. In addition, make sure that there are no rowspans that extend
465    /// past the end of their row group.
466    fn do_final_rowspan_calculation(&mut self) {
467        for row_index in 0..self.table.size.height {
468            let last_row_index_in_group = self.last_row_index_in_row_group_at_row_n(row_index);
469            for cell in self.table.slots[row_index].iter_mut() {
470                if let TableSlot::Cell(cell) = cell {
471                    let mut cell = cell.borrow_mut();
472                    if cell.rowspan == 1 {
473                        continue;
474                    }
475                    let rowspan_to_end_of_group = last_row_index_in_group - row_index + 1;
476                    if cell.rowspan == 0 {
477                        cell.rowspan = rowspan_to_end_of_group;
478                    } else {
479                        cell.rowspan = cell.rowspan.min(rowspan_to_end_of_group);
480                    }
481                }
482            }
483        }
484    }
485
486    fn current_y(&self) -> Option<usize> {
487        self.table.slots.len().checked_sub(1)
488    }
489
490    fn current_x(&self) -> Option<usize> {
491        Some(self.table.slots[self.current_y()?].len())
492    }
493
494    fn current_coords(&self) -> Option<TableSlotCoordinates> {
495        Some(TableSlotCoordinates::new(
496            self.current_x()?,
497            self.current_y()?,
498        ))
499    }
500
501    pub fn start_row(&mut self) {
502        self.table.slots.push(Vec::new());
503        self.table.size.height += 1;
504        self.create_slots_for_cells_above_with_rowspan(true);
505    }
506
507    pub fn end_row(&mut self) {
508        // TODO: We need to insert a cell for any leftover non-table-like
509        // content in the TableRowBuilder.
510
511        // Truncate entries that are zero at the end of [`Self::incoming_rowspans`]. This
512        // prevents padding the table with empty cells when it isn't necessary.
513        let current_x = self
514            .current_x()
515            .expect("Should have rows before calling `end_row`");
516        for i in (current_x..self.incoming_rowspans.len()).rev() {
517            if self.incoming_rowspans[i] == 0 {
518                self.incoming_rowspans.pop();
519            } else {
520                break;
521            }
522        }
523
524        self.create_slots_for_cells_above_with_rowspan(false);
525    }
526
527    /// Create a [`TableSlot::Spanned`] for the target cell at the given coordinates. If
528    /// no slots cover the target, then this returns [`None`]. Note: This does not handle
529    /// slots that cover the target using `colspan`, but instead only considers slots that
530    /// cover this slot via `rowspan`. `colspan` should be handled by appending to the
531    /// return value of this function.
532    fn create_spanned_slot_based_on_cell_above(
533        &self,
534        target_coords: TableSlotCoordinates,
535    ) -> Option<TableSlot> {
536        let y_above = self.current_y()?.checked_sub(1)?;
537        let coords_for_slot_above = TableSlotCoordinates::new(target_coords.x, y_above);
538        let slots_covering_slot_above = self.table.resolve_slot_at(coords_for_slot_above);
539
540        let coords_of_slots_that_cover_target: Vec<_> = slots_covering_slot_above
541            .into_iter()
542            .filter(|slot| slot.covers_cell_at(target_coords))
543            .map(|slot| target_coords - slot.coords)
544            .collect();
545
546        if coords_of_slots_that_cover_target.is_empty() {
547            None
548        } else {
549            Some(TableSlot::Spanned(coords_of_slots_that_cover_target))
550        }
551    }
552
553    /// When not in the process of filling a cell, make sure any incoming rowspans are
554    /// filled so that the next specified cell comes after them. Should have been called before
555    /// [`Self::add_cell`]
556    ///
557    /// if `stop_at_cell_opportunity` is set, this will stop at the first slot with
558    /// `incoming_rowspans` equal to zero. If not, it will insert [`TableSlot::Empty`] and
559    /// continue to look for more incoming rowspans (which should only be done once we're
560    /// finished processing the cells in a row, and after calling truncating cells with
561    /// remaining rowspan from the end of `incoming_rowspans`.
562    fn create_slots_for_cells_above_with_rowspan(&mut self, stop_at_cell_opportunity: bool) {
563        let mut current_coords = self
564            .current_coords()
565            .expect("Should have rows before calling `create_slots_for_cells_above_with_rowspan`");
566        while let Some(span) = self.incoming_rowspans.get_mut(current_coords.x) {
567            // This column has no incoming rowspanned cells and `stop_at_zero` is true, so
568            // we should stop to process new cells defined in the current row.
569            if *span == 0 && stop_at_cell_opportunity {
570                break;
571            }
572
573            let new_cell = if *span != 0 {
574                *span -= 1;
575                self.create_spanned_slot_based_on_cell_above(current_coords)
576                    .expect(
577                        "Nonzero incoming rowspan cannot occur without a cell spanning this slot",
578                    )
579            } else {
580                TableSlot::Empty
581            };
582
583            self.table.push_new_slot_to_last_row(new_cell);
584            current_coords.x += 1;
585        }
586        debug_assert_eq!(Some(current_coords), self.current_coords());
587    }
588
589    /// <https://html.spec.whatwg.org/multipage/#algorithm-for-processing-rows>
590    /// Push a single cell onto the slot map, handling any colspans it may have, and
591    /// setting up the outgoing rowspans.
592    pub fn add_cell(&mut self, cell: ArcRefCell<TableSlotCell>) {
593        // Make sure the incoming_rowspans table is large enough
594        // because we will be writing to it.
595        let current_coords = self
596            .current_coords()
597            .expect("Should have rows before calling `add_cell`");
598
599        let (colspan, rowspan) = {
600            let cell = cell.borrow();
601            (cell.colspan, cell.rowspan)
602        };
603
604        if self.incoming_rowspans.len() < current_coords.x + colspan {
605            self.incoming_rowspans
606                .resize(current_coords.x + colspan, 0isize);
607        }
608
609        debug_assert_eq!(
610            self.incoming_rowspans[current_coords.x], 0,
611            "Added a cell in a position that also had an incoming rowspan!"
612        );
613
614        // If `rowspan` is zero, this is automatically negative and will stay negative.
615        let outgoing_rowspan = rowspan as isize - 1;
616        self.table.push_new_slot_to_last_row(TableSlot::Cell(cell));
617        self.incoming_rowspans[current_coords.x] = outgoing_rowspan;
618
619        // Draw colspanned cells
620        for colspan_offset in 1..colspan {
621            let current_x_plus_colspan_offset = current_coords.x + colspan_offset;
622            let new_offset = TableSlotOffset::new(colspan_offset, 0);
623            let incoming_rowspan = &mut self.incoming_rowspans[current_x_plus_colspan_offset];
624            let new_slot = if *incoming_rowspan == 0 {
625                *incoming_rowspan = outgoing_rowspan;
626                TableSlot::new_spanned(new_offset)
627            } else {
628                // This means we have a table model error.
629
630                // if `incoming_rowspan` is greater than zero, a cell from above is spanning
631                // into our row, colliding with the cells we are creating via colspan. In
632                // that case, set the incoming rowspan to the highest of two possible
633                // outgoing rowspan values (the incoming rowspan minus one, OR this cell's
634                // outgoing rowspan).  `spanned_slot()`` will handle filtering out
635                // inapplicable spans when it needs to.
636                //
637                // If the `incoming_rowspan` is negative we are in `rowspan=0` mode, (i.e.
638                // rowspan=infinity), so we don't have to worry about the current cell
639                // making it larger. In that case, don't change the rowspan.
640                if *incoming_rowspan > 0 {
641                    *incoming_rowspan = std::cmp::max(*incoming_rowspan - 1, outgoing_rowspan);
642                }
643
644                // This code creates a new slot in the case that there is a table model error.
645                let coords_of_spanned_cell =
646                    TableSlotCoordinates::new(current_x_plus_colspan_offset, current_coords.y);
647                let mut incoming_slot = self
648                    .create_spanned_slot_based_on_cell_above(coords_of_spanned_cell)
649                    .expect(
650                        "Nonzero incoming rowspan cannot occur without a cell spanning this slot",
651                    );
652                incoming_slot.push_spanned(new_offset);
653                incoming_slot
654            };
655            self.table.push_new_slot_to_last_row(new_slot);
656        }
657
658        debug_assert_eq!(
659            Some(TableSlotCoordinates::new(
660                current_coords.x + colspan,
661                current_coords.y
662            )),
663            self.current_coords(),
664            "Must have produced `colspan` slot entries!"
665        );
666        self.create_slots_for_cells_above_with_rowspan(true);
667    }
668}
669
670pub(crate) struct TableBuilderTraversal<'style, 'dom> {
671    context: &'style LayoutContext<'style>,
672    info: &'style NodeAndStyleInfo<'dom>,
673
674    /// The value of the [`PropagatedBoxTreeData`] to use, either for the row group
675    /// if processing one or for the table itself if outside a row group.
676    current_propagated_data: PropagatedBoxTreeData,
677
678    /// The [`TableBuilder`] for this [`TableBuilderTraversal`]. This is separated
679    /// into another struct so that we can write unit tests against the builder.
680    builder: TableBuilder,
681
682    current_anonymous_row_content: Vec<AnonymousTableContent<'dom>>,
683
684    /// The index of the current row group, if there is one.
685    current_row_group_index: Option<usize>,
686}
687
688impl<'style, 'dom> TableBuilderTraversal<'style, 'dom> {
689    pub(crate) fn new(
690        context: &'style LayoutContext<'style>,
691        info: &'style NodeAndStyleInfo<'dom>,
692        grid_style: Arc<ComputedValues>,
693        propagated_data: PropagatedBoxTreeData,
694    ) -> Self {
695        TableBuilderTraversal {
696            context,
697            info,
698            current_propagated_data: propagated_data,
699            builder: TableBuilder::new(
700                info.style.clone(),
701                grid_style,
702                info.into(),
703                propagated_data.allow_percentage_column_in_tables,
704            ),
705            current_anonymous_row_content: Vec::new(),
706            current_row_group_index: None,
707        }
708    }
709
710    pub(crate) fn finish(mut self) -> Table {
711        self.finish_anonymous_row_if_needed();
712        self.builder.finish()
713    }
714
715    fn finish_anonymous_row_if_needed(&mut self) {
716        if AnonymousTableContent::remove_whitespace_only(&mut self.current_anonymous_row_content) {
717            return;
718        }
719        let row_content = std::mem::take(&mut self.current_anonymous_row_content);
720        let anonymous_info = self
721            .info
722            .with_pseudo_element(self.context, PseudoElement::ServoAnonymousTableRow)
723            .expect("Should never fail to create anonymous row info.");
724        let mut row_builder =
725            TableRowBuilder::new(self, &anonymous_info, self.current_propagated_data);
726
727        let mut enter_display_contents = vec![];
728        for cell_content in row_content {
729            match cell_content {
730                AnonymousTableContent::Element(element) => {
731                    row_builder.handle_element(
732                        &element.info,
733                        element.display,
734                        element.contents,
735                        element.box_slot,
736                    );
737                },
738                AnonymousTableContent::Text(info, text) => {
739                    row_builder.handle_text(&info, text);
740                },
741                AnonymousTableContent::EnterDisplayContents(ref styles) => {
742                    row_builder.enter_display_contents(styles.clone());
743                    enter_display_contents.push(cell_content);
744                },
745                AnonymousTableContent::LeaveDisplayContents => {
746                    row_builder.leave_display_contents();
747                    enter_display_contents.pop();
748                },
749            }
750        }
751        row_builder.finish();
752        self.current_anonymous_row_content = enter_display_contents;
753
754        let style = anonymous_info.style.clone();
755        let table_row = ArcRefCell::new(TableTrack {
756            base: LayoutBoxBase::new((&anonymous_info).into(), style.clone()),
757            group_index: self.current_row_group_index,
758            is_anonymous: true,
759            shared_background_style: SharedStyle::new(style),
760        });
761        self.push_table_row(table_row.clone());
762
763        anonymous_info
764            .node
765            .box_slot()
766            .set(LayoutBox::TableLevelBox(TableLevelBox::Track(table_row)))
767    }
768
769    fn push_table_row(&mut self, table_track: ArcRefCell<TableTrack>) {
770        self.builder.table.rows.push(table_track);
771
772        let last_row = self.builder.table.rows.len();
773        if let Some(index) = self.current_row_group_index {
774            let row_group = &mut self.builder.table.row_groups[index];
775            row_group.borrow_mut().track_range.end = last_row;
776        }
777    }
778}
779
780impl<'dom> TraversalHandler<'dom> for TableBuilderTraversal<'_, 'dom> {
781    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: BoxTreeString<'dom>) {
782        self.current_anonymous_row_content
783            .push(AnonymousTableContent::Text(info.clone(), text));
784    }
785
786    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
787        self.current_anonymous_row_content
788            .push(AnonymousTableContent::EnterDisplayContents(styles));
789    }
790
791    fn leave_display_contents(&mut self) {
792        self.current_anonymous_row_content
793            .push(AnonymousTableContent::LeaveDisplayContents);
794    }
795
796    /// <https://html.spec.whatwg.org/multipage/#forming-a-table>
797    fn handle_element(
798        &mut self,
799        info: &NodeAndStyleInfo<'dom>,
800        display: DisplayGeneratingBox,
801        contents: Contents,
802        box_slot: BoxSlot<'dom>,
803    ) {
804        match display {
805            DisplayGeneratingBox::LayoutInternal(internal) => match internal {
806                DisplayLayoutInternal::TableRowGroup |
807                DisplayLayoutInternal::TableFooterGroup |
808                DisplayLayoutInternal::TableHeaderGroup => {
809                    self.finish_anonymous_row_if_needed();
810                    self.builder.incoming_rowspans.clear();
811
812                    let next_row_index = self.builder.table.rows.len();
813                    let row_group = ArcRefCell::new(TableTrackGroup {
814                        base: LayoutBoxBase::new(info.into(), info.style.clone()),
815                        group_type: internal.into(),
816                        track_range: next_row_index..next_row_index,
817                        shared_background_style: SharedStyle::new(info.style.clone()),
818                    });
819                    self.builder.table.row_groups.push(row_group.clone());
820
821                    let new_row_group_index = self.builder.table.row_groups.len() - 1;
822                    let context = self.context;
823                    let mut row_group_builder = TableRowGroupBuilder::new(
824                        self,
825                        info,
826                        self.current_propagated_data,
827                        new_row_group_index,
828                    );
829
830                    contents
831                        .non_replaced_contents()
832                        .expect("Replaced should not have a LayoutInternal display type.")
833                        .traverse(context, info, &mut row_group_builder);
834
835                    row_group_builder.finish();
836
837                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::TrackGroup(
838                        row_group,
839                    )));
840                },
841                DisplayLayoutInternal::TableRow => {
842                    self.finish_anonymous_row_if_needed();
843
844                    let context = self.context;
845                    let mut row_builder =
846                        TableRowBuilder::new(self, info, self.current_propagated_data);
847
848                    contents
849                        .non_replaced_contents()
850                        .expect("Replaced should not have a LayoutInternal display type.")
851                        .traverse(context, info, &mut row_builder);
852                    row_builder.finish();
853
854                    let row = ArcRefCell::new(TableTrack {
855                        base: LayoutBoxBase::new(info.into(), info.style.clone()),
856                        group_index: self.current_row_group_index,
857                        is_anonymous: false,
858                        shared_background_style: SharedStyle::new(info.style.clone()),
859                    });
860                    self.push_table_row(row.clone());
861                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Track(row)));
862                },
863                DisplayLayoutInternal::TableColumn => {
864                    let old_box = box_slot.take_layout_box();
865                    let old_column = old_box.and_then(|layout_box| match layout_box {
866                        LayoutBox::TableLevelBox(TableLevelBox::Track(column)) => Some(column),
867                        _ => None,
868                    });
869                    let column = add_column(
870                        &mut self.builder.table.columns,
871                        info,
872                        None,  /* group_index */
873                        false, /* is_anonymous */
874                        old_column,
875                    );
876                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Track(column)));
877                },
878                DisplayLayoutInternal::TableColumnGroup => {
879                    let column_group_index = self.builder.table.column_groups.len();
880                    let mut column_group_builder = TableColumnGroupBuilder {
881                        column_group_index,
882                        columns: Vec::new(),
883                    };
884
885                    contents
886                        .non_replaced_contents()
887                        .expect("Replaced should not have a LayoutInternal display type.")
888                        .traverse(self.context, info, &mut column_group_builder);
889
890                    let first_column = self.builder.table.columns.len();
891                    if column_group_builder.columns.is_empty() {
892                        add_column(
893                            &mut self.builder.table.columns,
894                            info,
895                            Some(column_group_index),
896                            true, /* is_anonymous */
897                            None,
898                        );
899                    } else {
900                        self.builder
901                            .table
902                            .columns
903                            .extend(column_group_builder.columns);
904                    }
905
906                    let column_group = ArcRefCell::new(TableTrackGroup {
907                        base: LayoutBoxBase::new(info.into(), info.style.clone()),
908                        group_type: internal.into(),
909                        track_range: first_column..self.builder.table.columns.len(),
910                        shared_background_style: SharedStyle::new(info.style.clone()),
911                    });
912                    self.builder.table.column_groups.push(column_group.clone());
913                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::TrackGroup(
914                        column_group,
915                    )));
916                },
917                DisplayLayoutInternal::TableCaption => {
918                    let old_box = box_slot.take_layout_box();
919                    let old_caption = old_box.and_then(|layout_box| match layout_box {
920                        LayoutBox::TableLevelBox(TableLevelBox::Caption(caption)) => Some(caption),
921                        _ => None,
922                    });
923
924                    let caption = old_caption.unwrap_or_else(|| {
925                        let non_replaced_contents = contents
926                            .non_replaced_contents()
927                            .expect("Replaced should not have a LayoutInternal display type.");
928                        let contents = IndependentFormattingContextContents::Flow(
929                            BlockFormattingContext::construct(
930                                self.context,
931                                info,
932                                non_replaced_contents,
933                                self.current_propagated_data,
934                                false, /* is_list_item */
935                                false, /* is_table_cell */
936                            ),
937                        );
938                        let base = LayoutBoxBase::new(info.into(), info.style.clone());
939                        ArcRefCell::new(TableCaption {
940                            context: IndependentFormattingContext::new(
941                                base,
942                                contents,
943                                self.current_propagated_data,
944                            ),
945                        })
946                    });
947
948                    self.builder.table.captions.push(caption.clone());
949                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Caption(caption)));
950                },
951                DisplayLayoutInternal::TableCell => {
952                    self.current_anonymous_row_content
953                        .push(AnonymousTableContent::Element(Box::new(
954                            AnonymousTableContentElement {
955                                info: info.clone(),
956                                display,
957                                contents,
958                                box_slot,
959                            },
960                        )));
961                },
962            },
963            _ => {
964                self.current_anonymous_row_content
965                    .push(AnonymousTableContent::Element(Box::new(
966                        AnonymousTableContentElement {
967                            info: info.clone(),
968                            display,
969                            contents,
970                            box_slot,
971                        },
972                    )));
973            },
974        }
975    }
976}
977
978struct TableRowGroupBuilder<'style, 'builder, 'dom, 'a> {
979    table_traversal: &'builder mut TableBuilderTraversal<'style, 'dom>,
980    info: &'a NodeAndStyleInfo<'dom>,
981    propagated_data: PropagatedBoxTreeData,
982    current_anonymous_row_content: Vec<AnonymousTableContent<'dom>>,
983}
984
985impl<'style, 'builder, 'dom, 'a> TableRowGroupBuilder<'style, 'builder, 'dom, 'a> {
986    fn new(
987        table_traversal: &'builder mut TableBuilderTraversal<'style, 'dom>,
988        info: &'a NodeAndStyleInfo<'dom>,
989        propagated_data: PropagatedBoxTreeData,
990        row_group_index: usize,
991    ) -> Self {
992        // Row groups are only opened from TableBuilderTraversal, never nested, so current_row_group_index is always None here.
993        debug_assert!(table_traversal.current_row_group_index.is_none());
994        table_traversal.current_row_group_index = Some(row_group_index);
995
996        Self {
997            table_traversal,
998            info,
999            propagated_data,
1000            current_anonymous_row_content: Vec::new(),
1001        }
1002    }
1003
1004    fn finish(mut self) {
1005        self.finish_anonymous_row_if_needed();
1006        self.table_traversal.current_row_group_index = None;
1007        self.table_traversal.builder.incoming_rowspans.clear();
1008    }
1009
1010    fn finish_anonymous_row_if_needed(&mut self) {
1011        if AnonymousTableContent::remove_whitespace_only(&mut self.current_anonymous_row_content) {
1012            return;
1013        }
1014
1015        let row_content = std::mem::take(&mut self.current_anonymous_row_content);
1016        let anonymous_info = self
1017            .info
1018            .with_pseudo_element(
1019                self.table_traversal.context,
1020                PseudoElement::ServoAnonymousTableRow,
1021            )
1022            .expect("Should never fail to create anonymous row info.");
1023
1024        let mut row_builder =
1025            TableRowBuilder::new(self.table_traversal, &anonymous_info, self.propagated_data);
1026
1027        let mut enter_display_contents = vec![];
1028        for cell_content in row_content {
1029            match cell_content {
1030                AnonymousTableContent::Element(element) => {
1031                    row_builder.handle_element(
1032                        &element.info,
1033                        element.display,
1034                        element.contents,
1035                        element.box_slot,
1036                    );
1037                },
1038                AnonymousTableContent::Text(info, text) => {
1039                    row_builder.handle_text(&info, text);
1040                },
1041                AnonymousTableContent::EnterDisplayContents(ref styles) => {
1042                    row_builder.enter_display_contents(styles.clone());
1043                    enter_display_contents.push(cell_content);
1044                },
1045                AnonymousTableContent::LeaveDisplayContents => {
1046                    row_builder.leave_display_contents();
1047                    enter_display_contents.pop();
1048                },
1049            }
1050        }
1051        self.current_anonymous_row_content = enter_display_contents;
1052
1053        row_builder.finish();
1054
1055        let style = anonymous_info.style.clone();
1056        let table_row = ArcRefCell::new(TableTrack {
1057            base: LayoutBoxBase::new((&anonymous_info).into(), style.clone()),
1058            group_index: self.table_traversal.current_row_group_index,
1059            is_anonymous: true,
1060            shared_background_style: SharedStyle::new(style),
1061        });
1062        self.table_traversal.push_table_row(table_row.clone());
1063
1064        anonymous_info
1065            .node
1066            .box_slot()
1067            .set(LayoutBox::TableLevelBox(TableLevelBox::Track(table_row)));
1068    }
1069}
1070
1071impl<'dom> TraversalHandler<'dom> for TableRowGroupBuilder<'_, '_, 'dom, '_> {
1072    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: BoxTreeString<'dom>) {
1073        self.current_anonymous_row_content
1074            .push(AnonymousTableContent::Text(info.clone(), text));
1075    }
1076
1077    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
1078        self.current_anonymous_row_content
1079            .push(AnonymousTableContent::EnterDisplayContents(styles));
1080    }
1081
1082    fn leave_display_contents(&mut self) {
1083        self.current_anonymous_row_content
1084            .push(AnonymousTableContent::LeaveDisplayContents);
1085    }
1086
1087    fn handle_element(
1088        &mut self,
1089        info: &NodeAndStyleInfo<'dom>,
1090        display: DisplayGeneratingBox,
1091        contents: Contents,
1092        box_slot: BoxSlot<'dom>,
1093    ) {
1094        match display {
1095            DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableRow) => {
1096                self.finish_anonymous_row_if_needed();
1097
1098                let context = self.table_traversal.context;
1099                let mut row_builder =
1100                    TableRowBuilder::new(self.table_traversal, info, self.propagated_data);
1101
1102                contents
1103                    .non_replaced_contents()
1104                    .expect("Replaced should not have a LayoutInternal display type.")
1105                    .traverse(context, info, &mut row_builder);
1106                row_builder.finish();
1107
1108                let row = ArcRefCell::new(TableTrack {
1109                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
1110                    group_index: self.table_traversal.current_row_group_index,
1111                    is_anonymous: false,
1112                    shared_background_style: SharedStyle::new(info.style.clone()),
1113                });
1114                self.table_traversal.push_table_row(row.clone());
1115                box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Track(row)));
1116            },
1117
1118            _ => {
1119                self.current_anonymous_row_content
1120                    .push(AnonymousTableContent::Element(Box::new(
1121                        AnonymousTableContentElement {
1122                            info: info.clone(),
1123                            display,
1124                            contents,
1125                            box_slot,
1126                        },
1127                    )));
1128            },
1129        }
1130    }
1131}
1132
1133struct TableRowBuilder<'style, 'builder, 'dom, 'a> {
1134    table_traversal: &'builder mut TableBuilderTraversal<'style, 'dom>,
1135
1136    /// The [`NodeAndStyleInfo`] of this table row, which we use to
1137    /// construct anonymous table cells.
1138    info: &'a NodeAndStyleInfo<'dom>,
1139
1140    current_anonymous_cell_content: Vec<AnonymousTableContent<'dom>>,
1141
1142    /// The [`PropagatedBoxTreeData`] to use for all children of this row.
1143    propagated_data: PropagatedBoxTreeData,
1144}
1145
1146impl<'style, 'builder, 'dom, 'a> TableRowBuilder<'style, 'builder, 'dom, 'a> {
1147    fn new(
1148        table_traversal: &'builder mut TableBuilderTraversal<'style, 'dom>,
1149        info: &'a NodeAndStyleInfo<'dom>,
1150        propagated_data: PropagatedBoxTreeData,
1151    ) -> Self {
1152        table_traversal.builder.start_row();
1153
1154        TableRowBuilder {
1155            table_traversal,
1156            info,
1157            current_anonymous_cell_content: Vec::new(),
1158            propagated_data,
1159        }
1160    }
1161
1162    fn finish(mut self) {
1163        self.finish_current_anonymous_cell_if_needed();
1164        self.table_traversal.builder.end_row();
1165    }
1166
1167    fn finish_current_anonymous_cell_if_needed(&mut self) {
1168        if AnonymousTableContent::remove_whitespace_only(&mut self.current_anonymous_cell_content) {
1169            return;
1170        }
1171
1172        let context = self.table_traversal.context;
1173        let anonymous_info = self
1174            .info
1175            .with_pseudo_element(context, PseudoElement::ServoAnonymousTableCell)
1176            .expect("Should never fail to create anonymous table cell info");
1177        let propagated_data = self.propagated_data.disallowing_percentage_table_columns();
1178        let mut builder = BlockContainerBuilder::new(context, &anonymous_info, propagated_data);
1179
1180        let mut enter_display_contents = vec![];
1181        for cell_content in self.current_anonymous_cell_content.drain(..) {
1182            match cell_content {
1183                AnonymousTableContent::Element(element) => {
1184                    builder.handle_element(
1185                        &element.info,
1186                        element.display,
1187                        element.contents,
1188                        element.box_slot,
1189                    );
1190                },
1191                AnonymousTableContent::Text(info, text) => {
1192                    builder.handle_text(&info, text);
1193                },
1194                AnonymousTableContent::EnterDisplayContents(ref styles) => {
1195                    builder.enter_display_contents(styles.clone());
1196                    enter_display_contents.push(cell_content);
1197                },
1198                AnonymousTableContent::LeaveDisplayContents => {
1199                    builder.leave_display_contents();
1200                    enter_display_contents.pop();
1201                },
1202            }
1203        }
1204        self.current_anonymous_cell_content = enter_display_contents;
1205
1206        let block_container = builder.finish();
1207        let new_table_cell = ArcRefCell::new(TableSlotCell {
1208            context: IndependentFormattingContext::new(
1209                LayoutBoxBase::new(BaseFragmentInfo::anonymous(), anonymous_info.style),
1210                IndependentFormattingContextContents::Flow(
1211                    BlockFormattingContext::from_block_container(
1212                        block_container,
1213                        /* is_table_cell = */ true,
1214                        /* textarea_size = */ None,
1215                    ),
1216                ),
1217                propagated_data,
1218            ),
1219            colspan: 1,
1220            rowspan: 1,
1221        });
1222        self.table_traversal
1223            .builder
1224            .add_cell(new_table_cell.clone());
1225
1226        anonymous_info
1227            .node
1228            .box_slot()
1229            .set(LayoutBox::TableLevelBox(TableLevelBox::Cell(
1230                new_table_cell,
1231            )));
1232    }
1233}
1234
1235impl<'dom> TraversalHandler<'dom> for TableRowBuilder<'_, '_, 'dom, '_> {
1236    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: BoxTreeString<'dom>) {
1237        self.current_anonymous_cell_content
1238            .push(AnonymousTableContent::Text(info.clone(), text));
1239    }
1240
1241    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
1242        self.current_anonymous_cell_content
1243            .push(AnonymousTableContent::EnterDisplayContents(styles));
1244    }
1245
1246    fn leave_display_contents(&mut self) {
1247        self.current_anonymous_cell_content
1248            .push(AnonymousTableContent::LeaveDisplayContents);
1249    }
1250
1251    /// <https://html.spec.whatwg.org/multipage/#algorithm-for-processing-rows>
1252    fn handle_element(
1253        &mut self,
1254        info: &NodeAndStyleInfo<'dom>,
1255        display: DisplayGeneratingBox,
1256        contents: Contents,
1257        box_slot: BoxSlot<'dom>,
1258    ) {
1259        match display {
1260            DisplayGeneratingBox::LayoutInternal(internal) => match internal {
1261                DisplayLayoutInternal::TableCell => {
1262                    self.finish_current_anonymous_cell_if_needed();
1263
1264                    let old_box = box_slot.take_layout_box();
1265                    let old_cell = old_box.and_then(|layout_box| match layout_box {
1266                        LayoutBox::TableLevelBox(TableLevelBox::Cell(cell)) => Some(cell),
1267                        _ => None,
1268                    });
1269
1270                    let cell = old_cell.unwrap_or_else(|| {
1271                        // This value will already have filtered out rowspan=0
1272                        // in quirks mode, so we don't have to worry about that.
1273                        let (rowspan, colspan) = if info.pseudo_element_chain().is_empty() {
1274                            let rowspan = info.node.table_rowspan().unwrap_or(1) as usize;
1275                            let colspan = info.node.table_colspan().unwrap_or(1) as usize;
1276
1277                            // The HTML specification clamps value of `rowspan` to [0, 65534] and
1278                            // `colspan` to [1, 1000].
1279                            assert!((1..=1000).contains(&colspan));
1280                            assert!((0..=65534).contains(&rowspan));
1281
1282                            (rowspan, colspan)
1283                        } else {
1284                            (1, 1)
1285                        };
1286
1287                        let propagated_data =
1288                            self.propagated_data.disallowing_percentage_table_columns();
1289                        let non_replaced_contents = contents
1290                            .non_replaced_contents()
1291                            .expect("Replaced should not have a LayoutInternal display type.");
1292
1293                        let contents = BlockFormattingContext::construct(
1294                            self.table_traversal.context,
1295                            info,
1296                            non_replaced_contents,
1297                            propagated_data,
1298                            false, /* is_list_item */
1299                            true,  /* is_table_cell */
1300                        );
1301
1302                        ArcRefCell::new(TableSlotCell {
1303                            context: IndependentFormattingContext::new(
1304                                LayoutBoxBase::new(info.into(), info.style.clone()),
1305                                IndependentFormattingContextContents::Flow(contents),
1306                                propagated_data,
1307                            ),
1308                            colspan,
1309                            rowspan,
1310                        })
1311                    });
1312
1313                    self.table_traversal.builder.add_cell(cell.clone());
1314                    box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Cell(cell)));
1315                },
1316                _ => {
1317                    //// TODO: Properly handle other table-like elements in the middle of a row.
1318                    self.current_anonymous_cell_content
1319                        .push(AnonymousTableContent::Element(Box::new(
1320                            AnonymousTableContentElement {
1321                                info: info.clone(),
1322                                display,
1323                                contents,
1324                                box_slot,
1325                            },
1326                        )));
1327                },
1328            },
1329            _ => {
1330                self.current_anonymous_cell_content
1331                    .push(AnonymousTableContent::Element(Box::new(
1332                        AnonymousTableContentElement {
1333                            info: info.clone(),
1334                            display,
1335                            contents,
1336                            box_slot,
1337                        },
1338                    )));
1339            },
1340        }
1341    }
1342}
1343
1344struct TableColumnGroupBuilder {
1345    column_group_index: usize,
1346    columns: Vec<ArcRefCell<TableTrack>>,
1347}
1348
1349impl<'dom> TraversalHandler<'dom> for TableColumnGroupBuilder {
1350    fn handle_text(&mut self, _info: &NodeAndStyleInfo<'dom>, _text: BoxTreeString<'dom>) {}
1351    fn enter_display_contents(&mut self, _: SharedInlineStyles) {}
1352    fn leave_display_contents(&mut self) {}
1353    fn handle_element(
1354        &mut self,
1355        info: &NodeAndStyleInfo<'dom>,
1356        display: DisplayGeneratingBox,
1357        _contents: Contents,
1358        box_slot: BoxSlot<'dom>,
1359    ) {
1360        if !matches!(
1361            display,
1362            DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableColumn)
1363        ) {
1364            // The BoxSlot destructor will check to ensure that it isn't empty but in this case, the
1365            // DOM node doesn't produce any box, so explicitly skip the destructor here.
1366            ::std::mem::forget(box_slot);
1367            return;
1368        }
1369        let old_box = box_slot.take_layout_box();
1370        let old_column = old_box.and_then(|layout_box| match layout_box {
1371            LayoutBox::TableLevelBox(TableLevelBox::Track(column)) => Some(column),
1372            _ => None,
1373        });
1374        let column = add_column(
1375            &mut self.columns,
1376            info,
1377            Some(self.column_group_index),
1378            false, /* is_anonymous */
1379            old_column,
1380        );
1381        box_slot.set(LayoutBox::TableLevelBox(TableLevelBox::Track(column)));
1382    }
1383}
1384
1385impl From<DisplayLayoutInternal> for TableTrackGroupType {
1386    fn from(value: DisplayLayoutInternal) -> Self {
1387        match value {
1388            DisplayLayoutInternal::TableColumnGroup => TableTrackGroupType::ColumnGroup,
1389            DisplayLayoutInternal::TableFooterGroup => TableTrackGroupType::FooterGroup,
1390            DisplayLayoutInternal::TableHeaderGroup => TableTrackGroupType::HeaderGroup,
1391            DisplayLayoutInternal::TableRowGroup => TableTrackGroupType::RowGroup,
1392            _ => unreachable!(),
1393        }
1394    }
1395}
1396
1397fn add_column(
1398    collection: &mut Vec<ArcRefCell<TableTrack>>,
1399    column_info: &NodeAndStyleInfo,
1400    group_index: Option<usize>,
1401    is_anonymous: bool,
1402    old_column: Option<ArcRefCell<TableTrack>>,
1403) -> ArcRefCell<TableTrack> {
1404    let span = if column_info.pseudo_element_chain().is_empty() {
1405        column_info.node.table_span().unwrap_or(1)
1406    } else {
1407        1
1408    };
1409
1410    // The HTML specification clamps value of `span` for `<col>` to [1, 1000].
1411    assert!((1..=1000).contains(&span));
1412
1413    let column = match old_column {
1414        Some(column) => {
1415            column.borrow_mut().group_index = group_index;
1416            column
1417        },
1418        None => ArcRefCell::new(TableTrack {
1419            base: LayoutBoxBase::new(column_info.into(), column_info.style.clone()),
1420            group_index,
1421            is_anonymous,
1422            shared_background_style: SharedStyle::new(column_info.style.clone()),
1423        }),
1424    };
1425    collection.extend(repeat_n(column.clone(), span as usize));
1426    column
1427}