layout/flow/
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::borrow::Cow;
6
7use rayon::iter::{IntoParallelIterator, ParallelIterator};
8use servo_arc::Arc;
9use style::properties::ComputedValues;
10use style::properties::longhands::list_style_position::computed_value::T as ListStylePosition;
11use style::selector_parser::PseudoElement;
12use style::str::char_is_whitespace;
13use style::values::specified::box_::DisplayOutside as StyloDisplayOutside;
14
15use super::OutsideMarker;
16use super::inline::construct::InlineFormattingContextBuilder;
17use super::inline::inline_box::InlineBox;
18use super::inline::{InlineFormattingContext, SharedInlineStyles};
19use crate::PropagatedBoxTreeData;
20use crate::cell::ArcRefCell;
21use crate::context::LayoutContext;
22use crate::dom::{BoxSlot, LayoutBox, NodeExt};
23use crate::dom_traversal::{
24    Contents, NodeAndStyleInfo, NonReplacedContents, PseudoElementContentItem, TraversalHandler,
25};
26use crate::flow::float::FloatBox;
27use crate::flow::{BlockContainer, BlockFormattingContext, BlockLevelBox};
28use crate::formatting_contexts::IndependentFormattingContext;
29use crate::fragment_tree::FragmentFlags;
30use crate::layout_box_base::LayoutBoxBase;
31use crate::positioned::AbsolutelyPositionedBox;
32use crate::style_ext::{ComputedValuesExt, DisplayGeneratingBox, DisplayInside, DisplayOutside};
33use crate::table::{AnonymousTableContent, Table};
34
35impl BlockFormattingContext {
36    pub(crate) fn construct(
37        context: &LayoutContext,
38        info: &NodeAndStyleInfo<'_>,
39        contents: NonReplacedContents,
40        propagated_data: PropagatedBoxTreeData,
41        is_list_item: bool,
42    ) -> Self {
43        Self::from_block_container(BlockContainer::construct(
44            context,
45            info,
46            contents,
47            propagated_data,
48            is_list_item,
49        ))
50    }
51
52    pub(crate) fn from_block_container(contents: BlockContainer) -> Self {
53        let contains_floats = contents.contains_floats();
54        Self {
55            contents,
56            contains_floats,
57        }
58    }
59}
60
61struct BlockLevelJob<'dom> {
62    info: NodeAndStyleInfo<'dom>,
63    box_slot: BoxSlot<'dom>,
64    propagated_data: PropagatedBoxTreeData,
65    kind: BlockLevelCreator,
66}
67
68enum BlockLevelCreator {
69    SameFormattingContextBlock(IntermediateBlockContainer),
70    Independent {
71        display_inside: DisplayInside,
72        contents: Contents,
73    },
74    OutOfFlowAbsolutelyPositionedBox {
75        display_inside: DisplayInside,
76        contents: Contents,
77    },
78    OutOfFlowFloatBox {
79        display_inside: DisplayInside,
80        contents: Contents,
81    },
82    OutsideMarker {
83        list_item_style: Arc<ComputedValues>,
84        contents: Vec<PseudoElementContentItem>,
85    },
86    AnonymousTable {
87        table_block: ArcRefCell<BlockLevelBox>,
88    },
89}
90
91/// A block container that may still have to be constructed.
92///
93/// Represents either the inline formatting context of an anonymous block
94/// box or the yet-to-be-computed block container generated from the children
95/// of a given element.
96///
97/// Deferring allows using rayon’s `into_par_iter`.
98enum IntermediateBlockContainer {
99    InlineFormattingContext(BlockContainer),
100    Deferred {
101        contents: NonReplacedContents,
102        propagated_data: PropagatedBoxTreeData,
103        is_list_item: bool,
104    },
105}
106
107/// A builder for a block container.
108///
109/// This builder starts from the first child of a given DOM node
110/// and does a preorder traversal of all of its inclusive siblings.
111pub(crate) struct BlockContainerBuilder<'dom, 'style> {
112    context: &'style LayoutContext<'style>,
113
114    /// This NodeAndStyleInfo contains the root node, the corresponding pseudo
115    /// content designator, and the block container style.
116    info: &'style NodeAndStyleInfo<'dom>,
117
118    /// The list of block-level boxes to be built for the final block container.
119    ///
120    /// Contains all the block-level jobs we found traversing the tree
121    /// so far, if this is empty at the end of the traversal and the ongoing
122    /// inline formatting context is not empty, the block container establishes
123    /// an inline formatting context (see end of `build`).
124    ///
125    /// DOM nodes which represent block-level boxes are immediately pushed
126    /// to this list with their style without ever being traversed at this
127    /// point, instead we just move to their next sibling. If the DOM node
128    /// doesn't have a next sibling, we either reached the end of the container
129    /// root or there are ongoing inline-level boxes
130    /// (see `handle_block_level_element`).
131    block_level_boxes: Vec<BlockLevelJob<'dom>>,
132
133    /// Whether or not this builder has yet produced a block which would be
134    /// be considered the first line for the purposes of `text-indent`.
135    have_already_seen_first_line_for_text_indent: bool,
136
137    /// The propagated data to use for BoxTree construction.
138    propagated_data: PropagatedBoxTreeData,
139
140    /// The [`InlineFormattingContextBuilder`] if we have encountered any inline items,
141    /// otherwise None.
142    ///
143    /// TODO: This can be `OnceCell` once `OnceCell::get_mut_or_init` is stabilized.
144    inline_formatting_context_builder: Option<InlineFormattingContextBuilder>,
145
146    /// The [`NodeAndStyleInfo`] to use for anonymous block boxes pushed to the list of
147    /// block-level boxes, lazily initialized.
148    anonymous_box_info: Option<NodeAndStyleInfo<'dom>>,
149
150    /// A collection of content that is being added to an anonymous table. This is
151    /// composed of any sequence of internal table elements or table captions that
152    /// are found outside of a table.
153    anonymous_table_content: Vec<AnonymousTableContent<'dom>>,
154
155    /// Any [`InlineFormattingContexts`] created need to know about the ongoing `display: contents`
156    /// ancestors that have been processed. This `Vec` allows passing those into new
157    /// [`InlineFormattingContext`]s that we create.
158    display_contents_shared_styles: Vec<SharedInlineStyles>,
159}
160
161impl BlockContainer {
162    pub fn construct(
163        context: &LayoutContext,
164        info: &NodeAndStyleInfo<'_>,
165        contents: NonReplacedContents,
166        propagated_data: PropagatedBoxTreeData,
167        is_list_item: bool,
168    ) -> BlockContainer {
169        let mut builder = BlockContainerBuilder::new(context, info, propagated_data);
170
171        if is_list_item {
172            if let Some((marker_info, marker_contents)) = crate::lists::make_marker(context, info) {
173                match marker_info.style.clone_list_style_position() {
174                    ListStylePosition::Inside => {
175                        builder.handle_list_item_marker_inside(&marker_info, marker_contents)
176                    },
177                    ListStylePosition::Outside => builder.handle_list_item_marker_outside(
178                        &marker_info,
179                        marker_contents,
180                        info.style.clone(),
181                    ),
182                }
183            }
184        }
185
186        contents.traverse(context, info, &mut builder);
187        builder.finish()
188    }
189}
190
191impl<'dom, 'style> BlockContainerBuilder<'dom, 'style> {
192    pub(crate) fn new(
193        context: &'style LayoutContext,
194        info: &'style NodeAndStyleInfo<'dom>,
195        propagated_data: PropagatedBoxTreeData,
196    ) -> Self {
197        BlockContainerBuilder {
198            context,
199            info,
200            block_level_boxes: Vec::new(),
201            propagated_data,
202            have_already_seen_first_line_for_text_indent: false,
203            anonymous_box_info: None,
204            anonymous_table_content: Vec::new(),
205            inline_formatting_context_builder: None,
206            display_contents_shared_styles: Vec::new(),
207        }
208    }
209
210    fn currently_processing_inline_box(&self) -> bool {
211        self.inline_formatting_context_builder
212            .as_ref()
213            .is_some_and(InlineFormattingContextBuilder::currently_processing_inline_box)
214    }
215
216    fn ensure_inline_formatting_context_builder(&mut self) -> &mut InlineFormattingContextBuilder {
217        self.inline_formatting_context_builder
218            .get_or_insert_with(|| {
219                let mut builder = InlineFormattingContextBuilder::new(self.info);
220                for shared_inline_styles in self.display_contents_shared_styles.iter() {
221                    builder.enter_display_contents(shared_inline_styles.clone());
222                }
223                builder
224            })
225    }
226
227    fn finish_ongoing_inline_formatting_context(&mut self) -> Option<InlineFormattingContext> {
228        self.inline_formatting_context_builder.take()?.finish(
229            self.context,
230            !self.have_already_seen_first_line_for_text_indent,
231            self.info.node.is_single_line_text_input(),
232            self.info.style.to_bidi_level(),
233        )
234    }
235
236    pub(crate) fn finish(mut self) -> BlockContainer {
237        debug_assert!(!self.currently_processing_inline_box());
238
239        self.finish_anonymous_table_if_needed();
240
241        if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context() {
242            // There are two options here. This block was composed of both one or more inline formatting contexts
243            // and child blocks OR this block was a single inline formatting context. In the latter case, we
244            // just return the inline formatting context as the block itself.
245            if self.block_level_boxes.is_empty() {
246                return BlockContainer::InlineFormattingContext(inline_formatting_context);
247            }
248            self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
249        }
250
251        let context = self.context;
252        let block_level_boxes = if self.context.use_rayon {
253            self.block_level_boxes
254                .into_par_iter()
255                .map(|block_level_job| block_level_job.finish(context))
256                .collect()
257        } else {
258            self.block_level_boxes
259                .into_iter()
260                .map(|block_level_job| block_level_job.finish(context))
261                .collect()
262        };
263
264        BlockContainer::BlockLevelBoxes(block_level_boxes)
265    }
266
267    fn finish_anonymous_table_if_needed(&mut self) {
268        if self.anonymous_table_content.is_empty() {
269            return;
270        }
271
272        // From https://drafts.csswg.org/css-tables/#fixup-algorithm:
273        //  > If the box’s parent is an inline, run-in, or ruby box (or any box that would perform
274        //  > inlinification of its children), then an inline-table box must be generated; otherwise
275        //  > it must be a table box.
276        //
277        // Note that text content in the inline formatting context isn't enough to force the
278        // creation of an inline table. It requires the parent to be an inline box.
279        let inline_table = self.currently_processing_inline_box();
280
281        let contents: Vec<AnonymousTableContent<'dom>> =
282            self.anonymous_table_content.drain(..).collect();
283        let last_text = match contents.last() {
284            Some(AnonymousTableContent::Text(info, text)) => Some((info.clone(), text.clone())),
285            _ => None,
286        };
287
288        let (table_info, ifc) =
289            Table::construct_anonymous(self.context, self.info, contents, self.propagated_data);
290
291        if inline_table {
292            self.ensure_inline_formatting_context_builder()
293                .push_atomic(|| ArcRefCell::new(ifc), None);
294        } else {
295            let table_block = ArcRefCell::new(BlockLevelBox::Independent(ifc));
296
297            if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context()
298            {
299                self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
300            }
301
302            let box_slot = table_info.node.box_slot();
303            self.block_level_boxes.push(BlockLevelJob {
304                info: table_info,
305                box_slot,
306                kind: BlockLevelCreator::AnonymousTable { table_block },
307                propagated_data: self.propagated_data,
308            });
309        }
310
311        // If the last element in the anonymous table content is whitespace, that
312        // whitespace doesn't actually belong to the table. It should be processed outside
313        // ie become a space between the anonymous table and the rest of the block
314        // content. Anonymous tables are really only constructed around internal table
315        // elements and the whitespace between them, so this trailing whitespace should
316        // not be included.
317        //
318        // See https://drafts.csswg.org/css-tables/#fixup-algorithm sections "Remove
319        // irrelevant boxes" and "Generate missing parents."
320        if let Some((info, text)) = last_text {
321            self.handle_text(&info, text);
322        }
323    }
324}
325
326impl<'dom> TraversalHandler<'dom> for BlockContainerBuilder<'dom, '_> {
327    fn handle_element(
328        &mut self,
329        info: &NodeAndStyleInfo<'dom>,
330        display: DisplayGeneratingBox,
331        contents: Contents,
332        box_slot: BoxSlot<'dom>,
333    ) {
334        match display {
335            DisplayGeneratingBox::OutsideInside { outside, inside } => {
336                self.finish_anonymous_table_if_needed();
337
338                match outside {
339                    DisplayOutside::Inline => {
340                        self.handle_inline_level_element(info, inside, contents, box_slot)
341                    },
342                    DisplayOutside::Block => {
343                        let box_style = info.style.get_box();
344                        // Floats and abspos cause blockification, so they only happen in this case.
345                        // https://drafts.csswg.org/css2/visuren.html#dis-pos-flo
346                        if box_style.position.is_absolutely_positioned() {
347                            self.handle_absolutely_positioned_element(
348                                info, inside, contents, box_slot,
349                            )
350                        } else if box_style.float.is_floating() {
351                            self.handle_float_element(info, inside, contents, box_slot)
352                        } else {
353                            self.handle_block_level_element(info, inside, contents, box_slot)
354                        }
355                    },
356                };
357            },
358            DisplayGeneratingBox::LayoutInternal(_) => {
359                self.anonymous_table_content
360                    .push(AnonymousTableContent::Element {
361                        info: info.clone(),
362                        display,
363                        contents,
364                        box_slot,
365                    });
366            },
367        }
368    }
369
370    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: Cow<'dom, str>) {
371        if text.is_empty() {
372            return;
373        }
374
375        // If we are building an anonymous table ie this text directly followed internal
376        // table elements that did not have a `<table>` ancestor, then we forward all
377        // whitespace to the table builder.
378        if !self.anonymous_table_content.is_empty() && text.chars().all(char_is_whitespace) {
379            self.anonymous_table_content
380                .push(AnonymousTableContent::Text(info.clone(), text));
381            return;
382        } else {
383            self.finish_anonymous_table_if_needed();
384        }
385
386        self.ensure_inline_formatting_context_builder()
387            .push_text(text, info);
388    }
389
390    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
391        self.display_contents_shared_styles.push(styles.clone());
392        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
393            builder.enter_display_contents(styles);
394        }
395    }
396
397    fn leave_display_contents(&mut self) {
398        self.display_contents_shared_styles.pop();
399        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
400            builder.leave_display_contents();
401        }
402    }
403}
404
405impl<'dom> BlockContainerBuilder<'dom, '_> {
406    fn handle_list_item_marker_inside(
407        &mut self,
408        marker_info: &NodeAndStyleInfo<'dom>,
409        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
410    ) {
411        let box_slot = marker_info.node.box_slot();
412        self.handle_inline_level_element(
413            marker_info,
414            DisplayInside::Flow {
415                is_list_item: false,
416            },
417            Contents::for_pseudo_element(contents),
418            box_slot,
419        );
420    }
421
422    fn handle_list_item_marker_outside(
423        &mut self,
424        marker_info: &NodeAndStyleInfo<'dom>,
425        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
426        list_item_style: Arc<ComputedValues>,
427    ) {
428        let box_slot = marker_info.node.box_slot();
429        self.block_level_boxes.push(BlockLevelJob {
430            info: marker_info.clone(),
431            box_slot,
432            kind: BlockLevelCreator::OutsideMarker {
433                contents,
434                list_item_style,
435            },
436            propagated_data: self.propagated_data,
437        });
438    }
439
440    fn handle_inline_level_element(
441        &mut self,
442        info: &NodeAndStyleInfo<'dom>,
443        display_inside: DisplayInside,
444        contents: Contents,
445        box_slot: BoxSlot<'dom>,
446    ) {
447        let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
448        let (is_list_item, non_replaced_contents) = match (display_inside, contents) {
449            (
450                DisplayInside::Flow { is_list_item },
451                Contents::NonReplaced(non_replaced_contents),
452            ) => (is_list_item, non_replaced_contents),
453            (_, contents) => {
454                // If this inline element is an atomic, handle it and return.
455                let context = self.context;
456                let propagated_data = self.propagated_data;
457
458                let construction_callback = || {
459                    ArcRefCell::new(IndependentFormattingContext::construct(
460                        context,
461                        info,
462                        display_inside,
463                        contents,
464                        propagated_data,
465                    ))
466                };
467
468                let atomic = self
469                    .ensure_inline_formatting_context_builder()
470                    .push_atomic(construction_callback, old_layout_box);
471                box_slot.set(LayoutBox::InlineLevel(atomic));
472                return;
473            },
474        };
475
476        // Otherwise, this is just a normal inline box. Whatever happened before, all we need to do
477        // before recurring is to remember this ongoing inline level box.
478        let inline_builder = self.ensure_inline_formatting_context_builder();
479        inline_builder.start_inline_box(|| ArcRefCell::new(InlineBox::new(info)), old_layout_box);
480        box_slot.set(LayoutBox::InlineLevel(
481            inline_builder.inline_items.last().unwrap().clone(),
482        ));
483
484        if is_list_item {
485            if let Some((marker_info, marker_contents)) =
486                crate::lists::make_marker(self.context, info)
487            {
488                // Ignore `list-style-position` here:
489                // “If the list item is an inline box: this value is equivalent to `inside`.”
490                // https://drafts.csswg.org/css-lists/#list-style-position-outside
491                self.handle_list_item_marker_inside(&marker_info, marker_contents)
492            }
493        }
494
495        // `unwrap` doesn’t panic here because `is_replaced` returned `false`.
496        non_replaced_contents.traverse(self.context, info, self);
497
498        self.finish_anonymous_table_if_needed();
499
500        self.inline_formatting_context_builder
501            .as_mut()
502            .expect("Should be building an InlineFormattingContext")
503            .end_inline_box();
504    }
505
506    fn handle_block_level_element(
507        &mut self,
508        info: &NodeAndStyleInfo<'dom>,
509        display_inside: DisplayInside,
510        contents: Contents,
511        box_slot: BoxSlot<'dom>,
512    ) {
513        let propagated_data = self.propagated_data;
514        let kind = match contents {
515            Contents::NonReplaced(contents) => match display_inside {
516                DisplayInside::Flow { is_list_item }
517                    // Fragment flags are just used to indicate that the element is not replaced, so empty
518                    // flags are okay here.
519                    if !info.style.establishes_block_formatting_context(
520                        FragmentFlags::empty()
521                    ) =>
522                {
523                    BlockLevelCreator::SameFormattingContextBlock(
524                        IntermediateBlockContainer::Deferred {
525                            contents,
526                            propagated_data,
527                            is_list_item,
528                        },
529                    )
530                },
531                _ => BlockLevelCreator::Independent {
532                    display_inside,
533                    contents: Contents::NonReplaced(contents),
534                },
535            },
536            Contents::Replaced(_) | Contents::Widget(_) => BlockLevelCreator::Independent {
537                display_inside,
538                contents,
539            },
540        };
541        let job = BlockLevelJob {
542            info: info.clone(),
543            box_slot,
544            kind,
545            propagated_data,
546        };
547        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
548            if builder.currently_processing_inline_box() {
549                builder.push_block_level_box(job.finish(self.context), self.info, self.context);
550                return;
551            }
552            if let Some(context) = self.finish_ongoing_inline_formatting_context() {
553                self.push_block_level_job_for_inline_formatting_context(context);
554            }
555        }
556        self.block_level_boxes.push(job);
557
558        // Any block also counts as the first line for the purposes of text indent. Even if
559        // they don't actually indent.
560        self.have_already_seen_first_line_for_text_indent = true;
561    }
562
563    fn handle_absolutely_positioned_element(
564        &mut self,
565        info: &NodeAndStyleInfo<'dom>,
566        display_inside: DisplayInside,
567        contents: Contents,
568        box_slot: BoxSlot<'dom>,
569    ) {
570        // If the original display was inline-level, then we need an inline formatting context
571        // in order to compute the static position correctly.
572        // If it was block-level, we don't want to break an existing inline formatting context,
573        // so push it there (`LineItemLayout::layout_absolute` can handle this well). But if
574        // there is no inline formatting context, then we can avoid creating one.
575        let needs_inline_builder =
576            info.style.get_box().original_display.outside() == StyloDisplayOutside::Inline;
577        if needs_inline_builder {
578            self.ensure_inline_formatting_context_builder();
579        }
580        let inline_builder = self
581            .inline_formatting_context_builder
582            .as_mut()
583            .filter(|builder| needs_inline_builder || !builder.is_empty);
584        if let Some(inline_builder) = inline_builder {
585            let constructor = || {
586                ArcRefCell::new(AbsolutelyPositionedBox::construct(
587                    self.context,
588                    info,
589                    display_inside,
590                    contents,
591                ))
592            };
593            let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
594            let inline_level_box =
595                inline_builder.push_absolutely_positioned_box(constructor, old_layout_box);
596            box_slot.set(LayoutBox::InlineLevel(inline_level_box));
597            return;
598        }
599
600        let kind = BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
601            contents,
602            display_inside,
603        };
604        self.block_level_boxes.push(BlockLevelJob {
605            info: info.clone(),
606            box_slot,
607            kind,
608            propagated_data: self.propagated_data,
609        });
610    }
611
612    fn handle_float_element(
613        &mut self,
614        info: &NodeAndStyleInfo<'dom>,
615        display_inside: DisplayInside,
616        contents: Contents,
617        box_slot: BoxSlot<'dom>,
618    ) {
619        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
620            if !builder.is_empty {
621                let constructor = || {
622                    ArcRefCell::new(FloatBox::construct(
623                        self.context,
624                        info,
625                        display_inside,
626                        contents,
627                        self.propagated_data,
628                    ))
629                };
630                let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
631                let inline_level_box = builder.push_float_box(constructor, old_layout_box);
632                box_slot.set(LayoutBox::InlineLevel(inline_level_box));
633                return;
634            }
635        }
636
637        let kind = BlockLevelCreator::OutOfFlowFloatBox {
638            contents,
639            display_inside,
640        };
641        self.block_level_boxes.push(BlockLevelJob {
642            info: info.clone(),
643            box_slot,
644            kind,
645            propagated_data: self.propagated_data,
646        });
647    }
648
649    fn push_block_level_job_for_inline_formatting_context(
650        &mut self,
651        inline_formatting_context: InlineFormattingContext,
652    ) {
653        let layout_context = self.context;
654        let anonymous_info = self
655            .anonymous_box_info
656            .get_or_insert_with(|| {
657                self.info
658                    .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
659                    .expect("Should never fail to create anonymous box")
660            })
661            .clone();
662
663        let box_slot = anonymous_info.node.box_slot();
664        self.block_level_boxes.push(BlockLevelJob {
665            info: anonymous_info,
666            box_slot,
667            kind: BlockLevelCreator::SameFormattingContextBlock(
668                IntermediateBlockContainer::InlineFormattingContext(
669                    BlockContainer::InlineFormattingContext(inline_formatting_context),
670                ),
671            ),
672            propagated_data: self.propagated_data,
673        });
674
675        self.have_already_seen_first_line_for_text_indent = true;
676    }
677}
678
679impl BlockLevelJob<'_> {
680    fn finish(self, context: &LayoutContext) -> ArcRefCell<BlockLevelBox> {
681        let info = &self.info;
682
683        // If this `BlockLevelBox` is undamaged and it has been laid out before, reuse
684        // the old one, while being sure to clear the layout cache.
685        if !info.damage.has_box_damage() {
686            if let Some(block_level_box) = match &*self.box_slot.slot.borrow() {
687                Some(LayoutBox::BlockLevel(block_level_box)) => Some(block_level_box.clone()),
688                _ => None,
689            } {
690                return block_level_box;
691            }
692        }
693
694        let block_level_box = match self.kind {
695            BlockLevelCreator::SameFormattingContextBlock(intermediate_block_container) => {
696                let contents = intermediate_block_container.finish(context, info);
697                let contains_floats = contents.contains_floats();
698                ArcRefCell::new(BlockLevelBox::SameFormattingContextBlock {
699                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
700                    contents,
701                    contains_floats,
702                })
703            },
704            BlockLevelCreator::Independent {
705                display_inside,
706                contents,
707            } => {
708                let context = IndependentFormattingContext::construct(
709                    context,
710                    info,
711                    display_inside,
712                    contents,
713                    self.propagated_data,
714                );
715                ArcRefCell::new(BlockLevelBox::Independent(context))
716            },
717            BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
718                display_inside,
719                contents,
720            } => ArcRefCell::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
721                ArcRefCell::new(AbsolutelyPositionedBox::construct(
722                    context,
723                    info,
724                    display_inside,
725                    contents,
726                )),
727            )),
728            BlockLevelCreator::OutOfFlowFloatBox {
729                display_inside,
730                contents,
731            } => ArcRefCell::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
732                context,
733                info,
734                display_inside,
735                contents,
736                self.propagated_data,
737            ))),
738            BlockLevelCreator::OutsideMarker {
739                contents,
740                list_item_style,
741            } => {
742                let contents = NonReplacedContents::OfPseudoElement(contents);
743                let block_container = BlockContainer::construct(
744                    context,
745                    info,
746                    contents,
747                    self.propagated_data,
748                    false, /* is_list_item */
749                );
750                // An outside ::marker must establish a BFC, and can't contain floats.
751                let block_formatting_context = BlockFormattingContext {
752                    contents: block_container,
753                    contains_floats: false,
754                };
755                ArcRefCell::new(BlockLevelBox::OutsideMarker(OutsideMarker {
756                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
757                    block_formatting_context,
758                    list_item_style,
759                }))
760            },
761            BlockLevelCreator::AnonymousTable { table_block } => table_block,
762        };
763        self.box_slot
764            .set(LayoutBox::BlockLevel(block_level_box.clone()));
765        block_level_box
766    }
767}
768
769impl IntermediateBlockContainer {
770    fn finish(self, context: &LayoutContext, info: &NodeAndStyleInfo<'_>) -> BlockContainer {
771        match self {
772            IntermediateBlockContainer::Deferred {
773                contents,
774                propagated_data,
775                is_list_item,
776            } => BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
777            IntermediateBlockContainer::InlineFormattingContext(block_container) => block_container,
778        }
779    }
780}