1
//! CSS properties for `display` and `float`.
2

            
3
use alloc::string::{String, ToString};
4

            
5
use crate::{corety::AzString, props::formatter::PrintAsCssValue};
6

            
7
/// Represents a `display` CSS property value
8
// +spec:display-property:472a62 - display property controls box generation types per CSS 2.2 §9.2
9
// +spec:display-property:cf1820 - display type enum defining box generation qualities
10
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
11
#[repr(C)]
12
pub enum LayoutDisplay {
13
    // Basic display types
14
    None,
15
    // +spec:display-property:7d945d - outer display defaults to block, inner defaults to flow
16
    #[default]
17
    Block,
18
    Inline,
19
    InlineBlock,
20

            
21
    // Flex layout
22
    Flex,
23
    InlineFlex,
24

            
25
    // +spec:display-property:03b26a - Table display types mapping document elements to CSS table
26
    // model +spec:display-property:d40388 - layout-internal display types set both inner and
27
    // outer display +spec:display-property:dcf7f5 - table display values (table,
28
    // inline-table, table-row, etc.) per CSS 2.2 §17 +spec:table-layout:7fdc60 - display
29
    // property maps elements to table roles (CSS 2.2 §17.1) Table layout
30
    // +spec:display-property:1554ad - Layout-internal display types for table layout
31
    // +spec:table-layout:6cc828 - <display-internal> and <display-legacy> table display types
32
    Table,
33
    InlineTable,
34
    TableRowGroup,
35
    TableHeaderGroup,
36
    TableFooterGroup,
37
    TableRow,
38
    TableColumnGroup,
39
    TableColumn,
40
    TableCell,
41
    TableCaption,
42

            
43
    FlowRoot,
44

            
45
    // List layout
46
    ListItem,
47

            
48
    // Special displays
49
    RunIn,
50
    Marker,
51

            
52
    // CSS3 additions
53
    Grid,
54
    InlineGrid,
55

            
56
    // display:contents - element generates no box, children promoted to parent
57
    Contents,
58
}
59

            
60
impl LayoutDisplay {
61
    /// Returns true if this display type establishes a block formatting context.
62
    #[must_use]
63
19629
    pub const fn creates_block_context(&self) -> bool {
64
116
        matches!(
65
19629
            self,
66
            Self::Block | Self::FlowRoot | Self::Flex | Self::Grid | Self::Table | Self::ListItem
67
        )
68
19629
    }
69

            
70
    /// Returns true if this display type establishes a flex formatting context.
71
    #[must_use]
72
164
    pub const fn creates_flex_context(&self) -> bool {
73
164
        matches!(self, Self::Flex | Self::InlineFlex)
74
164
    }
75

            
76
    // +spec:display-property:798b4f - table box establishes table formatting context (CSS 2.2
77
    // §17.4)
78
    /// Returns true if this display type establishes a table formatting context.
79
    #[must_use]
80
599
    pub const fn creates_table_context(&self) -> bool {
81
599
        matches!(self, Self::Table | Self::InlineTable)
82
599
    }
83

            
84
    /// Returns true for layout-internal display types (CSS Display 3 §2.4):
85
    /// table-row-group, table-header-group, table-footer-group, table-row,
86
    /// table-column-group, table-column, table-cell, table-caption.
87
    #[must_use]
88
294070
    pub const fn is_layout_internal(&self) -> bool {
89
292298
        matches!(
90
294070
            self,
91
            Self::TableRowGroup
92
                | Self::TableHeaderGroup
93
                | Self::TableFooterGroup
94
                | Self::TableRow
95
                | Self::TableColumnGroup
96
                | Self::TableColumn
97
                | Self::TableCell
98
                | Self::TableCaption
99
        )
100
294070
    }
101

            
102
    // +spec:display-property:101f27 - inline-level boxes (InlineBlock, InlineFlex, etc.) vs inline
103
    // boxes (Inline) +spec:display-property:18e77e - inner-only display keywords (flex, grid,
104
    // table, flow-root) are not inline-level, defaulting outer display to block
105
    // +spec:display-property:a43e48 - inline-table is inline-level per CSS 2.2 §17.4
106
    /// Returns true if this display type generates an inline-level box.
107
    #[must_use]
108
158
    pub const fn is_inline_level(&self) -> bool {
109
123
        matches!(
110
158
            self,
111
            Self::Inline
112
                | Self::InlineBlock
113
                | Self::InlineFlex
114
                | Self::InlineTable
115
                | Self::InlineGrid
116
        )
117
158
    }
118

            
119
    /// Returns true for an ATOMIC inline-level box (CSS Display 3 §2.2 / §5.1):
120
    /// `inline-block`, `inline-flex`, `inline-table`, `inline-grid`. These are
121
    /// inline-level but establish their own independent formatting context and
122
    /// participate in their parent's IFC as a single opaque unit — unlike a
123
    /// (non-atomic) inline box (`Inline`), whose content flows directly into the
124
    /// IFC. `is_inline_level` covers both; this predicate is the distinction
125
    /// between them (which the enum has variants for but previously had no way to
126
    /// query).
127
    #[must_use]
128
967139
    pub const fn is_atomic_inline(&self) -> bool {
129
945591
        matches!(
130
967139
            self,
131
            Self::InlineBlock | Self::InlineFlex | Self::InlineTable | Self::InlineGrid
132
        )
133
967139
    }
134
}
135

            
136
// +spec:display-property:cabaec - serialization uses short display keywords per CSSOM precedence
137
// rules
138
impl PrintAsCssValue for LayoutDisplay {
139
6376
    fn print_as_css_value(&self) -> String {
140
6376
        String::from(match self {
141
3
            Self::None => "none",
142
5083
            Self::Block => "block",
143
850
            Self::Inline => "inline",
144
6
            Self::InlineBlock => "inline-block",
145
137
            Self::Flex => "flex",
146
8
            Self::InlineFlex => "inline-flex",
147
9
            Self::Table => "table",
148
10
            Self::InlineTable => "inline-table",
149
11
            Self::TableRowGroup => "table-row-group",
150
12
            Self::TableHeaderGroup => "table-header-group",
151
13
            Self::TableFooterGroup => "table-footer-group",
152
14
            Self::TableRow => "table-row",
153
15
            Self::TableColumnGroup => "table-column-group",
154
16
            Self::TableColumn => "table-column",
155
17
            Self::TableCell => "table-cell",
156
18
            Self::TableCaption => "table-caption",
157
20
            Self::ListItem => "list-item",
158
21
            Self::RunIn => "run-in",
159
22
            Self::Marker => "marker",
160
19
            Self::FlowRoot => "flow-root",
161
23
            Self::Grid => "grid",
162
24
            Self::InlineGrid => "inline-grid",
163
25
            Self::Contents => "contents",
164
        })
165
6376
    }
166
}
167

            
168
/// Represents a `float` attribute
169
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
170
#[repr(C)]
171
pub enum LayoutFloat {
172
    Left,
173
    Right,
174
    #[default]
175
    None,
176
}
177

            
178
impl PrintAsCssValue for LayoutFloat {
179
6
    fn print_as_css_value(&self) -> String {
180
6
        String::from(match self {
181
2
            Self::Left => "left",
182
2
            Self::Right => "right",
183
2
            Self::None => "none",
184
        })
185
6
    }
186
}
187

            
188
// --- PARSERS ---
189

            
190
#[cfg(feature = "parser")]
191
#[derive(Clone, PartialEq, Eq)]
192
pub enum LayoutDisplayParseError<'a> {
193
    InvalidValue(&'a str),
194
}
195

            
196
#[cfg(feature = "parser")]
197
impl_debug_as_display!(LayoutDisplayParseError<'a>);
198

            
199
#[cfg(feature = "parser")]
200
impl_display! { LayoutDisplayParseError<'a>, {
201
    InvalidValue(val) => format!("Invalid display value: \"{}\"", val),
202
}}
203

            
204
#[cfg(feature = "parser")]
205
#[derive(Debug, Clone, PartialEq, Eq)]
206
#[repr(C, u8)]
207
pub enum LayoutDisplayParseErrorOwned {
208
    InvalidValue(AzString),
209
}
210

            
211
#[cfg(feature = "parser")]
212
impl LayoutDisplayParseError<'_> {
213
    #[must_use]
