1
//! CSS properties related to dimensions and sizing.
2
//!
3
//! Key types: [`LayoutWidth`] / [`LayoutHeight`] (support `auto`, pixel values,
4
//! `min-content`, `max-content`, `fit-content()`, and `calc()` expressions),
5
//! [`LayoutMinWidth`], [`LayoutMinHeight`], [`LayoutMaxWidth`], [`LayoutMaxHeight`]
6
//! (simple pixel-value constraints), and [`LayoutBoxSizing`].
7
//!
8
//! `calc()` expressions use a flat stack-machine representation via [`CalcAstItem`]
9
//! — see its documentation for the encoding scheme. The layout solver in
10
//! `layout/src/solver3/calc.rs` evaluates these at resolve time.
11

            
12
use alloc::{
13
    string::{String, ToString},
14
    vec::Vec,
15
};
16

            
17
use crate::{
18
    impl_option, impl_option_inner, impl_vec, impl_vec_clone, impl_vec_debug, impl_vec_eq,
19
    impl_vec_hash, impl_vec_mut, impl_vec_ord, impl_vec_partialeq, impl_vec_partialord,
20
    props::{
21
        basic::pixel::{CssPixelValueParseError, CssPixelValueParseErrorOwned, PixelValue},
22
        formatter::PrintAsCssValue,
23
        macros::PixelValueTaker,
24
    },
25
};
26

            
27
// -- Calc AST --
28
#[allow(variant_size_differences)]
29
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
30
// disparity accepted
31
/// A single item in a `calc()` expression, stored as a flat stack-machine representation.
32
///
33
/// The expression `calc(33.333% - 10px)` is stored as:
34
/// ```text
35
/// [Value(33.333%), Sub, Value(10px)]
36
/// ```
37
///
38
/// For nested expressions like `calc(100% - (20px + 5%))`:
39
/// ```text
40
/// [Value(100%), Sub, BraceOpen, Value(20px), Add, Value(5%), BraceClose]
41
/// ```
42
///
43
/// **Resolution**: Walk left to right. When `BraceClose` is hit, resolve everything
44
/// back to the matching `BraceOpen`, replace that span with a single `Value`, and continue.
45
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
46
#[repr(C, u8)]
47
pub enum CalcAstItem {
48
    /// A literal value (e.g. `10px`, `33.333%`, `2em`)
49
    Value(PixelValue),
50
    /// `+` operator
51
    Add,
52
    /// `-` operator
53
    Sub,
54
    /// `*` operator
55
    Mul,
56
    /// `/` operator
57
    Div,
58
    /// `(` — opens a sub-expression
59
    BraceOpen,
60
    /// `)` — closes a sub-expression; triggers resolution of the inner span
61
    BraceClose,
62
}
63

            
64
/// C-compatible `Vec<CalcAstItem>` for FFI interop.
65
impl_vec!(
66
    CalcAstItem,
67
    CalcAstItemVec,
68
    CalcAstItemVecDestructor,
69
    CalcAstItemVecDestructorType,
70
    CalcAstItemVecSlice,
71
    OptionCalcAstItem
72
);
73
impl_vec_clone!(CalcAstItem, CalcAstItemVec, CalcAstItemVecDestructor);
74
impl_vec_debug!(CalcAstItem, CalcAstItemVec);
75
impl_vec_partialeq!(CalcAstItem, CalcAstItemVec);
76
impl_vec_eq!(CalcAstItem, CalcAstItemVec);
77
impl_vec_partialord!(CalcAstItem, CalcAstItemVec);
78
impl_vec_ord!(CalcAstItem, CalcAstItemVec);
79
impl_vec_hash!(CalcAstItem, CalcAstItemVec);
80
impl_vec_mut!(CalcAstItem, CalcAstItemVec);
81

            
82
impl_option!(
83
    CalcAstItem,
84
    OptionCalcAstItem,
85
    copy = false,
86
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
87
);
88

            
89
/// Parse a `calc()` inner expression (the part between the parentheses) into
90
/// a flat `CalcAstItemVec` suitable for stack-machine evaluation.
91
///
92
/// Examples:
93
/// - `"100% - 20px"` → `[Value(100%), Sub, Value(20px)]`
94
/// - `"(100% - 20px) / 3"` → `[BraceOpen, Value(100%), Sub, Value(20px), BraceClose, Div,
95
///   Value(3)]`
96
///
97
/// **Tokenisation rules**:
98
///  - Whitespace is skipped between tokens.
99
///  - `+`, `-`, `*`, `/` are operators (but `-` at the start of a number is part of the number
100
///    literal, e.g. `-10px`).
101
///  - `(` / `)` produce `BraceOpen` / `BraceClose`.
102
///  - Anything else is parsed as a `PixelValue` via `parse_pixel_value`.
103
#[cfg(feature = "parser")]
104
5074
fn parse_calc_expression(input: &str) -> Result<CalcAstItemVec, ()> {
105
    use crate::props::basic::pixel::parse_pixel_value;
106

            
107
5074
    let mut items: Vec<CalcAstItem> = Vec::new();
108
5074
    let input = input.trim();
109
5074
    let bytes = input.as_bytes();
110
5074
    let mut i = 0;
111

            
112
271302
    while i < bytes.len() {
113
        // Skip whitespace
114
269779
        if bytes[i].is_ascii_whitespace() {
115
101193
            i += 1;
116
101193
            continue;
117
168586
        }
118

            
119
168586
        match bytes[i] {
120
50683
            b'+' => {
121
50683
                items.push(CalcAstItem::Add);
122
50683
                i += 1;
123
50683
            }
124
680
            b'*' => {
125
680
                items.push(CalcAstItem::Mul);
126
680
                i += 1;
127
680
            }
128
678
            b'/' => {
129
678
                items.push(CalcAstItem::Div);
130
678
                i += 1;
131
678
            }
132
35691
            b'(' => {
133
35691
                items.push(CalcAstItem::BraceOpen);
134
35691
                i += 1;
135
35691
            }
136
25708
            b')' => {
137
25708
                items.push(CalcAstItem::BraceClose);
138
25708
                i += 1;
139
25708
            }
140
            b'-' => {
141
                // Decide: is this a subtraction operator or a negative number?
142
                // It's a negative number if:
143
                //   - it's the first token, OR
144
                //   - the previous token is an operator or BraceOpen
145
606
                let is_negative_number = items.is_empty()
146
192
                    || matches!(
147
304
                        items.last(),
148
                        Some(
149
                            CalcAstItem::Add
150
                                | CalcAstItem::Sub
151
                                | CalcAstItem::Mul
152
                                | CalcAstItem::Div
153
                                | CalcAstItem::BraceOpen
154
                        )
155
                    );
156

            
157
606
                if is_negative_number {
158
                    // Parse as negative number value
159
414
                    let rest = &input[i..];
160
414
                    let end = find_value_end(rest);
161
414
                    if end == 0 {
162
                        return Err(());
163
414
                    }
164
414
                    let val_str = &rest[..end];
165
414
                    let pv = parse_pixel_value(val_str).map_err(|_| ())?;
166
70
                    items.push(CalcAstItem::Value(pv));
167
70
                    i += end;
168
192
                } else {
169
192
                    items.push(CalcAstItem::Sub);
170
192
                    i += 1;
171
192
                }
172
            }
173
            _ => {
174
                // Must be a numeric value (e.g. 100%, 20px, 3, 1.5em)
175
54540
                let rest = &input[i..];
176
54540
                let end = find_value_end(rest);
177
54540
                if end == 0 {
178
996
                    return Err(());
179
53544
                }
180
53544
                let val_str = &rest[..end];
181
53544
                let pv = parse_pixel_value(val_str).map_err(|_| ())?;
182
51333
                items.push(CalcAstItem::Value(pv));
183
51333
                i += end;
184
            }
185
        }
186
    }
187

            
188
1523
    if items.is_empty() {
189
15
        return Err(());
190
1508
    }
191

            
192
1508
    Ok(CalcAstItemVec::from(items))
193
5074
}
194

            
195
/// Find the end of a numeric value token in a `calc()` expression.
196
/// Returns the byte offset where the value ends.
197
#[cfg(feature = "parser")]
198
54988
fn find_value_end(s: &str) -> usize {
199
54988
    let bytes = s.as_bytes();
200
54988
    let mut i = 0;
201

            
202
    // Optional leading sign
203
54988
    if i < bytes.len() && (bytes[i] == b'-' || bytes[i] == b'+') {
204
419
        i += 1;
205
54569
    }
206

            
207
    // Digits and decimal point
208
507658
    while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
209
452670
        i += 1;
210
452670
    }