214
10
    pub fn to_contained(&self) -> LayoutDisplayParseErrorOwned {
215
10
        match self {
216
10
            Self::InvalidValue(s) => {
217
10
                LayoutDisplayParseErrorOwned::InvalidValue((*s).to_string().into())
218
            }
219
        }
220
10
    }
221
}
222

            
223
#[cfg(feature = "parser")]
224
impl LayoutDisplayParseErrorOwned {
225
    #[must_use]
226
9
    pub fn to_shared(&self) -> LayoutDisplayParseError<'_> {
227
9
        match self {
228
9
            Self::InvalidValue(s) => LayoutDisplayParseError::InvalidValue(s.as_str()),
229
        }
230
9
    }
231
}
232

            
233
#[cfg(feature = "parser")]
234
/// # Errors
235
///
236
/// Returns an error if `input` is not a valid CSS `display` value.
237
65117
pub fn parse_layout_display(input: &str) -> Result<LayoutDisplay, LayoutDisplayParseError<'_>> {
238
65117
    let input = input.trim();
239
65117
    match input {
240
65117
        "none" => Ok(LayoutDisplay::None),
241
65022
        "block" => Ok(LayoutDisplay::Block),
242
51899
        "inline" => Ok(LayoutDisplay::Inline),
243
        // +spec:display-property:f704ef - legacy single-keyword inline-level display values
244
        // (inline-block, inline-table, inline-flex, inline-grid)
245
50986
        "inline-block" => Ok(LayoutDisplay::InlineBlock),
246
50192
        "flex" => Ok(LayoutDisplay::Flex),
247
1508
        "inline-flex" => Ok(LayoutDisplay::InlineFlex),
248
1256
        "table" => Ok(LayoutDisplay::Table),
249
1110
        "inline-table" => Ok(LayoutDisplay::InlineTable),
250
1055
        "table-row-group" => Ok(LayoutDisplay::TableRowGroup),
251
1026
        "table-header-group" => Ok(LayoutDisplay::TableHeaderGroup),
252
997
        "table-footer-group" => Ok(LayoutDisplay::TableFooterGroup),
253
981
        "table-row" => Ok(LayoutDisplay::TableRow),
254
861
        "table-column-group" => Ok(LayoutDisplay::TableColumnGroup),
255
845
        "table-column" => Ok(LayoutDisplay::TableColumn),
256
804
        "table-cell" => Ok(LayoutDisplay::TableCell),
257
592
        "table-caption" => Ok(LayoutDisplay::TableCaption),
258
549
        "list-item" => Ok(LayoutDisplay::ListItem),
259
351
        "run-in" => Ok(LayoutDisplay::RunIn),
260
348
        "marker" => Ok(LayoutDisplay::Marker),
261
345
        "grid" => Ok(LayoutDisplay::Grid),
262
242
        "inline-grid" => Ok(LayoutDisplay::InlineGrid),
263
187
        "flow-root" => Ok(LayoutDisplay::FlowRoot),
264
132
        "contents" => Ok(LayoutDisplay::Contents),
265
90
        _ => Err(LayoutDisplayParseError::InvalidValue(input)),
266
    }