211

            
212
    // Unit suffix (alphabetic characters like px, %, em, rem, vw, vh, etc.)
213
358831
    while i < bytes.len() && (bytes[i].is_ascii_alphabetic() || bytes[i] == b'%') {
214
303843
        i += 1;
215
303843
    }
216

            
217
54988
    i
218
54988
}
219

            
220
/// Format a `CalcAstItemVec` as a CSS `calc(...)` string.
221
724
fn calc_ast_to_css_string(items: &CalcAstItemVec) -> String {
222
724
    let inner: Vec<String> = items
223
724
        .iter()
224
131711
        .map(|i| match i {
225
540
            CalcAstItem::Value(v) => v.to_string(),
226
218
            CalcAstItem::Add => "+".to_string(),
227
67
            CalcAstItem::Sub => "-".to_string(),
228
217
            CalcAstItem::Mul => "*".to_string(),
229
216
            CalcAstItem::Div => "/".to_string(),
230
115219
            CalcAstItem::BraceOpen => "(".to_string(),
231
15234
            CalcAstItem::BraceClose => ")".to_string(),
232
131711
        })
233
724
        .collect();
234
724
    alloc::format!("calc({})", inner.join(" "))
235
724
}
236

            
237
// -- Type Definitions --
238

            
239
macro_rules! define_dimension_property {
240
    ($struct_name:ident, $default_fn:expr) => {
241
        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
242
        #[repr(C)]
243
        pub struct $struct_name {
244
            pub inner: PixelValue,
245
        }
246

            
247
        impl Default for $struct_name {
248
4
            fn default() -> Self {
249
4
                $default_fn()
250
4
            }
251
        }
252

            
253
        impl PixelValueTaker for $struct_name {
254
22368
            fn from_pixel_value(inner: PixelValue) -> Self {
255
22368
                Self { inner }
256
22368
            }
257
        }
258

            
259
        impl_pixel_value!($struct_name);
260

            
261
        impl PrintAsCssValue for $struct_name {
262
            fn print_as_css_value(&self) -> String {
263
                self.inner.to_string()
264
            }
265
        }
266
    };
267
}
268

            
269
macro_rules! define_sizing_enum {
270
    ($name:ident) => {
271
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
272
        #[repr(C, u8)]
273
        #[derive(Default)]
274
        pub enum $name {
275
            #[default]
276
            Auto,
277
            Px(PixelValue),
278
            MinContent,
279
            MaxContent,
280
            /// `fit-content(<length-percentage>)` = `min(max-content, max(min-content,
281
            /// <length-percentage>))`
282
            FitContent(PixelValue),
283
            /// `calc()` expression stored as a flat stack-machine AST
284
            Calc(CalcAstItemVec),
285
        }
286

            
287
        impl PixelValueTaker for $name {
288
            fn from_pixel_value(inner: PixelValue) -> Self {
289
                $name::Px(inner)
290
            }
291
        }
292

            
293
        impl PrintAsCssValue for $name {
294
438
            fn print_as_css_value(&self) -> String {
295
438
                match self {
296
1
                    $name::Auto => "auto".to_string(),
297
431
                    $name::Px(v) => v.to_string(),
298
1
                    $name::MinContent => "min-content".to_string(),
299
1
                    $name::MaxContent => "max-content".to_string(),
300
1
                    $name::FitContent(v) => alloc::format!("fit-content({})", v),
301
3
                    $name::Calc(items) => calc_ast_to_css_string(items),
302
                }
303
438
            }
304
        }
305

            
306
        impl $name {
307
            #[must_use]
308
7786
            pub fn px(value: f32) -> Self {
309
7786
                $name::Px(PixelValue::px(value))
310
7786
            }
311

            
312
            #[must_use]
313
635334
            pub const fn const_px(value: isize) -> Self {
314
635334
                $name::Px(PixelValue::const_px(value))
315
635334
            }
316

            
317
            #[must_use]
318
1569
            pub fn interpolate(&self, other: &Self, t: f32) -> Self {
319
1569
                match (self, other) {
320
1564
                    ($name::Px(a), $name::Px(b)) => $name::Px(a.interpolate(b, t)),
321
                    ($name::FitContent(a), $name::FitContent(b)) => {
322
                        $name::FitContent(a.interpolate(b, t))
323
                    }
324
                    (_, $name::Px(b)) if t >= 0.5 => $name::Px(*b),
325
                    ($name::Px(a), _) if t < 0.5 => $name::Px(*a),
326
                    ($name::Auto, $name::Auto) => $name::Auto,
327
5
                    (a, _) if t < 0.5 => a.clone(),
328
3
                    (_, b) => b.clone(),
329
                }
330
1569
            }
331
        }
332
    };
333
}
334

            
335
define_sizing_enum!(LayoutWidth);
336
define_sizing_enum!(LayoutHeight);
337

            
338
/// CSS `min-width` property. Defaults to `0px`.
339
define_dimension_property!(LayoutMinWidth, || Self {
340
1
    inner: PixelValue::zero()
341
1
});
342
/// CSS `min-height` property. Defaults to `0px`.
343
define_dimension_property!(LayoutMinHeight, || Self {
344
1
    inner: PixelValue::zero()
345
1
});
346
/// CSS `max-width` property. Defaults to `f32::MAX` pixels (i.e. unconstrained).
347
///
348
/// NOTE: The layout solver must handle `f32::MAX` gracefully — adding
349
/// padding/margin to this sentinel would overflow to infinity.
350
define_dimension_property!(LayoutMaxWidth, || Self {
351
1
    inner: PixelValue::px(core::f32::MAX)
352
1
});
353
/// CSS `max-height` property. Defaults to `f32::MAX` pixels (i.e. unconstrained).
354
///
355
/// NOTE: The layout solver must handle `f32::MAX` gracefully — adding
356
/// padding/margin to this sentinel would overflow to infinity.
357
define_dimension_property!(LayoutMaxHeight, || Self {
358
1
    inner: PixelValue::px(core::f32::MAX)
359
1
});
360

            
361
/// Represents a `box-sizing` attribute
362
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
363
#[repr(C)]
364
#[derive(Default)]
365
pub enum LayoutBoxSizing {
366
    #[default]
367
    ContentBox,
368
    BorderBox,
369
}
370

            
371
impl PrintAsCssValue for LayoutBoxSizing {
372
2
    fn print_as_css_value(&self) -> String {
373
2
        String::from(match self {
374
1
            Self::ContentBox => "content-box",
375
1
            Self::BorderBox => "border-box",
376
        })
377
2
    }
378
}
379

            
380
// -- Parser --
381

            
382
#[cfg(feature = "parser")]
383
pub mod parser {
384

            
385
    use alloc::string::ToString;
386

            
387
    #[allow(clippy::wildcard_imports)]
388
    // parser submodule reuses the parent module's value types
389
    use super::*;
390
    use crate::{corety::AzString, props::basic::pixel::parse_pixel_value};
391

            
392
    macro_rules! define_pixel_dimension_parser {
393
        ($fn_name:ident, $struct_name:ident, $error_name:ident, $error_owned_name:ident) => {
394
            #[derive(Clone, PartialEq, Eq)]
395
            pub enum $error_name<'a> {
396
                PixelValue(CssPixelValueParseError<'a>),
397
            }
398

            
399
            impl_debug_as_display!($error_name<'a>);
400
            impl_display! { $error_name<'a>, {
401
                PixelValue(e) => format!("{}", e),
402
            }}
403

            
404
            impl_from! { CssPixelValueParseError<'a>, $error_name::PixelValue }
405

            
406
            #[derive(Debug, Clone, PartialEq, Eq)]
407
            #[repr(C, u8)]
408
            pub enum $error_owned_name {
409
                PixelValue(CssPixelValueParseErrorOwned),
410
            }
411

            
412
            impl $error_name<'_> {
413
                #[must_use]
414
6
                pub fn to_contained(&self) -> $error_owned_name {
415
6
                    match self {
416
6
                        $error_name::PixelValue(e) => {
417
6
                            $error_owned_name::PixelValue(e.to_contained())
418
                        }
419
                    }
420
6
                }
421
            }
422

            
423
            impl $error_owned_name {
424
                #[must_use]
425
6
                pub fn to_shared(&self) -> $error_name<'_> {
426
6
                    match self {
427
6
                        $error_owned_name::PixelValue(e) => $error_name::PixelValue(e.to_shared()),
428
                    }
429
6
                }
430
            }
431

            
432
            /// # Errors
433
            ///
434
            /// Returns an error if `input` is not a valid CSS value for this property.
435
4817
            pub fn $fn_name(input: &str) -> Result<$struct_name, $error_name<'_>> {
436
4817
                parse_pixel_value(input)
437
4817
                    .map(|v| $struct_name { inner: v })
438
4817
                    .map_err($error_name::PixelValue)
439
4817
            }
440
        };
441
    }
442

            
443
    macro_rules! define_sizing_parser {
444
        (
445
            $fn_name:ident,
446
            $enum_name:ident,
447
            $error_name:ident,
448
            $error_owned_name:ident,
449
            $keyword_label:expr
450
        ) => {
451
            #[derive(Clone, PartialEq, Eq)]
452
            pub enum $error_name<'a> {
453
                PixelValue(CssPixelValueParseError<'a>),
454
                InvalidKeyword(&'a str),
455
            }
456

            
457
            impl_debug_as_display!($error_name<'a>);
458
            impl_display! { $error_name<'a>, {
459
                PixelValue(e) => format!("{}", e),
460
                InvalidKeyword(k) => format!("Invalid {} keyword: \"{}\"", $keyword_label, k),
461
            }}
462

            
463
            impl_from! { CssPixelValueParseError<'a>, $error_name::PixelValue }
464

            
465
            #[derive(Debug, Clone, PartialEq, Eq)]
466
            #[repr(C, u8)]
467
            pub enum $error_owned_name {
468
                PixelValue(CssPixelValueParseErrorOwned),
469
                InvalidKeyword(AzString),
470
            }
471

            
472
            impl $error_name<'_> {
473
                #[must_use]
474
5
                pub fn to_contained(&self) -> $error_owned_name {
475
5
                    match self {
476
4
                        $error_name::PixelValue(e) => {
477
4
                            $error_owned_name::PixelValue(e.to_contained())
478
                        }
479
1
                        $error_name::InvalidKeyword(k) => {
480
1
                            $error_owned_name::InvalidKeyword(k.to_string().into())
481
                        }
482
                    }
483
5
                }
484
            }
485

            
486
            impl $error_owned_name {
487
                #[must_use]
488
5
                pub fn to_shared(&self) -> $error_name<'_> {
489
5
                    match self {
490
4
                        $error_owned_name::PixelValue(e) => $error_name::PixelValue(e.to_shared()),
491
1
                        $error_owned_name::InvalidKeyword(k) => $error_name::InvalidKeyword(k),
492
                    }
493
5
                }
494
            }
495

            
496
            /// # Errors
497
            ///
498
            /// Returns an error if `input` is not a valid CSS value for this property.
499
102691
            pub fn $fn_name(input: &str) -> Result<$enum_name, $error_name<'_>> {
500
102691
                let trimmed = input.trim();
501
102670
                match trimmed {
502
102691
                    "auto" => Ok($enum_name::Auto),
503
102689
                    "min-content" => Ok($enum_name::MinContent),
504
102687
                    "max-content" => Ok($enum_name::MaxContent),
505
102685
                    s if s.starts_with("fit-content(") && s.ends_with(')') => {
506
15
                        let inner = &s[12..s.len() - 1].trim();
507
15
                        parse_pixel_value(inner)
508
15
                            .map(|pv| {
509
5
                                if pv.number.get() < 0.0 {
510
2
                                    $enum_name::FitContent(PixelValue::zero())
511
                                } else {
512
3
                                    $enum_name::FitContent(pv)
513
                                }
514
5
                            })
515
15
                            .map_err($error_name::PixelValue)
516
                    }
517
102670
                    s if s.starts_with("calc(") && s.ends_with(')') => {
518
48
                        let inner = &s[5..s.len() - 1];
519
48
                        parse_calc_expression(inner)
520
48
                            .map($enum_name::Calc)
521
48
                            .map_err(|_| $error_name::InvalidKeyword(input))
522
                    }
523
102622
                    _ => parse_pixel_value(trimmed)
524
102622
                        .map($enum_name::Px)
525
102622
                        .map_err($error_name::PixelValue),
526
                }
527
102691
            }
528
        };
529
    }
530

            
531
    define_sizing_parser!(
532
        parse_layout_width,
533
        LayoutWidth,
534
        LayoutWidthParseError,
535
        LayoutWidthParseErrorOwned,
536
        "width"
537
    );
538
    define_sizing_parser!(
539
        parse_layout_height,
540
        LayoutHeight,
541
        LayoutHeightParseError,
542
        LayoutHeightParseErrorOwned,
543
        "height"
544
    );
545
    define_pixel_dimension_parser!(
546
        parse_layout_min_width,
547
        LayoutMinWidth,
548
        LayoutMinWidthParseError,
549
        LayoutMinWidthParseErrorOwned
550
    );
551
    define_pixel_dimension_parser!(
552
        parse_layout_min_height,
553
        LayoutMinHeight,
554
        LayoutMinHeightParseError,
555
        LayoutMinHeightParseErrorOwned
556
    );
557
    define_pixel_dimension_parser!(
558
        parse_layout_max_width,
559
        LayoutMaxWidth,
560
        LayoutMaxWidthParseError,
561
        LayoutMaxWidthParseErrorOwned
562
    );
563
    define_pixel_dimension_parser!(
564
        parse_layout_max_height,
565
        LayoutMaxHeight,
566
        LayoutMaxHeightParseError,
567
        LayoutMaxHeightParseErrorOwned
568
    );
569

            
570
    // -- Box Sizing Parser --
571

            
572
    #[derive(Clone, PartialEq, Eq)]
573
    pub enum LayoutBoxSizingParseError<'a> {
574
        InvalidValue(&'a str),
575
    }
576

            
577
    impl_debug_as_display!(LayoutBoxSizingParseError<'a>);
578
    impl_display! { LayoutBoxSizingParseError<'a>, {
579
        InvalidValue(v) => format!("Invalid box-sizing value: \"{}\"", v),
580
    }}
581

            
582
    #[derive(Debug, Clone, PartialEq, Eq)]
583
    #[repr(C, u8)]
584
    pub enum LayoutBoxSizingParseErrorOwned {
585
        InvalidValue(AzString),
586
    }
587

            
588
    impl LayoutBoxSizingParseError<'_> {
589
        #[must_use]
590
7
        pub fn to_contained(&self) -> LayoutBoxSizingParseErrorOwned {
591
7
            match self {
592
7
                LayoutBoxSizingParseError::InvalidValue(s) => {
593
7
                    LayoutBoxSizingParseErrorOwned::InvalidValue((*s).to_string().into())
594
                }
595
            }
596
7
        }
597
    }
598

            
599
    impl LayoutBoxSizingParseErrorOwned {
600
        #[must_use]
601
7
        pub fn to_shared(&self) -> LayoutBoxSizingParseError<'_> {
602
7
            match self {
603
7
                Self::InvalidValue(s) => LayoutBoxSizingParseError::InvalidValue(s),
604
            }
605
7
        }
606
    }
607

            
608
    /// # Errors
609
    ///
610
    /// Returns an error if `input` is not a valid CSS `box-sizing` value.
611
1995
    pub fn parse_layout_box_sizing(
612
1995
        input: &str,
613
1995
    ) -> Result<LayoutBoxSizing, LayoutBoxSizingParseError<'_>> {
614
1995
        match input.trim() {
615
1995
            "content-box" => Ok(LayoutBoxSizing::ContentBox),
616
1992
            "border-box" => Ok(LayoutBoxSizing::BorderBox),
617
36
            other => Err(LayoutBoxSizingParseError::InvalidValue(other)),
618
        }
619
1995
    }