267
65117
}
268

            
269
#[cfg(feature = "parser")]
270
#[derive(Clone, PartialEq, Eq)]
271
pub enum LayoutFloatParseError<'a> {
272
    InvalidValue(&'a str),
273
}
274

            
275
#[cfg(feature = "parser")]
276
impl_debug_as_display!(LayoutFloatParseError<'a>);
277

            
278
#[cfg(feature = "parser")]
279
impl_display! { LayoutFloatParseError<'a>, {
280
    InvalidValue(val) => format!("Invalid float value: \"{}\"", val),
281
}}
282

            
283
#[cfg(feature = "parser")]
284
#[derive(Debug, Clone, PartialEq, Eq)]
285
#[repr(C, u8)]
286
pub enum LayoutFloatParseErrorOwned {
287
    InvalidValue(AzString),
288
}
289

            
290
#[cfg(feature = "parser")]
291
impl LayoutFloatParseError<'_> {
292
    #[must_use]
293
6
    pub fn to_contained(&self) -> LayoutFloatParseErrorOwned {
294
6
        match self {
295
6
            Self::InvalidValue(s) => {
296
6
                LayoutFloatParseErrorOwned::InvalidValue((*s).to_string().into())
297
            }
298
        }
299
6
    }
300
}
301

            
302
#[cfg(feature = "parser")]
303
impl LayoutFloatParseErrorOwned {
304
    #[must_use]
305
6
    pub fn to_shared(&self) -> LayoutFloatParseError<'_> {
306
6
        match self {
307
6
            Self::InvalidValue(s) => LayoutFloatParseError::InvalidValue(s.as_str()),
308
        }
309
6
    }
310
}
311

            
312
#[cfg(feature = "parser")]
313
/// # Errors
314
///
315
/// Returns an error if `input` is not a valid CSS `float` value.
316
588
pub fn parse_layout_float(input: &str) -> Result<LayoutFloat, LayoutFloatParseError<'_>> {
317
588
    let input = input.trim();
318
588
    match input {
319
588
        "left" => Ok(LayoutFloat::Left),
320
231
        "right" => Ok(LayoutFloat::Right),
321
83
        "none" => Ok(LayoutFloat::None),
322
66
        _ => Err(LayoutFloatParseError::InvalidValue(input)),
323
    }