620
}
621

            
622
#[cfg(feature = "parser")]
623
pub use self::parser::*;
624

            
625
#[cfg(all(test, feature = "parser"))]
626
mod tests {
627
    use super::*;
628
    use crate::props::basic::pixel::PixelValue;
629

            
630
    #[test]
631
1
    fn test_parse_layout_width() {
632
1
        assert_eq!(
633
1
            parse_layout_width("150px").unwrap(),
634
1
            LayoutWidth::Px(PixelValue::px(150.0))
635
        );
636
1
        assert_eq!(
637
1
            parse_layout_width("2.5em").unwrap(),
638
1
            LayoutWidth::Px(PixelValue::em(2.5))
639
        );
640
1
        assert_eq!(
641
1
            parse_layout_width("75%").unwrap(),
642
1
            LayoutWidth::Px(PixelValue::percent(75.0))
643
        );
644
1
        assert_eq!(
645
1
            parse_layout_width("0").unwrap(),
646
1
            LayoutWidth::Px(PixelValue::px(0.0))
647
        );
648
1
        assert_eq!(
649
1
            parse_layout_width("  100pt  ").unwrap(),
650
1
            LayoutWidth::Px(PixelValue::pt(100.0))
651
        );
652
1
        assert_eq!(
653
1
            parse_layout_width("min-content").unwrap(),
654
            LayoutWidth::MinContent
655
        );
656
1
        assert_eq!(
657
1
            parse_layout_width("max-content").unwrap(),
658
            LayoutWidth::MaxContent
659
        );
660
1
    }
661

            
662
    #[test]
663
1
    fn test_parse_layout_height_invalid() {
664
        // "auto" is now a valid value for height (CSS spec)
665
1
        assert!(parse_layout_height("auto").is_ok());
666
        // Liberal parsing accepts whitespace between number and unit
667
1
        assert!(parse_layout_height("150 px").is_ok());
668
1
        assert!(parse_layout_height("px").is_err());
669
1
        assert!(parse_layout_height("invalid").is_err());
670
1
    }
671

            
672
    #[test]
673
1
    fn test_parse_layout_box_sizing() {
674
1
        assert_eq!(
675
1
            parse_layout_box_sizing("content-box").unwrap(),
676
            LayoutBoxSizing::ContentBox
677
        );
678
1
        assert_eq!(
679
1
            parse_layout_box_sizing("border-box").unwrap(),
680
            LayoutBoxSizing::BorderBox
681
        );
682
1
        assert_eq!(
683
1
            parse_layout_box_sizing("  border-box  ").unwrap(),
684
            LayoutBoxSizing::BorderBox
685
        );
686
1
    }
687

            
688
    #[test]
689
1
    fn test_parse_layout_box_sizing_invalid() {
690
1
        assert!(parse_layout_box_sizing("padding-box").is_err());
691
1
        assert!(parse_layout_box_sizing("borderbox").is_err());
692
1
        assert!(parse_layout_box_sizing("").is_err());
693
1
    }
694
}
695

            
696
#[cfg(all(test, feature = "parser"))]
697
mod autotest_generated {
698
    use alloc::{
699
        format,
700
        string::{String, ToString},
701
        vec,
702
        vec::Vec,
703
    };
704

            
705
    #[allow(clippy::wildcard_imports)]
706
    use super::*;
707

            
708
    /// Maps a `CalcAstItem` to a discriminant tag, so tests can compare the *shape*
709
    /// of two ASTs without depending on `FloatValue`'s 1/1000 quantisation.
710
    const fn tag(item: &CalcAstItem) -> u8 {
711
        match item {
712
            CalcAstItem::Value(_) => 0,
713
            CalcAstItem::Add => 1,
714
            CalcAstItem::Sub => 2,
715
            CalcAstItem::Mul => 3,
716
            CalcAstItem::Div => 4,
717
            CalcAstItem::BraceOpen => 5,
718
            CalcAstItem::BraceClose => 6,
719
        }
720
    }
721

            
722
    fn shape(items: &CalcAstItemVec) -> Vec<u8> {
723
        items.iter().map(tag).collect()
724
    }
725

            
726
    fn calc_items(w: &LayoutWidth) -> Vec<CalcAstItem> {
727
        match w {
728
            LayoutWidth::Calc(items) => items.as_slice().to_vec(),
729
            other => panic!("expected LayoutWidth::Calc, got {other:?}"),
730
        }
731
    }
732

            
733
    fn shape_of_width(w: &LayoutWidth) -> Vec<u8> {
734
        calc_items(w).iter().map(tag).collect()
735
    }
736

            
737
    // ---------------------------------------------------------------------
738
    // parse_calc_expression — malformed / boundary / unicode
739
    // ---------------------------------------------------------------------
740

            
741
    #[test]
742
    fn calc_empty_and_whitespace_only_input_is_err() {
743
        assert!(parse_calc_expression("").is_err());
744
        assert!(parse_calc_expression("   ").is_err());
745
        assert!(parse_calc_expression("\t\n\r ").is_err());
746
    }
747

            
748
    #[test]
749
    fn calc_garbage_input_is_err_never_panics() {
750
        for garbage in [
751
            "???",
752
            "@@@",
753
            "px",
754
            "em",
755
            "%",
756
            "#",
757
            "1px;",
758
            "abc",
759
            "!!!",
760
            "\0",
761
            "\u{7f}",
762
            ",",
763
            ";",
764
            "1,2",
765
            "10 px 20 %%",
766
            "--",
767
            "-",
768
            "-.",
769
            "1..px",
770
            "1.2.3px",
771
        ] {
772
            assert!(
773
                parse_calc_expression(garbage).is_err(),
774
                "expected Err for {garbage:?}"
775
            );
776
        }
777
    }
778

            
779
    #[test]
780
    fn calc_valid_minimal_matches_documented_ast() {
781
        // Positive control, straight out of the doc comment on `parse_calc_expression`.
782
        let parsed = parse_calc_expression("100% - 20px").unwrap();
783
        let expected = vec![
784
            CalcAstItem::Value(PixelValue::percent(100.0)),
785
            CalcAstItem::Sub,
786
            CalcAstItem::Value(PixelValue::px(20.0)),
787
        ];
788
        assert_eq!(parsed.as_slice(), expected.as_slice());
789
    }
790

            
791
    #[test]
792
    fn calc_documented_nested_example_parses_exactly() {
793
        let parsed = parse_calc_expression("(100% - 20px) / 3").unwrap();
794
        let expected = vec![
795
            CalcAstItem::BraceOpen,
796
            CalcAstItem::Value(PixelValue::percent(100.0)),
797
            CalcAstItem::Sub,
798
            CalcAstItem::Value(PixelValue::px(20.0)),
799
            CalcAstItem::BraceClose,
800
            CalcAstItem::Div,
801
            // A bare `3` is a unit-less number and becomes `px`.
802
            CalcAstItem::Value(PixelValue::px(3.0)),
803
        ];
804
        assert_eq!(parsed.as_slice(), expected.as_slice());
805
    }
806

            
807
    #[test]
808
    fn calc_minus_disambiguates_between_sub_and_negative_literal() {
809
        // Leading `-` is part of the literal.
810
        assert_eq!(
811
            parse_calc_expression("-10px").unwrap().as_slice(),
812
            [CalcAstItem::Value(PixelValue::px(-10.0))].as_slice()
813
        );
814
        // `-` after an operator is part of the literal.
815
        assert_eq!(
816
            parse_calc_expression("100% * -2").unwrap().as_slice(),
817
            [
818
                CalcAstItem::Value(PixelValue::percent(100.0)),
819
                CalcAstItem::Mul,
820
                CalcAstItem::Value(PixelValue::px(-2.0)),
821
            ]
822
            .as_slice()
823
        );
824
        // `-` after `(` is part of the literal.
825
        assert_eq!(
826
            parse_calc_expression("(-5px)").unwrap().as_slice(),
827
            [
828
                CalcAstItem::BraceOpen,
829
                CalcAstItem::Value(PixelValue::px(-5.0)),
830
                CalcAstItem::BraceClose,
831
            ]
832
            .as_slice()
833
        );
834
        // `-` after a value is subtraction — even when written as `5px -10px`, so a
835
        // whitespace-separated negative literal silently becomes a subtraction.
836
        assert_eq!(
837
            parse_calc_expression("5px -10px").unwrap().as_slice(),
838
            [
839
                CalcAstItem::Value(PixelValue::px(5.0)),
840
                CalcAstItem::Sub,
841
                CalcAstItem::Value(PixelValue::px(10.0)),
842
            ]
843
            .as_slice()
844
        );
845
        // `-` after `)` is subtraction.
846
        assert_eq!(
847
            shape(&parse_calc_expression("(1px) - 2px").unwrap()),
848
            vec![5, 0, 6, 2, 0]
849
        );
850
    }
851

            
852
    #[test]
853
    fn calc_leading_minus_followed_by_space_is_rejected() {
854
        // `- 10px` at the start is treated as a negative literal `-`, which fails to parse.
855
        assert!(parse_calc_expression("- 10px").is_err());
856
        assert!(parse_calc_expression("(- 10px)").is_err());
857
    }
858

            
859
    #[test]
860
    fn calc_unicode_input_is_rejected_without_panic() {
861
        // Every one of these puts a multi-byte char where the tokeniser slices `&input[i..]`;
862
        // if `find_value_end` ever returned a non-char-boundary offset this would panic.
863
        for input in [
864
            "\u{1F600}",          // emoji
865
            "100px\u{1F600}",     // emoji after a valid token
866
            "10px\u{0301}",       // combining acute accent
867
            "10px\u{00A0}- 5px",  // non-breaking space is NOT ascii whitespace
868
            "\u{FF11}\u{FF10}px", // full-width digits
869
            "100%",            // full-width digits + ascii percent
870
            "π",
871
            "10\u{2212}5",  // U+2212 MINUS SIGN, not ASCII '-'
872
            "\u{202E}10px", // RTL override
873
            "e\u{0301}m",
874
        ] {
875
            assert!(
876
                parse_calc_expression(input).is_err(),
877
                "expected Err for {input:?}"
878
            );
879
        }
880
    }
881

            
882
    #[test]
883
    fn calc_nan_literal_is_accepted_but_coerced_to_zero() {
884
        // ADVERSARIAL: `parse_pixel_value` delegates to `f32::from_str`, which happily
885
        // parses "NaN". The value survives into the AST — but `FloatValue::new` casts
886
        // `NaN * 1000.0` to isize, and `as isize` maps NaN to 0. So no NaN ever reaches
887
        // the layout solver; the expression silently means `calc(0px)` instead of failing.
888
        let parsed = parse_calc_expression("NaN").unwrap();
889
        match parsed.get(0).unwrap() {
890
            CalcAstItem::Value(v) => {
891
                assert!(
892
                    !v.number.get().is_nan(),
893
                    "NaN must not survive into the AST"
894
                );
895
                assert_eq!(v.number.get(), 0.0);
896
            }
897
            other => panic!("expected a Value, got {other:?}"),
898
        }
899
    }
900

            
901
    #[test]
902
    fn calc_huge_and_infinite_literals_saturate_to_a_finite_value() {
903
        // "inf" and out-of-range literals parse to f32::INFINITY, which `FloatValue::new`
904
        // saturates to isize::MAX. Assert the AST never carries a non-finite number.
905
        let huge = "9".repeat(50); // ~1e50, far past f32::MAX
906
        for input in [
907
            "inf",
908
            "-inf",
909
            huge.as_str(),
910
            "9223372036854775807", // i64::MAX
911
            "-9223372036854775808",
912
            "340282350000000000000000000000000000000px", // f32::MAX
913
        ] {
914
            let parsed = parse_calc_expression(input)
915
                .unwrap_or_else(|()| panic!("expected Ok for {input:?}"));
916
            match parsed.get(0).unwrap() {
917
                CalcAstItem::Value(v) => {
918
                    let n = v.number.get();
919
                    assert!(n.is_finite(), "{input:?} produced a non-finite value: {n}");
920
                }
921
                other => panic!("expected a Value for {input:?}, got {other:?}"),
922
            }
923
        }
924
    }
925

            
926
    #[test]
927
    fn calc_zero_and_negative_zero() {
928
        for input in ["0", "-0", "0px", "-0px", "0%"] {
929
            let parsed = parse_calc_expression(input).unwrap();
930
            match parsed.get(0).unwrap() {
931
                CalcAstItem::Value(v) => assert_eq!(
932
                    v.number.get(),
933
                    0.0,
934
                    "{input:?} should quantise to exactly zero"
935
                ),
936
                other => panic!("expected a Value for {input:?}, got {other:?}"),
937
            }
938
        }
939
        // -0.0 is normalised to +0.0 by the isize round-trip, so it never prints as "-0".
940
        assert_eq!(
941
            calc_ast_to_css_string(&parse_calc_expression("-0px").unwrap()),
942
            "calc(0px)"
943
        );
944
    }
945

            
946
    #[test]
947
    fn calc_sub_millisecond_precision_is_quantised_to_zero() {
948
        // FloatValue keeps 3 decimal places; anything below 0.001 collapses to 0.
949
        let parsed = parse_calc_expression("0.0005px").unwrap();
950
        match parsed.get(0).unwrap() {
951
            CalcAstItem::Value(v) => assert_eq!(v.number.get(), 0.0),
952
            other => panic!("expected a Value, got {other:?}"),
953
        }
954
        let parsed = parse_calc_expression("0.001px").unwrap();
955
        match parsed.get(0).unwrap() {
956
            CalcAstItem::Value(v) => assert!((v.number.get() - 0.001).abs() < 1e-6),
957
            other => panic!("expected a Value, got {other:?}"),
958
        }
959
    }
960

            
961
    #[test]
962
    fn calc_deeply_nested_braces_do_not_stack_overflow() {
963
        // The tokeniser is iterative, so 10_000 levels of nesting must not blow the stack.
964
        const DEPTH: usize = 10_000;
965
        let input = format!("{}1px{}", "(".repeat(DEPTH), ")".repeat(DEPTH));
966
        let parsed = parse_calc_expression(&input).unwrap();
967
        assert_eq!(parsed.len(), DEPTH * 2 + 1);
968
        assert_eq!(*parsed.get(0).unwrap(), CalcAstItem::BraceOpen);
969
        assert_eq!(
970
            *parsed.get(parsed.len() - 1).unwrap(),
971
            CalcAstItem::BraceClose
972
        );
973
        // Printing the same AST must also stay iterative.
974
        let printed = calc_ast_to_css_string(&parsed);
975
        assert_eq!(printed.matches('(').count(), DEPTH + 1); // + the "calc(" paren
976
        assert_eq!(printed.matches(')').count(), DEPTH + 1);
977
    }
978

            
979
    #[test]
980
    fn calc_unbalanced_braces_are_accepted_without_validation() {
981
        // ADVERSARIAL / documents current behaviour: the tokeniser performs NO grammar
982
        // validation, so structurally meaningless expressions parse to Ok(..). Anything
983
        // that consumes a CalcAstItemVec (the solver in layout/src/solver3/calc.rs) must
984
        // therefore be robust against unbalanced braces and dangling operators.
985
        assert_eq!(shape(&parse_calc_expression("(((").unwrap()), vec![5, 5, 5]);
986
        assert_eq!(shape(&parse_calc_expression(")))").unwrap()), vec![6, 6, 6]);
987
        assert_eq!(
988
            shape(&parse_calc_expression(")1px(").unwrap()),
989
            vec![6, 0, 5]
990
        );
991

            
992
        // The same holds through the public parser: `width: calc(()` is accepted.
993
        assert_eq!(
994
            shape_of_width(&parse_layout_width("calc(()").unwrap()),
995
            vec![5]
996
        );
997
        assert_eq!(
998
            shape_of_width(&parse_layout_width("calc()))").unwrap()),
999
            vec![6, 6]
        );
    }
    #[test]
    fn calc_dangling_operators_and_missing_operands_are_accepted() {
        // Same story as the braces: operators with no operands still yield Ok(..).
        assert_eq!(shape(&parse_calc_expression("+").unwrap()), vec![1]);
        assert_eq!(shape(&parse_calc_expression("*/").unwrap()), vec![3, 4]);
        assert_eq!(
            shape(&parse_calc_expression("1px 2px").unwrap()),
            vec![0, 0]
        );
        assert_eq!(
            shape(&parse_calc_expression("1px + + 2px").unwrap()),
            vec![0, 1, 1, 0]
        );
    }
    #[test]
    fn calc_extremely_long_expression_terminates() {
        // 50_000 terms — the tokeniser is O(n), so this must not hang.
        const TERMS: usize = 50_000;
        let mut input = String::from("1px");
        for _ in 0..TERMS {
            input.push_str(" + 1px");
        }
        let parsed = parse_calc_expression(&input).unwrap();
        assert_eq!(parsed.len(), TERMS * 2 + 1);
    }
    #[test]
    fn calc_extremely_long_garbage_token_is_err() {
        let long_alpha = "a".repeat(100_000);
        assert!(parse_calc_expression(&long_alpha).is_err());
        // A 100k-digit literal overflows f32 to +inf, which then saturates to a finite
        // FloatValue — it must not hang, panic, or produce inf.
        let long_digits = "1".repeat(100_000);
        let parsed = parse_calc_expression(&long_digits).unwrap();
        match parsed.get(0).unwrap() {
            CalcAstItem::Value(v) => assert!(v.number.get().is_finite()),
            other => panic!("expected a Value, got {other:?}"),
        }
    }
    #[test]
    fn calc_leading_and_trailing_junk_is_handled_deterministically() {
        // Surrounding whitespace is trimmed...
        assert_eq!(
            parse_calc_expression("  100% - 20px  ").unwrap().as_slice(),
            parse_calc_expression("100% - 20px").unwrap().as_slice()
        );
        // ...but real trailing junk is rejected.
        assert!(parse_calc_expression("100% - 20px;").is_err());
        assert!(parse_calc_expression("100% - 20px garbage").is_err());
        assert!(parse_calc_expression(";100% - 20px").is_err());
    }
    #[test]
    fn calc_scientific_notation_is_rejected() {
        // `find_value_end` stops the digit scan at 'e' and then eats it as a unit, so the
        // token handed to parse_pixel_value is "1e" — CSS `calc(1e3px)` is not supported.
        assert!(parse_calc_expression("1e3px").is_err());
        assert!(parse_calc_expression("1e40").is_err());
        assert!(parse_calc_expression("1E3px").is_err());
    }
    #[test]
    fn calc_every_single_ascii_char_is_panic_free() {
        for b in 0u8..128 {
            let s = String::from(b as char);
            // Only requirement: no panic, no hang. (Operators/digits are Ok, the rest Err.)
            let _ = parse_calc_expression(&s);
        }
    }
    #[test]
    fn calc_fuzz_triples_never_panic_and_reprint_keeps_the_shape() {
        // Deterministic mini-fuzz over the tokeniser's decision points, including two
        // multi-byte chars to smoke out any non-char-boundary slicing.
        const ALPHABET: [&str; 16] = [
            "(",
            ")",
            "+",
            "-",
            "*",
            "/",
            ".",
            "0",
            "9",
            "p",
            "x",
            "%",
            " ",
            "e",
            "é",
            "\u{1F600}",
        ];
        for a in ALPHABET {
            for b in ALPHABET {
                for c in ALPHABET {
                    let input = format!("{a}{b}{c}");
                    let Ok(ast) = parse_calc_expression(&input) else {
                        continue;
                    };
                    assert!(!ast.is_empty(), "Ok(..) must never be an empty AST");
                    // encode == decode: printing an AST and re-parsing it must give back
                    // the same sequence of item kinds.
                    let printed = calc_ast_to_css_string(&ast);
                    assert!(printed.starts_with("calc(") && printed.ends_with(')'));
                    let inner = &printed[5..printed.len() - 1];
                    let reparsed = parse_calc_expression(inner).unwrap_or_else(|()| {
                        panic!("re-printed AST {printed:?} (from {input:?}) failed to re-parse")
                    });
                    assert_eq!(
                        shape(&ast),
                        shape(&reparsed),
                        "round-trip changed the AST shape: {input:?} -> {printed:?}"
                    );
                }
            }
        }
    }
    // ---------------------------------------------------------------------
    // find_value_end
    // ---------------------------------------------------------------------
    #[test]
    fn find_value_end_basic_offsets() {
        assert_eq!(find_value_end(""), 0);
        assert_eq!(find_value_end("10px"), 4);
        assert_eq!(find_value_end("100%"), 4);
        assert_eq!(find_value_end("-1.5em"), 6);
        assert_eq!(find_value_end("+2px"), 4);
        assert_eq!(find_value_end("3"), 1);
        // Stops at the first char that is neither sign/digit/dot nor unit.
        assert_eq!(find_value_end("10px)"), 4);
        assert_eq!(find_value_end("10px + 2px"), 4);
        assert_eq!(find_value_end("(1px)"), 0);
        assert_eq!(find_value_end(")"), 0);
        // A lone sign consumes exactly the sign, so the caller gets the un-parsable "-".
        assert_eq!(find_value_end("-"), 1);
        assert_eq!(find_value_end("- 10px"), 1);
    }
    #[test]
    fn find_value_end_is_lax_and_hands_junk_to_the_pixel_parser() {
        // ADVERSARIAL: find_value_end is a *scanner*, not a validator — it happily returns
        // a non-empty span for these. The rejection only happens later, in parse_pixel_value.
        assert_eq!(find_value_end("..."), 3);
        assert_eq!(find_value_end("1.2.3px"), 7);
        assert_eq!(find_value_end("1px%em"), 6);
        assert_eq!(find_value_end("--"), 1);
        // ...which is why all of these end up as Err from the calc parser:
        for junk in ["...", "1.2.3px", "1px%em"] {
            assert!(parse_calc_expression(junk).is_err(), "{junk:?}");
        }
    }
    #[test]
    fn find_value_end_stops_at_an_exponent_marker() {
        // 'e' is treated as the start of a unit, so the digit scan never sees "e40".
        assert_eq!(find_value_end("1e40"), 2);
        assert_eq!(find_value_end("1e40px"), 2);
    }
    #[test]
    fn find_value_end_result_is_always_an_in_bounds_char_boundary() {
        // THE safety invariant: parse_calc_expression slices `&rest[..end]` with this
        // offset, so a non-boundary result would be an instant panic on any unicode input.
        for s in [
            "",
            " ",
            "10px",
            "\u{1F600}",
            "10px\u{1F600}",
            "1\u{0301}px",
            "é",
            "9é",
            "%é",
            "9%é",
            "10px",
            "\u{00A0}10px",
            "10\u{2212}5",
            "px\u{4e2d}\u{6587}",
        ] {
            let end = find_value_end(s);
            assert!(end <= s.len(), "{s:?}: end {end} out of bounds");
            assert!(
                s.is_char_boundary(end),
                "{s:?}: end {end} is not a char boundary"
            );
            // Slicing with the returned offset must be safe.
            let _ = &s[..end];
        }
    }
    #[test]
    fn find_value_end_long_input_terminates() {
        let long = "9".repeat(200_000);
        assert_eq!(find_value_end(&long), 200_000);
        let long_unit = format!("{}{}", "9".repeat(100_000), "x".repeat(100_000));
        assert_eq!(find_value_end(&long_unit), 200_000);
    }
    // ---------------------------------------------------------------------
    // calc_ast_to_css_string
    // ---------------------------------------------------------------------
    #[test]
    fn calc_ast_to_css_string_of_empty_vec_is_empty_calc() {
        assert_eq!(calc_ast_to_css_string(&CalcAstItemVec::new()), "calc()");
        // ...and that output is not itself re-parsable, i.e. an empty AST is not a
        // legal calc() — parse_layout_width rejects it.
        assert!(parse_layout_width("calc()").is_err());
    }
    #[test]
    fn calc_ast_to_css_string_prints_every_variant() {
        let items = CalcAstItemVec::from_vec(vec![
            CalcAstItem::Value(PixelValue::px(1.0)),
            CalcAstItem::Add,
            CalcAstItem::Sub,
            CalcAstItem::Mul,
            CalcAstItem::Div,
            CalcAstItem::BraceOpen,
            CalcAstItem::BraceClose,
        ]);
        assert_eq!(calc_ast_to_css_string(&items), "calc(1px + - * / ( ))");
    }
    #[test]
    fn calc_ast_to_css_string_never_prints_nan_or_inf() {
        // Even if a caller builds a PixelValue from NaN/inf/f32::MAX (e.g. over FFI),
        // the printed CSS must stay a parsable finite number.
        for v in [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
        ] {
            let items = CalcAstItemVec::from_vec(vec![CalcAstItem::Value(PixelValue::px(v))]);
            let printed = calc_ast_to_css_string(&items);
            assert!(!printed.contains("NaN"), "{v} printed as {printed:?}");
            assert!(!printed.contains("inf"), "{v} printed as {printed:?}");
            assert!(printed.starts_with("calc(") && printed.ends_with("px)"));
            // and it must survive a re-parse
            let inner = &printed[5..printed.len() - 1];
            assert!(
                parse_calc_expression(inner).is_ok(),
                "{printed:?} did not re-parse"
            );
        }
        // NaN specifically collapses to 0.
        let items = CalcAstItemVec::from_vec(vec![CalcAstItem::Value(PixelValue::px(f32::NAN))]);
        assert_eq!(calc_ast_to_css_string(&items), "calc(0px)");
    }
    #[test]
    fn calc_ast_print_parse_roundtrip_is_exact_for_representable_values() {
        for src in [
            "100% - 20px",
            "(100% - 20px) / 3",
            "-10px + 5px",
            "10px - -5px",
            "1.5em * 2",
            "100vw - 2rem",
            "50% + 1.25in",
            "((1px + 2px) * (3px - 4px))",
        ] {
            let ast = parse_calc_expression(src).unwrap();
            let printed = calc_ast_to_css_string(&ast);
            let inner = &printed[5..printed.len() - 1];
            let reparsed = parse_calc_expression(inner).unwrap();
            assert_eq!(
                ast.as_slice(),
                reparsed.as_slice(),
                "round-trip mismatch for {src:?} (printed as {printed:?})"
            );
        }
    }
    #[test]
    fn calc_ast_to_css_string_is_lossy_for_adjacent_values() {
        // ADVERSARIAL: the printer joins items with a single space and adds no
        // disambiguating parens, so an AST holding two adjacent Values — reachable via the
        // FFI/api constructors, though not via parse_calc_expression — prints to CSS that
        // re-parses as a *subtraction*. The encoding is not injective.
        let items = CalcAstItemVec::from_vec(vec![
            CalcAstItem::Value(PixelValue::px(1.0)),
            CalcAstItem::Value(PixelValue::px(-1.0)),
        ]);
        let printed = calc_ast_to_css_string(&items);
        assert_eq!(printed, "calc(1px -1px)");
        let reparsed = parse_calc_expression(&printed[5..printed.len() - 1]).unwrap();
        assert_eq!(shape(&items), vec![0, 0]);
        assert_eq!(shape(&reparsed), vec![0, 2, 0]); // Value, Sub, Value — not the input!
        assert_ne!(items.as_slice(), reparsed.as_slice());
    }
    #[test]
    fn calc_ast_to_css_string_handles_a_huge_ast() {
        let items = CalcAstItemVec::from_vec(vec![CalcAstItem::BraceOpen; 100_000]);
        let printed = calc_ast_to_css_string(&items);
        // 100_000 "(" joined by 100_000 - 1 spaces, plus "calc(" and ")"
        assert_eq!(printed.len(), 100_000 * 2 - 1 + 6);
    }
    // ---------------------------------------------------------------------
    // parse_layout_box_sizing + LayoutBoxSizingParseError round-trips
    // ---------------------------------------------------------------------
    #[test]
    fn box_sizing_valid_inputs_and_trimming() {
        assert_eq!(
            parse_layout_box_sizing("content-box").unwrap(),
            LayoutBoxSizing::ContentBox
        );
        assert_eq!(
            parse_layout_box_sizing("border-box").unwrap(),
            LayoutBoxSizing::BorderBox
        );
        assert_eq!(
            parse_layout_box_sizing("\t\n  border-box \r\n ").unwrap(),
            LayoutBoxSizing::BorderBox
        );
        // encode == decode
        for v in [LayoutBoxSizing::ContentBox, LayoutBoxSizing::BorderBox] {
            assert_eq!(parse_layout_box_sizing(&v.print_as_css_value()).unwrap(), v);
        }
    }
    #[test]
    fn box_sizing_empty_whitespace_and_garbage_are_err() {
        for input in [
            "",
            "   ",
            "\t\n",
            "padding-box",
            "borderbox",
            "border box",
            "content-box;",
            "content-box border-box",
            "content-box!",
            "\0",
            "-",
            "\u{1F600}",
            "content-box\u{0301}",
            "cöntent-box",
            "content\u{2010}box", // unicode hyphen, not ASCII '-'
        ] {
            assert!(
                parse_layout_box_sizing(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn box_sizing_rejects_numeric_boundary_strings() {
        for input in [
            "0",
            "-0",
            "NaN",
            "inf",
            "9223372036854775807",
            "-9223372036854775808",
            "3.4028235e38",
            "1e-45",
        ] {
            assert!(
                parse_layout_box_sizing(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn box_sizing_keyword_matching_is_case_sensitive() {
        // CSS keywords are ASCII case-insensitive per spec; this parser is not.
        // Documenting the current behaviour so a future fix has to update this test.
        assert!(parse_layout_box_sizing("Content-Box").is_err());
        assert!(parse_layout_box_sizing("BORDER-BOX").is_err());
    }
    #[test]
    fn box_sizing_extremely_long_input_is_err_and_terminates() {
        let long = "a".repeat(1_000_000);
        assert!(parse_layout_box_sizing(&long).is_err());
        // A long *valid* keyword surrounded by whitespace still trims down to Ok.
        let padded = format!("{}border-box{}", " ".repeat(100_000), " ".repeat(100_000));
        assert_eq!(
            parse_layout_box_sizing(&padded).unwrap(),
            LayoutBoxSizing::BorderBox
        );
    }
    #[test]
    fn box_sizing_error_payload_is_the_trimmed_input() {
        let err = parse_layout_box_sizing("  bogus  ").unwrap_err();
        match &err {
            LayoutBoxSizingParseError::InvalidValue(s) => assert_eq!(*s, "bogus"),
        }
        assert_eq!(format!("{err}"), "Invalid box-sizing value: \"bogus\"");
    }
    #[test]
    fn box_sizing_error_to_contained_to_shared_roundtrip() {
        let err = parse_layout_box_sizing("padding-box").unwrap_err();
        let owned = err.to_contained();
        assert_eq!(
            owned,
            LayoutBoxSizingParseErrorOwned::InvalidValue("padding-box".to_string().into())
        );
        // to_shared() must reproduce exactly what to_contained() consumed.
        assert_eq!(owned.to_shared(), err);
        // ...and be idempotent under repeated round-trips.
        assert_eq!(owned.to_shared().to_contained(), owned);
    }
    #[test]
    fn box_sizing_error_roundtrip_with_empty_and_unicode_payloads() {
        for input in ["", "   ", "\u{1F600}\u{0301}é", "a\0b"] {
            let err = parse_layout_box_sizing(input).unwrap_err();
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "round-trip failed for {input:?}");
            match &owned {
                LayoutBoxSizingParseErrorOwned::InvalidValue(s) => {
                    assert_eq!(s.as_str(), input.trim());
                }
            }
        }
    }
    #[test]
    fn box_sizing_error_roundtrip_with_a_huge_payload() {
        let long = "x".repeat(200_000);
        let err = parse_layout_box_sizing(&long).unwrap_err();
        let owned = err.to_contained();
        match &owned {
            LayoutBoxSizingParseErrorOwned::InvalidValue(s) => {
                assert_eq!(s.as_str().len(), 200_000);
            }
        }
        assert_eq!(owned.to_shared(), err);
    }
    // ---------------------------------------------------------------------
    // The sizing parsers — the only public path into the calc()/fit-content() slicing
    // ---------------------------------------------------------------------
    #[test]
    fn sizing_parser_paren_slicing_is_panic_free() {
        // Both branches slice with hard-coded byte offsets (`s[5..len-1]`, `s[12..len-1]`).
        // These inputs are the ones that would trip an off-by-one or a char-boundary bug.
        for input in [
            "calc()",
            "fit-content()",
            "fit-content(\u{1F600})",
            "calc(\u{1F600})",
            "calc(é)",
            "fit-content(é)",
            "calc( )",
            "fit-content( )",
            "calc(1px)garbage)",
            "fit-content(1px)garbage)",
            "fit-content(1px",
            "calc(1px",
        ] {
            // Only requirement: no panic. (All of these must also be Err.)
            assert!(
                parse_layout_width(input).is_err(),
                "expected Err for {input:?}"
            );
            assert!(
                parse_layout_height(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn sizing_parser_keywords_and_calc_roundtrip() {
        let cases = [
            (LayoutWidth::Auto, "auto"),
            (LayoutWidth::MinContent, "min-content"),
            (LayoutWidth::MaxContent, "max-content"),
            (LayoutWidth::Px(PixelValue::px(150.0)), "150px"),
            (
                LayoutWidth::FitContent(PixelValue::percent(50.0)),
                "fit-content(50%)",
            ),
        ];
        for (value, css) in cases {
            assert_eq!(parse_layout_width(css).unwrap(), value, "parse of {css:?}");
            assert_eq!(value.print_as_css_value(), css, "print of {css:?}");
        }
        // calc() survives the full encode/decode cycle.
        let parsed = parse_layout_width("calc(100% - 20px)").unwrap();
        assert_eq!(parsed.print_as_css_value(), "calc(100% - 20px)");
        assert_eq!(
            parse_layout_width(&parsed.print_as_css_value()).unwrap(),
            parsed
        );
        assert_eq!(
            calc_items(&parsed),
            vec![
                CalcAstItem::Value(PixelValue::percent(100.0)),
                CalcAstItem::Sub,
                CalcAstItem::Value(PixelValue::px(20.0)),
            ]
        );
    }
    #[test]
    fn sizing_parser_keywords_are_case_sensitive() {
        // Same spec deviation as box-sizing: CSS keywords should be case-insensitive.
        for input in [
            "AUTO",
            "Auto",
            "MIN-CONTENT",
            "CALC(1px)",
            "FIT-CONTENT(1px)",
        ] {
            assert!(
                parse_layout_width(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn fit_content_clamps_negative_values_to_zero() {
        // Documented invariant of the parser: fit-content() can never be negative.
        assert_eq!(
            parse_layout_width("fit-content(-10px)").unwrap(),
            LayoutWidth::FitContent(PixelValue::zero())
        );
        assert_eq!(
            parse_layout_height("fit-content(-99999%)").unwrap(),
            LayoutHeight::FitContent(PixelValue::zero())
        );
        // NaN quantises to 0, which is >= 0.0, so it takes the non-negative branch.
        assert_eq!(
            parse_layout_width("fit-content(NaN)").unwrap(),
            LayoutWidth::FitContent(PixelValue::zero())
        );
        // A huge value is kept, but saturated to a finite number.
        match parse_layout_width("fit-content(99999999999999999999999999999999999999999px)")
            .unwrap()
        {
            LayoutWidth::FitContent(v) => assert!(v.number.get().is_finite()),
            other => panic!("expected FitContent, got {other:?}"),
        }
    }
    #[test]
    fn sizing_parser_deeply_nested_calc_does_not_stack_overflow() {
        const DEPTH: usize = 5_000;
        let input = format!("calc({}1px{})", "(".repeat(DEPTH), ")".repeat(DEPTH));
        let parsed = parse_layout_width(&input).unwrap();
        assert_eq!(calc_items(&parsed).len(), DEPTH * 2 + 1);
        // Printing must survive it too (this is what the CSS serialiser calls).
        let printed = parsed.print_as_css_value();
        assert_eq!(printed.matches('(').count(), DEPTH + 1);
        assert_eq!(printed.matches(')').count(), DEPTH + 1);
    }
    #[test]
    fn sizing_parser_error_carries_the_untrimmed_input_for_bad_calc() {
        // Quirk worth pinning: InvalidKeyword gets the *raw* `input`, not the trimmed
        // string (unlike box-sizing, which reports the trimmed value).
        let err = parse_layout_width("  calc(??)  ").unwrap_err();
        match &err {
            LayoutWidthParseError::InvalidKeyword(k) => assert_eq!(*k, "  calc(??)  "),
            other => panic!("expected InvalidKeyword, got {other:?}"),
        }
        // ...and it round-trips through the owned representation unchanged.
        let owned = err.to_contained();
        assert_eq!(owned.to_shared(), err);
    }
    #[test]
    fn pixel_dimension_parser_errors_roundtrip() {
        for input in ["", "   ", "px", "garbage", "\u{1F600}", "1.2.3px"] {
            let err = parse_layout_min_width(input)
                .err()
                .unwrap_or_else(|| panic!("expected Err for {input:?}"));
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "for {input:?}");
            assert!(parse_layout_max_height(input).is_err(), "for {input:?}");
        }
        assert_eq!(
            parse_layout_min_width("0").unwrap(),
            LayoutMinWidth {
                inner: PixelValue::px(0.0)
            }
        );
    }
    // ---------------------------------------------------------------------
    // Defaults / numeric invariants
    // ---------------------------------------------------------------------
    #[test]
    fn max_dimension_defaults_are_finite_but_not_actually_f32_max() {
        // The doc comment says the default is `f32::MAX` pixels. It isn't: FloatValue
        // stores number * 1000 in an isize, and `f32::MAX * 1000.0` = inf saturates to
        // isize::MAX — so `get()` comes back as ~9.2e15, not 3.4e38. The sentinel is still
        // "effectively unconstrained" and, importantly, finite (so the solver's
        // padding/margin additions cannot reach inf) — but it is NOT f32::MAX.
        for got in [
            LayoutMaxWidth::default().inner.number.get(),
            LayoutMaxHeight::default().inner.number.get(),
        ] {
            assert!(
                got.is_finite(),
                "default max dimension is not finite: {got}"
            );
            assert!(got > 0.0);
            assert_ne!(got, f32::MAX);
        }
        // The min-* defaults are exactly zero.
        assert_eq!(LayoutMinWidth::default().inner.number.get(), 0.0);
        assert_eq!(LayoutMinHeight::default().inner.number.get(), 0.0);
        assert_eq!(LayoutWidth::default(), LayoutWidth::Auto);
        assert_eq!(LayoutHeight::default(), LayoutHeight::Auto);
        assert_eq!(LayoutBoxSizing::default(), LayoutBoxSizing::ContentBox);
    }
    #[test]
    fn sizing_interpolate_endpoints_and_nan_t() {
        let a = LayoutWidth::px(10.0);
        let b = LayoutWidth::px(20.0);
        assert_eq!(a.interpolate(&b, 0.0), a);
        assert_eq!(a.interpolate(&b, 1.0), b);
        assert_eq!(a.interpolate(&b, 0.5), LayoutWidth::px(15.0));
        // NaN `t` must not panic and must not leak a NaN into the value.
        match a.interpolate(&b, f32::NAN) {
            LayoutWidth::Px(v) => {
                assert!(!v.number.get().is_nan());
                assert_eq!(v.number.get(), 0.0);
            }
            other => panic!("expected Px, got {other:?}"),
        }
        // Discrete keywords snap rather than blend, and NaN falls through to `other`.
        let auto = LayoutWidth::Auto;
        let min = LayoutWidth::MinContent;
        assert_eq!(auto.interpolate(&min, 0.0), LayoutWidth::Auto);
        assert_eq!(auto.interpolate(&min, 1.0), LayoutWidth::MinContent);
        assert_eq!(auto.interpolate(&min, f32::NAN), LayoutWidth::MinContent);
        // Interpolating a calc() clones the AST (no double-free, no panic).
        let calc = parse_layout_width("calc(100% - 20px)").unwrap();
        assert_eq!(calc.interpolate(&auto, 0.0), calc);
        assert_eq!(auto.interpolate(&calc, 1.0), calc);
    }
    #[test]
    fn sizing_parser_px_quantisation_limits() {
        // Sub-0.001 collapses to zero...
        match parse_layout_width("0.0005px").unwrap() {
            LayoutWidth::Px(v) => assert_eq!(v.number.get(), 0.0),
            other => panic!("expected Px, got {other:?}"),
        }
        // ...and an out-of-f32-range literal saturates to a finite value rather than inf.
        match parse_layout_width(&format!("{}px", "9".repeat(60))).unwrap() {
            LayoutWidth::Px(v) => assert!(v.number.get().is_finite()),
            other => panic!("expected Px, got {other:?}"),
        }
        // A bare NaN literal is accepted as a length and quantises to 0.
        match parse_layout_width("NaN").unwrap() {
            LayoutWidth::Px(v) => assert_eq!(v.number.get(), 0.0),
            other => panic!("expected Px, got {other:?}"),
        }
    }
}