324
588
}
325

            
326
#[cfg(all(test, feature = "parser"))]
327
mod tests {
328
    use super::*;
329

            
330
    #[test]
331
    #[allow(clippy::cognitive_complexity)] // large but cohesive: single-purpose CSS
332
                                           // parser/formatter/dispatch table (one branch per
333
                                           // property/variant)
334
1
    fn test_parse_layout_display() {
335
1
        assert_eq!(parse_layout_display("block").unwrap(), LayoutDisplay::Block);
336
1
        assert_eq!(
337
1
            parse_layout_display("inline").unwrap(),
338
            LayoutDisplay::Inline
339
        );
340
1
        assert_eq!(
341
1
            parse_layout_display("inline-block").unwrap(),
342
            LayoutDisplay::InlineBlock
343
        );
344
1
        assert_eq!(parse_layout_display("flex").unwrap(), LayoutDisplay::Flex);
345
1
        assert_eq!(
346
1
            parse_layout_display("inline-flex").unwrap(),
347
            LayoutDisplay::InlineFlex
348
        );
349
1
        assert_eq!(parse_layout_display("grid").unwrap(), LayoutDisplay::Grid);
350
1
        assert_eq!(
351
1
            parse_layout_display("inline-grid").unwrap(),
352
            LayoutDisplay::InlineGrid
353
        );
354
1
        assert_eq!(parse_layout_display("none").unwrap(), LayoutDisplay::None);
355
1
        assert_eq!(
356
1
            parse_layout_display("flow-root").unwrap(),
357
            LayoutDisplay::FlowRoot
358
        );
359
1
        assert_eq!(
360
1
            parse_layout_display("list-item").unwrap(),
361
            LayoutDisplay::ListItem
362
        );
363
        // Note: 'inherit' and 'initial' are handled by the CSS cascade system,
364
        // not as enum variants
365
1
        assert!(parse_layout_display("inherit").is_err());
366
1
        assert!(parse_layout_display("initial").is_err());
367

            
368
        // Table values
369
1
        assert_eq!(parse_layout_display("table").unwrap(), LayoutDisplay::Table);
370
1
        assert_eq!(
371
1
            parse_layout_display("inline-table").unwrap(),
372
            LayoutDisplay::InlineTable
373
        );
374
1
        assert_eq!(
375
1
            parse_layout_display("table-row").unwrap(),
376
            LayoutDisplay::TableRow
377
        );
378
1
        assert_eq!(
379
1
            parse_layout_display("table-cell").unwrap(),
380
            LayoutDisplay::TableCell
381
        );
382
1
        assert_eq!(
383
1
            parse_layout_display("table-caption").unwrap(),
384
            LayoutDisplay::TableCaption
385
        );
386
1
        assert_eq!(
387
1
            parse_layout_display("table-column-group").unwrap(),
388
            LayoutDisplay::TableColumnGroup
389
        );
390
1
        assert_eq!(
391
1
            parse_layout_display("table-header-group").unwrap(),
392
            LayoutDisplay::TableHeaderGroup
393
        );
394
1
        assert_eq!(
395
1
            parse_layout_display("table-footer-group").unwrap(),
396
            LayoutDisplay::TableFooterGroup
397
        );
398
1
        assert_eq!(
399
1
            parse_layout_display("table-row-group").unwrap(),
400
            LayoutDisplay::TableRowGroup
401
        );
402

            
403
        // Whitespace
404
1
        assert_eq!(
405
1
            parse_layout_display("  inline-flex  ").unwrap(),
406
            LayoutDisplay::InlineFlex
407
        );
408

            
409
        // Invalid values
410
1
        assert!(parse_layout_display("invalid-value").is_err());
411
1
        assert!(parse_layout_display("").is_err());
412
1
        assert!(parse_layout_display("display").is_err());
413
1
    }
414

            
415
    #[test]
416
1
    fn test_parse_layout_float() {
417
1
        assert_eq!(parse_layout_float("left").unwrap(), LayoutFloat::Left);
418
1
        assert_eq!(parse_layout_float("right").unwrap(), LayoutFloat::Right);
419
1
        assert_eq!(parse_layout_float("none").unwrap(), LayoutFloat::None);
420

            
421
        // Whitespace
422
1
        assert_eq!(parse_layout_float("  right  ").unwrap(), LayoutFloat::Right);
423

            
424
        // Invalid values
425
1
        assert!(parse_layout_float("center").is_err());
426
1
        assert!(parse_layout_float("").is_err());
427
1
        assert!(parse_layout_float("float-left").is_err());
428
1
    }
429
}
430

            
431
#[cfg(all(test, feature = "parser"))]
432
mod autotest_generated {
433
    use super::*;
434

            
435
    /// Every `LayoutDisplay` variant. Kept honest by [`display_variant_index`],
436
    /// whose exhaustive match stops compiling when a variant is added.
437
    const ALL_DISPLAY: [LayoutDisplay; 23] = [
438
        LayoutDisplay::None,
439
        LayoutDisplay::Block,
440
        LayoutDisplay::Inline,
441
        LayoutDisplay::InlineBlock,
442
        LayoutDisplay::Flex,
443
        LayoutDisplay::InlineFlex,
444
        LayoutDisplay::Table,
445
        LayoutDisplay::InlineTable,
446
        LayoutDisplay::TableRowGroup,
447
        LayoutDisplay::TableHeaderGroup,
448
        LayoutDisplay::TableFooterGroup,
449
        LayoutDisplay::TableRow,
450
        LayoutDisplay::TableColumnGroup,
451
        LayoutDisplay::TableColumn,
452
        LayoutDisplay::TableCell,
453
        LayoutDisplay::TableCaption,
454
        LayoutDisplay::FlowRoot,
455
        LayoutDisplay::ListItem,
456
        LayoutDisplay::RunIn,
457
        LayoutDisplay::Marker,
458
        LayoutDisplay::Grid,
459
        LayoutDisplay::InlineGrid,
460
        LayoutDisplay::Contents,
461
    ];
462

            
463
    const ALL_FLOAT: [LayoutFloat; 3] = [LayoutFloat::Left, LayoutFloat::Right, LayoutFloat::None];
464

            
465
    /// Position of each variant inside `ALL_DISPLAY`. The match is deliberately
466
    /// exhaustive (no `_` arm) so a new `LayoutDisplay` variant is a compile
467
    /// error here rather than a silently untested variant below.
468
    const fn display_variant_index(d: LayoutDisplay) -> usize {
469
        match d {
470
            LayoutDisplay::None => 0,
471
            LayoutDisplay::Block => 1,
472
            LayoutDisplay::Inline => 2,
473
            LayoutDisplay::InlineBlock => 3,
474
            LayoutDisplay::Flex => 4,
475
            LayoutDisplay::InlineFlex => 5,
476
            LayoutDisplay::Table => 6,
477
            LayoutDisplay::InlineTable => 7,
478
            LayoutDisplay::TableRowGroup => 8,
479
            LayoutDisplay::TableHeaderGroup => 9,
480
            LayoutDisplay::TableFooterGroup => 10,
481
            LayoutDisplay::TableRow => 11,
482
            LayoutDisplay::TableColumnGroup => 12,
483
            LayoutDisplay::TableColumn => 13,
484
            LayoutDisplay::TableCell => 14,
485
            LayoutDisplay::TableCaption => 15,
486
            LayoutDisplay::FlowRoot => 16,
487
            LayoutDisplay::ListItem => 17,
488
            LayoutDisplay::RunIn => 18,
489
            LayoutDisplay::Marker => 19,
490
            LayoutDisplay::Grid => 20,
491
            LayoutDisplay::InlineGrid => 21,
492
            LayoutDisplay::Contents => 22,
493
        }
494
    }
495

            
496
    // -----------------------------------------------------------------
497
    // Coverage guards
498
    // -----------------------------------------------------------------
499

            
500
    #[test]
501
    fn all_display_lists_every_variant_exactly_once() {
502
        for (i, d) in ALL_DISPLAY.iter().enumerate() {
503
            assert_eq!(
504
                display_variant_index(*d),
505
                i,
506
                "ALL_DISPLAY is out of sync at index {i} ({d:?})"
507
            );
508
        }
509
    }
510

            
511
    // -----------------------------------------------------------------
512
    // creates_block_context / creates_flex_context / creates_table_context
513
    // -----------------------------------------------------------------
514

            
515
    #[test]
516
    fn creates_block_context_matches_an_exact_variant_set() {
517
        // NOTE (spec deviation, pinned as *current* behaviour): CSS 2.1 §9.4.1
518
        // also gives inline-blocks, table-cells and table-captions a new block
519
        // formatting context, and flex/grid containers establish flex/grid
520
        // formatting contexts rather than block ones. This implementation uses
521
        // the narrower set below.
522
        const EXPECTED: [LayoutDisplay; 6] = [
523
            LayoutDisplay::Block,
524
            LayoutDisplay::FlowRoot,
525
            LayoutDisplay::Flex,
526
            LayoutDisplay::Grid,
527
            LayoutDisplay::Table,
528
            LayoutDisplay::ListItem,
529
        ];
530
        for d in ALL_DISPLAY {
531
            assert_eq!(
532
                d.creates_block_context(),
533
                EXPECTED.contains(&d),
534
                "creates_block_context({d:?})"
535
            );
536
        }
537
    }
538

            
539
    #[test]
540
    fn creates_flex_context_matches_an_exact_variant_set() {
541
        const EXPECTED: [LayoutDisplay; 2] = [LayoutDisplay::Flex, LayoutDisplay::InlineFlex];
542
        for d in ALL_DISPLAY {
543
            assert_eq!(
544
                d.creates_flex_context(),
545
                EXPECTED.contains(&d),
546
                "creates_flex_context({d:?})"
547
            );
548
        }
549
    }
550

            
551
    #[test]
552
    fn creates_table_context_matches_an_exact_variant_set() {
553
        // Only the table *wrapper* boxes establish a table formatting context;
554
        // the layout-internal boxes (rows, cells, ...) participate in one.
555
        const EXPECTED: [LayoutDisplay; 2] = [LayoutDisplay::Table, LayoutDisplay::InlineTable];
556
        for d in ALL_DISPLAY {
557
            assert_eq!(
558
                d.creates_table_context(),
559
                EXPECTED.contains(&d),
560
                "creates_table_context({d:?})"
561
            );
562
        }
563
    }
564

            
565
    // -----------------------------------------------------------------
566
    // is_layout_internal / is_inline_level
567
    // -----------------------------------------------------------------
568

            
569
    #[test]
570
    fn is_layout_internal_matches_css_display_3_table_internals() {
571
        const EXPECTED: [LayoutDisplay; 8] = [
572
            LayoutDisplay::TableRowGroup,
573
            LayoutDisplay::TableHeaderGroup,
574
            LayoutDisplay::TableFooterGroup,
575
            LayoutDisplay::TableRow,
576
            LayoutDisplay::TableColumnGroup,
577
            LayoutDisplay::TableColumn,
578
            LayoutDisplay::TableCell,
579
            LayoutDisplay::TableCaption,
580
        ];
581
        for d in ALL_DISPLAY {
582
            assert_eq!(
583
                d.is_layout_internal(),
584
                EXPECTED.contains(&d),
585
                "is_layout_internal({d:?})"
586
            );
587
        }
588
        // The table wrappers themselves are *not* layout-internal.
589
        assert!(!LayoutDisplay::Table.is_layout_internal());
590
        assert!(!LayoutDisplay::InlineTable.is_layout_internal());
591
    }
592

            
593
    #[test]
594
    fn is_inline_level_matches_an_exact_variant_set() {
595
        const EXPECTED: [LayoutDisplay; 5] = [
596
            LayoutDisplay::Inline,
597
            LayoutDisplay::InlineBlock,
598
            LayoutDisplay::InlineFlex,
599
            LayoutDisplay::InlineTable,
600
            LayoutDisplay::InlineGrid,
601
        ];
602
        for d in ALL_DISPLAY {
603
            assert_eq!(
604
                d.is_inline_level(),
605
                EXPECTED.contains(&d),
606
                "is_inline_level({d:?})"
607
            );
608
        }
609
        // Inner-only keywords default their outer display to block.
610
        assert!(!LayoutDisplay::Flex.is_inline_level());
611
        assert!(!LayoutDisplay::Grid.is_inline_level());
612
        assert!(!LayoutDisplay::Table.is_inline_level());
613
        assert!(!LayoutDisplay::FlowRoot.is_inline_level());
614
    }
615

            
616
    #[test]
617
    fn is_atomic_inline_matches_an_exact_variant_set() {
618
        // Atomic inline-level boxes = inline-level minus the (non-atomic) `Inline`
619
        // box. Every atomic-inline is inline-level; `Inline` is inline-level but
620
        // NOT atomic.
621
        const EXPECTED: [LayoutDisplay; 4] = [
622
            LayoutDisplay::InlineBlock,
623
            LayoutDisplay::InlineFlex,
624
            LayoutDisplay::InlineTable,
625
            LayoutDisplay::InlineGrid,
626
        ];
627
        for d in ALL_DISPLAY {
628
            assert_eq!(
629
                d.is_atomic_inline(),
630
                EXPECTED.contains(&d),
631
                "is_atomic_inline({d:?})"
632
            );
633
            // An atomic inline is always inline-level.
634
            if d.is_atomic_inline() {
635
                assert!(
636
                    d.is_inline_level(),
637
                    "atomic-inline must be inline-level ({d:?})"
638
                );
639
            }
640
        }
641
        assert!(!LayoutDisplay::Inline.is_atomic_inline());
642
        assert!(LayoutDisplay::Inline.is_inline_level());
643
    }
644

            
645
    // -----------------------------------------------------------------
646
    // Cross-predicate invariants
647
    // -----------------------------------------------------------------
648

            
649
    #[test]
650
    fn flex_and_table_contexts_are_mutually_exclusive() {
651
        for d in ALL_DISPLAY {
652
            assert!(
653
                !(d.creates_flex_context() && d.creates_table_context()),
654
                "{d:?} claims to establish both a flex and a table formatting context"
655
            );
656
        }
657
    }
658

            
659
    #[test]
660
    fn layout_internal_and_inline_level_are_mutually_exclusive() {
661
        for d in ALL_DISPLAY {
662
            assert!(
663
                !(d.is_layout_internal() && d.is_inline_level()),
664
                "{d:?} is both layout-internal and inline-level"
665
            );
666
        }
667
    }
668

            
669
    #[test]
670
    fn boxless_displays_establish_and_generate_nothing() {
671
        // `display: none` generates no box at all; `display: contents` generates
672
        // no box for itself, so neither may establish any formatting context nor
673
        // count as an inline-level or layout-internal box.
674
        for d in [LayoutDisplay::None, LayoutDisplay::Contents] {
675
            assert!(!d.creates_block_context(), "{d:?}");
676
            assert!(!d.creates_flex_context(), "{d:?}");
677
            assert!(!d.creates_table_context(), "{d:?}");
678
            assert!(!d.is_layout_internal(), "{d:?}");
679
            assert!(!d.is_inline_level(), "{d:?}");
680
        }
681
    }
682

            
683
    #[test]
684
    fn predicates_on_the_default_instance_do_not_panic() {
685
        // `Default` is `block`: a block-level box establishing a block context.
686
        let d = LayoutDisplay::default();
687
        assert_eq!(d, LayoutDisplay::Block);
688
        assert!(d.creates_block_context());
689
        assert!(!d.creates_flex_context());
690
        assert!(!d.creates_table_context());
691
        assert!(!d.is_layout_internal());
692
        assert!(!d.is_inline_level());
693

            
694
        assert_eq!(LayoutFloat::default(), LayoutFloat::None);
695
    }
696

            
697
    #[test]
698
    fn predicates_are_pure_and_repeatable() {
699
        for d in ALL_DISPLAY {
700
            let snapshot = (
701
                d.creates_block_context(),
702
                d.creates_flex_context(),
703
                d.creates_table_context(),
704
                d.is_layout_internal(),
705
                d.is_inline_level(),
706
            );
707
            for _ in 0..4 {
708
                assert_eq!(
709
                    (
710
                        d.creates_block_context(),
711
                        d.creates_flex_context(),
712
                        d.creates_table_context(),
713
                        d.is_layout_internal(),
714
                        d.is_inline_level(),
715
                    ),
716
                    snapshot,
717
                    "predicates are not deterministic for {d:?}"
718
                );
719
            }
720
        }
721
    }
722

            
723
    #[test]
724
    fn predicates_are_usable_in_const_context() {
725
        // All five predicates are `const fn`; regressing that is a breaking
726
        // change for downstream `const` tables.
727
        const BLOCK_CTX: bool = LayoutDisplay::FlowRoot.creates_block_context();
728
        const FLEX_CTX: bool = LayoutDisplay::InlineFlex.creates_flex_context();
729
        const TABLE_CTX: bool = LayoutDisplay::InlineTable.creates_table_context();
730
        const INTERNAL: bool = LayoutDisplay::TableCell.is_layout_internal();
731
        const INLINE: bool = LayoutDisplay::InlineGrid.is_inline_level();
732
        const _: () = assert!(BLOCK_CTX && FLEX_CTX && TABLE_CTX && INTERNAL && INLINE);
733
    }
734

            
735
    // -----------------------------------------------------------------
736
    // Round-trip: print_as_css_value <-> parse
737
    // -----------------------------------------------------------------
738

            
739
    #[test]
740
    fn display_round_trips_through_its_css_serialization() {
741
        for d in ALL_DISPLAY {
742
            let printed = d.print_as_css_value();
743
            assert_eq!(
744
                parse_layout_display(&printed),
745
                Ok(d),
746
                "round-trip failed for {d:?} (printed as {printed:?})"
747
            );
748
        }
749
    }
750

            
751
    #[test]
752
    fn float_round_trips_through_its_css_serialization() {
753
        for f in ALL_FLOAT {
754
            let printed = f.print_as_css_value();
755
            assert_eq!(
756
                parse_layout_float(&printed),
757
                Ok(f),
758
                "round-trip failed for {f:?} (printed as {printed:?})"
759
            );
760
        }
761
    }
762

            
763
    #[test]
764
    fn display_serializations_are_unique_bare_idents() {
765
        for (i, a) in ALL_DISPLAY.iter().enumerate() {
766
            let printed = a.print_as_css_value();
767
            assert!(!printed.is_empty(), "{a:?} serializes to the empty string");
768
            assert_eq!(printed.trim(), printed, "{a:?} serializes with padding");
769
            assert!(
770
                printed.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
771
                "{a:?} serializes to a non-ident {printed:?}"
772
            );
773
            // A duplicate keyword would make the round-trip above lossy.
774
            for b in &ALL_DISPLAY[i + 1..] {
775
                assert_ne!(
776
                    printed,
777
                    b.print_as_css_value(),
778
                    "{a:?} and {b:?} share a CSS keyword"
779
                );
780
            }
781
        }
782
    }
783

            
784
    #[test]
785
    fn parse_then_print_is_idempotent() {
786
        for keyword in [
787
            "none",
788
            "block",
789
            "inline",
790
            "inline-block",
791
            "flex",
792
            "inline-flex",
793
            "table",
794
            "inline-table",
795
            "table-row-group",
796
            "table-header-group",
797
            "table-footer-group",
798
            "table-row",
799
            "table-column-group",
800
            "table-column",
801
            "table-cell",
802
            "table-caption",
803
            "list-item",
804
            "run-in",
805
            "marker",
806
            "grid",
807
            "inline-grid",
808
            "flow-root",
809
            "contents",
810
        ] {
811
            let parsed = parse_layout_display(keyword)
812
                .unwrap_or_else(|e| panic!("{keyword:?} must parse, got {e}"));
813
            assert_eq!(parsed.print_as_css_value(), keyword);
814
        }
815
        for keyword in ["left", "right", "none"] {
816
            let parsed = parse_layout_float(keyword)
817
                .unwrap_or_else(|e| panic!("{keyword:?} must parse, got {e}"));
818
            assert_eq!(parsed.print_as_css_value(), keyword);
819
        }
820
    }
821

            
822
    // -----------------------------------------------------------------
823
    // parse_layout_display / parse_layout_float: malformed input
824
    // -----------------------------------------------------------------
825

            
826
    #[test]
827
    fn parsers_reject_empty_and_whitespace_only_input() {
828
        for blank in [
829
            "", " ", "   ", "\t", "\n", "\r\n", "\t\n\r ", "\u{c}", "\u{b}",
830
        ] {
831
            assert!(
832
                parse_layout_display(blank).is_err(),
833
                "display accepted blank {blank:?}"
834
            );
835
            assert!(
836
                parse_layout_float(blank).is_err(),
837
                "float accepted blank {blank:?}"
838
            );
839
        }
840
        // The error carries the *trimmed* input, so a blank input reports "".
841
        assert_eq!(
842
            parse_layout_display("   "),
843
            Err(LayoutDisplayParseError::InvalidValue(""))
844
        );
845
        assert_eq!(
846
            parse_layout_float("\t\n"),
847
            Err(LayoutFloatParseError::InvalidValue(""))
848
        );
849
    }
850

            
851
    #[test]
852
    fn display_parser_rejects_garbage_without_panicking() {
853
        for bad in [
854
            "invalid-value",
855
            "display",
856
            "display: block",
857
            "block;",
858
            "block ;",
859
            "block!important",
860
            "block block",
861
            "inline block",
862
            "inline_block",
863
            "inline--block",
864
            "-inline-block",
865
            "inline-block-",
866
            "-webkit-box",
867
            "block flow", // CSS Display 3 two-value syntax is not supported
868
            "inline flow-root",
869
            "table-column-groups",
870
            "tablerow",
871
            "\0",
872
            "blo\0ck",
873
            "block\0",
874
            "inherit",
875
            "initial",
876
            "unset",
877
            "revert",
878
            "\\62 lock", // CSS ident escape
879
            "/*block*/",
880
            "\"block\"",
881
        ] {
882
            assert!(
883
                parse_layout_display(bad).is_err(),
884
                "display accepted garbage {bad:?}"
885
            );
886
        }
887
    }
888

            
889
    #[test]
890
    fn float_parser_rejects_garbage_without_panicking() {
891
        for bad in [
892
            "center",
893
            "float-left",
894
            "left right",
895
            "leftright",
896
            "inline-start",
897
            "inline-end",
898
            "left;",
899
            "left!important",
900
            "\0",
901
            "le\0ft",
902
            "inherit",
903
            "initial",
904
            "footnote",
905
        ] {
906
            assert!(
907
                parse_layout_float(bad).is_err(),
908
                "float accepted garbage {bad:?}"
909
            );
910
        }
911
    }
912

            
913
    #[test]
914
    fn parsers_are_ascii_case_sensitive() {
915
        // NOTE (spec deviation, pinned as *current* behaviour): CSS keywords are
916
        // ASCII case-insensitive, so `display: BLOCK` is valid CSS. These
917
        // parsers match exactly; the requirement asserted here is only that they
918
        // reject deterministically instead of panicking.
919
        for bad in ["BLOCK", "Block", "bLoCk", "INLINE-FLEX", "Table-Cell"] {
920
            assert!(
921
                parse_layout_display(bad).is_err(),
922
                "display unexpectedly accepted {bad:?}"
923
            );
924
        }
925
        for bad in ["LEFT", "Left", "RIGHT", "None"] {
926
            assert!(
927
                parse_layout_float(bad).is_err(),
928
                "float unexpectedly accepted {bad:?}"
929
            );
930
        }
931
    }
932

            
933
    #[test]
934
    fn parsers_trim_leading_and_trailing_whitespace_but_not_junk() {
935
        assert_eq!(
936
            parse_layout_display("  inline-flex  "),
937
            Ok(LayoutDisplay::InlineFlex)
938
        );
939
        assert_eq!(
940
            parse_layout_display("\n\t table-cell \r\n"),
941
            Ok(LayoutDisplay::TableCell)
942
        );
943
        assert_eq!(parse_layout_float("\n right \t"), Ok(LayoutFloat::Right));
944

            
945
        // Interior whitespace and trailing junk are *not* forgiven.
946
        assert!(parse_layout_display("inline - flex").is_err());
947
        assert!(parse_layout_display("table-cell;garbage").is_err());
948
        assert!(parse_layout_float("right;garbage").is_err());
949
    }
950

            
951
    #[test]
952
    fn parsers_trim_unicode_whitespace_but_not_zero_width_characters() {
953
        // `str::trim` uses the Unicode `White_Space` property, a strict superset
954
        // of CSS whitespace (space, tab, LF, CR, FF). NBSP / ideographic space /
955
        // line separator therefore pass as padding - pinned as current behaviour.
956
        assert_eq!(
957
            parse_layout_display("\u{a0}block\u{a0}"),
958
            Ok(LayoutDisplay::Block)
959
        );
960
        assert_eq!(
961
            parse_layout_display("\u{3000}flex\u{2028}"),
962
            Ok(LayoutDisplay::Flex)
963
        );
964
        assert_eq!(
965
            parse_layout_float("\u{a0}left\u{a0}"),
966
            Ok(LayoutFloat::Left)
967
        );
968

            
969
        // U+200B ZERO WIDTH SPACE and U+FEFF are *not* `White_Space`, so they
970
        // survive the trim and must make the value invalid.
971
        assert!(parse_layout_display("\u{200b}block").is_err());
972
        assert!(parse_layout_display("block\u{feff}").is_err());
973
        assert!(parse_layout_float("\u{200b}left").is_err());
974
    }
975

            
976
    #[test]
977
    fn parsers_survive_non_ascii_and_multibyte_input() {
978
        for bad in [
979
            "\u{1F600}",
980
            "block\u{1F600}",
981
            "\u{1F3F3}\u{FE0F}\u{200D}\u{1F308}", // ZWJ emoji sequence
982
            "blocke\u{301}",                      // combining acute accent
983
            "\u{202E}block",                      // RTL override
984
            "block",                         // fullwidth latin
985
            "блок",
986
            "块",
987
            "\u{0}\u{1}\u{2}",
988
            "\u{10FFFF}",
989
        ] {
990
            assert!(
991
                parse_layout_display(bad).is_err(),
992
                "display accepted unicode garbage {bad:?}"
993
            );
994
            assert!(
995
                parse_layout_float(bad).is_err(),
996
                "float accepted unicode garbage {bad:?}"
997
            );
998
        }
999
    }
    #[test]
    fn parsers_reject_boundary_numeric_strings() {
        let numeric = [
            "0".to_string(),
            "-0".to_string(),
            "+0".to_string(),
            "1".to_string(),
            "-1".to_string(),
            i64::MAX.to_string(),
            i64::MIN.to_string(),
            u64::MAX.to_string(),
            format!("{}", f64::MAX),
            format!("{}", f64::MIN_POSITIVE),
            "NaN".to_string(),
            "nan".to_string(),
            "inf".to_string(),
            "-inf".to_string(),
            "infinity".to_string(),
            "1e400".to_string(),
            "-1e-400".to_string(),
            "0x7fffffffffffffff".to_string(),
            "99999999999999999999999999999999".to_string(),
        ];
        for n in &numeric {
            assert!(
                parse_layout_display(n).is_err(),
                "display accepted number {n:?}"
            );
            assert!(
                parse_layout_float(n).is_err(),
                "float accepted number {n:?}"
            );
        }
    }
    #[test]
    fn parsers_do_not_hang_on_extremely_long_input() {
        const LONG: usize = 1_000_000;
        let junk = "x".repeat(LONG);
        assert!(parse_layout_display(&junk).is_err());
        assert!(parse_layout_float(&junk).is_err());
        // A keyword that is *almost* right, one megabyte long.
        let near_miss = format!("block{}", "k".repeat(LONG));
        assert!(parse_layout_display(&near_miss).is_err());
        // Whitespace-only, one megabyte long: trims to "" and must still be Err.
        let blanks = " ".repeat(LONG);
        assert!(parse_layout_display(&blanks).is_err());
        assert!(parse_layout_float(&blanks).is_err());
        // A valid keyword buried in a megabyte of padding on each side.
        let padded = format!("{blanks}table-caption{blanks}");
        assert_eq!(
            parse_layout_display(&padded),
            Ok(LayoutDisplay::TableCaption)
        );
        let padded_float = format!("{blanks}left{blanks}");
        assert_eq!(parse_layout_float(&padded_float), Ok(LayoutFloat::Left));
    }
    #[test]
    fn parsers_do_not_stack_overflow_on_deeply_nested_input() {
        const DEPTH: usize = 10_000;
        let nested = format!("{}{}", "(".repeat(DEPTH), ")".repeat(DEPTH));
        assert!(parse_layout_display(&nested).is_err());
        assert!(parse_layout_float(&nested).is_err());
        let nested_fn = format!("{}block{}", "calc(".repeat(DEPTH), ")".repeat(DEPTH));
        assert!(parse_layout_display(&nested_fn).is_err());
    }
    // -----------------------------------------------------------------
    // Parse errors: payload, formatting, to_contained / to_shared
    // -----------------------------------------------------------------
    #[test]
    fn display_error_reports_the_trimmed_input() {
        assert_eq!(
            parse_layout_display("  bogus  "),
            Err(LayoutDisplayParseError::InvalidValue("bogus"))
        );
        // Unicode padding is trimmed off the reported value as well.
        assert_eq!(
            parse_layout_display("\u{a0}bogus\u{3000}"),
            Err(LayoutDisplayParseError::InvalidValue("bogus"))
        );
    }
    #[test]
    fn float_error_reports_the_trimmed_input() {
        assert_eq!(
            parse_layout_float("  bogus  "),
            Err(LayoutFloatParseError::InvalidValue("bogus"))
        );
    }
    #[test]
    fn parse_errors_display_and_debug_identically() {
        let d = parse_layout_display("bogus").unwrap_err();
        assert_eq!(format!("{d}"), "Invalid display value: \"bogus\"");
        assert_eq!(format!("{d:?}"), format!("{d}"));
        let f = parse_layout_float("bogus").unwrap_err();
        assert_eq!(format!("{f}"), "Invalid float value: \"bogus\"");
        assert_eq!(format!("{f:?}"), format!("{f}"));
        // An empty payload must still format without panicking.
        let empty = parse_layout_display("").unwrap_err();
        assert_eq!(format!("{empty}"), "Invalid display value: \"\"");
    }
    #[test]
    fn display_error_to_contained_to_shared_round_trips() {
        let long = "x".repeat(4096);
        let payloads: [&str; 8] = [
            "",
            " ",
            "bogus",
            "\u{1F600}",
            "a\0b",
            "block block",
            "\"quoted\"",
            &long,
        ];
        for payload in payloads {
            let shared = LayoutDisplayParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                LayoutDisplayParseErrorOwned::InvalidValue(payload.to_string().into()),
                "to_contained lost the payload {payload:?}"
            );
            assert_eq!(
                owned.to_shared(),
                shared,
                "to_shared did not restore the payload {payload:?}"
            );
            // Byte-for-byte, not just "equal enough".
            let LayoutDisplayParseErrorOwned::InvalidValue(s) = &owned;
            assert_eq!(s.as_str(), payload);
        }
    }
    #[test]
    fn float_error_to_contained_to_shared_round_trips() {
        let long = "y".repeat(4096);
        let payloads: [&str; 6] = ["", " ", "bogus", "\u{1F600}", "a\0b", &long];
        for payload in payloads {
            let shared = LayoutFloatParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                LayoutFloatParseErrorOwned::InvalidValue(payload.to_string().into()),
                "to_contained lost the payload {payload:?}"
            );
            assert_eq!(
                owned.to_shared(),
                shared,
                "to_shared did not restore the payload {payload:?}"
            );
            let LayoutFloatParseErrorOwned::InvalidValue(s) = &owned;
            assert_eq!(s.as_str(), payload);
        }
    }
    #[test]
    fn error_conversions_survive_a_borrowed_owned_borrowed_cycle() {
        // The owned form must outlive the &str it came from; converting back
        // must not resurrect a dangling borrow.
        let owned = {
            let input = format!("{}-bogus", "very-long-".repeat(64));
            parse_layout_display(&input).unwrap_err().to_contained()
        };
        let shared = owned.to_shared();
        assert_eq!(shared.to_contained(), owned);
        assert!(format!("{shared}").starts_with("Invalid display value: \"very-long-"));
    }
    // -----------------------------------------------------------------
    // Positive controls
    // -----------------------------------------------------------------
    #[test]
    fn valid_minimal_inputs_parse() {
        assert_eq!(parse_layout_display("none"), Ok(LayoutDisplay::None));
        assert_eq!(
            parse_layout_display("contents"),
            Ok(LayoutDisplay::Contents)
        );
        assert_eq!(parse_layout_display("run-in"), Ok(LayoutDisplay::RunIn));
        assert_eq!(parse_layout_display("marker"), Ok(LayoutDisplay::Marker));
        assert_eq!(parse_layout_float("none"), Ok(LayoutFloat::None));
        assert_eq!(parse_layout_float("left"), Ok(LayoutFloat::Left));
    }
}