kui-core 0.1.0-alpha.44

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Size expressions: CSS's `min()`, `max()` and `clamp()` over lengths
//! and percentages, resolved by layout against the parent's content box
//! (the same box a `Percent` sizing takes its cut of).
//!
//! ```text
//! size   := number ["px"] | number "%" | fn "(" size ("," size)* ")"
//! fn     := "min" | "max" | "clamp"         -- clamp takes exactly three
//! number := digits ["." digits] | "." digits  -- no sign, no exponent
//! ```
//!
//! As CSS reads it: a unit straight after its number (`80 %` is refused),
//! a function's `(` straight after its name, names and `px` in any case,
//! and whitespace free around the commas and inside the parentheses.
//! `"clamp(400px, 80%, 1000px)"` is 80% of the room, never under 400 nor
//! over 1000, and, as CSS has it, the minimum wins when it is over the
//! maximum. An expression with no percentage in it is a length
//! (`"min(300px, 400)"` is `Fixed(300)`), a bare percentage is a
//! `Percent`, and only what depends on the room becomes a [`Calc`].
//!
//! ```rust
//! use kui_core::{NodeSpec, Sizing, calc};
//!
//! let w = calc::sizing("clamp(400px, 80%, 1000px)").unwrap();
//! assert!(matches!(w, Sizing::Calc(_)));
//! assert_eq!(calc::sizing("min(300px, 400)").unwrap(), Sizing::Fixed(300.0));
//!
//! let pane = NodeSpec::column().width(w).max_width(calc::bound("50%").unwrap());
//! if let Sizing::Calc(c) = pane.layout.width {
//!     assert_eq!(c.resolve(1500.0), 1000.0); // 80% of 1500 is capped
//!     assert_eq!(c.resolve(200.0), 400.0);   // and floored
//! }
//! ```
//!
//! The same expression as data, for a binding that would rather not spell
//! it ([`from_value`]): a number is px, `{ pct = N }` (or `{ percent: N }`
//! in JS) a percentage, `{ px = N }` a length, and a function a one-key
//! table of its arguments. Rust builds one with [`Expr`] and [`intern`].
//!
//! A [`Calc`] is a handle. `LayoutSpec` is `Copy` and copied per node per
//! frame, so the tree it names lives in a process-wide table, one entry
//! per distinct expression, which a frame that declares the same
//! expression again finds rather than adds to. The table holds at most
//! [`MAX_CALCS`] entries and never lets one go: a program that reaches the
//! cap is spelling a new expression per frame (`format!("clamp({n}px, ..)")`
//! fed a drag). Past it a new expression is refused with [`FULL`] in its
//! error, which every binding reads as the prop left undeclared, and a
//! [`crate::diag::SIZE_EXPRESSIONS_FULL`] warning says so. An expression
//! already kept still resolves.

use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};

/// How many distinct expressions the table keeps.
pub const MAX_CALCS: usize = 1 << 16;

/// What the error of an expression refused for want of room in the table
/// starts with, under whatever a binding put before it: see [`is_full`].
pub const FULL: &str = "too many distinct size expressions";

/// Whether `err` is a refusal for want of room ([`FULL`]), not a bad
/// spelling: a binding leaves the prop at its default on one — the
/// expression was fine, the process has spelled too many — and fails on
/// the other.
pub fn is_full(err: &str) -> bool {
    err.contains(FULL)
}

/// How many expressions the full table refused, over the process, and
/// the last one's spelling: what the warning names.
static REFUSED: AtomicU64 = AtomicU64::new(0);
static LAST_REFUSED: Mutex<String> = Mutex::new(String::new());

/// How many new expressions the table has refused since the process
/// started, with the last one spelled.
pub fn refused() -> (u64, String) {
    let n = REFUSED.load(Ordering::Relaxed);
    if n == 0 {
        // Every drain of every core asks; the lock is for the rare answer.
        return (0, String::new());
    }
    let last = LAST_REFUSED.lock().map(|s| s.clone()).unwrap_or_default();
    (n, last)
}

/// How deep an expression nests: at most this many functions inside one
/// another, whatever built it — the grammar, data, prefix code, C's
/// builders or a Rust tree handed to [`intern`]. Every walk of a tree
/// (evaluating, hashing, comparing, spelling, dropping) recurses, so a
/// tree the table keeps is one those walks can finish.
pub const MAX_DEPTH: u32 = 32;

fn too_deep(what: &str) -> String {
    format!("bad size{what}: nested past {MAX_DEPTH}")
}

/// A number an expression may hold: finite, and `-0` as `0`. The table
/// finds an entry by its numbers' bits, and `NaN` is equal to nothing —
/// not even itself — so `{ min = { 0/0, { pct = 50 } } }` declared each
/// frame was a new entry each frame, towards the cap every view shares;
/// and `-0` and `0` were two entries for one expression.
/// Neither infinity means anything a room can be cut to either.
fn finite(v: f32) -> Result<f32, String> {
    if v.is_finite() {
        // `-0.0 == 0.0`, so this is `0.0` for either.
        Ok(if v == 0.0 { 0.0 } else { v })
    } else {
        Err(format!("bad size: {v} is not a finite number"))
    }
}

/// Holds a tree to what the table keeps — nested no deeper than
/// [`MAX_DEPTH`], its numbers [`finite`] and `-0` made `0` — at depth
/// `depth`: what [`intern`] and [`norm`] make of a tree built by hand (C's
/// builders, a Rust `Expr`), stopping at the first level past the cap
/// rather than walking the rest.
fn canon(e: &mut Expr, depth: u32) -> Result<(), String> {
    if depth > MAX_DEPTH {
        return Err(too_deep(""));
    }
    match e {
        Expr::Px(v) | Expr::Pct(v) => {
            *v = finite(*v)?;
            Ok(())
        }
        Expr::Min(xs) | Expr::Max(xs) => xs.iter_mut().try_for_each(|x| canon(x, depth + 1)),
        Expr::Clamp(a, b, c) => {
            canon(a, depth + 1)?;
            canon(b, depth + 1)?;
            canon(c, depth + 1)
        }
    }
}

/// A parsed expression: lengths in logical px, percentages as fractions.
#[derive(Clone, Debug, PartialEq)]
pub enum Expr {
    Px(f32),
    /// A fraction of the room (`"50%"` is `Pct(0.5)`).
    Pct(f32),
    Min(Vec<Expr>),
    Max(Vec<Expr>),
    /// `clamp(min, target, max)`.
    Clamp(Box<Expr>, Box<Expr>, Box<Expr>),
}

impl Expr {
    /// The expression in logical px of `room` px, never below zero.
    pub fn resolve(&self, room: f32) -> f32 {
        self.eval(room).max(0.0)
    }

    fn eval(&self, room: f32) -> f32 {
        match self {
            Expr::Px(px) => *px,
            Expr::Pct(f) => room * f,
            Expr::Min(xs) => xs
                .iter()
                .map(|x| x.eval(room))
                .fold(f32::INFINITY, f32::min),
            Expr::Max(xs) => xs
                .iter()
                .map(|x| x.eval(room))
                .fold(f32::NEG_INFINITY, f32::max),
            // CSS's order: the minimum over the maximum.
            Expr::Clamp(lo, target, hi) => target.eval(room).min(hi.eval(room)).max(lo.eval(room)),
        }
    }

    /// Whether the value depends on the room: a percentage anywhere in it.
    pub fn relative(&self) -> bool {
        match self {
            Expr::Px(_) => false,
            Expr::Pct(_) => true,
            Expr::Min(xs) | Expr::Max(xs) => xs.iter().any(Expr::relative),
            Expr::Clamp(a, b, c) => a.relative() || b.relative() || c.relative(),
        }
    }
}

/// Structural equality and hashing by the numbers' bits: what the table
/// finds an entry by, so data and prefix code find theirs without being
/// spelled out first.
impl Eq for Expr {}

impl std::hash::Hash for Expr {
    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
        match self {
            Expr::Px(v) => (0u8, v.to_bits()).hash(h),
            Expr::Pct(v) => (1u8, v.to_bits()).hash(h),
            Expr::Min(xs) => (2u8, xs).hash(h),
            Expr::Max(xs) => (3u8, xs).hash(h),
            Expr::Clamp(a, b, c) => (4u8, a, b, c).hash(h),
        }
    }
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn list(f: &mut fmt::Formatter<'_>, name: &str, xs: &[&Expr]) -> fmt::Result {
            write!(f, "{name}(")?;
            for (i, x) in xs.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{x}")?;
            }
            write!(f, ")")
        }
        match self {
            Expr::Px(px) => write!(f, "{px}px"),
            Expr::Pct(p) => write!(f, "{}%", p * 100.0),
            Expr::Min(xs) => list(f, "min", &xs.iter().collect::<Vec<_>>()),
            Expr::Max(xs) => list(f, "max", &xs.iter().collect::<Vec<_>>()),
            Expr::Clamp(a, b, c) => list(f, "clamp", &[a, b, c]),
        }
    }
}

/// An expression that depends on the room, by its place in the table.
/// `Copy`, so a `Sizing` holding one still is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Calc(u32);

impl Calc {
    /// The expression in logical px of `room` px — evaluated under the
    /// table's read lock, since layout asks once per node that has one.
    pub fn resolve(self, room: f32) -> f32 {
        table()
            .read()
            .ok()
            .and_then(|t| t.exprs.get(self.0 as usize).map(|e| e.resolve(room)))
            .unwrap_or(0.0)
    }

    /// The tree the handle names.
    pub fn expr(self) -> Option<Arc<Expr>> {
        table().read().ok()?.exprs.get(self.0 as usize).cloned()
    }

    /// The handle's number: what a binding carries across (the C ABI's
    /// `KUI_CALC` sizing holds it in its `value`).
    pub fn id(self) -> u32 {
        self.0
    }

    /// A handle by number, when the table has one there.
    pub fn from_id(id: u32) -> Option<Calc> {
        let t = table().read().ok()?;
        ((id as usize) < t.exprs.len()).then_some(Calc(id))
    }

    /// The canonical spelling (`clamp(400px, 80%, 1000px)`), for a reader.
    pub fn describe(self) -> String {
        self.expr()
            .map_or_else(|| "calc(?)".into(), |e| e.to_string())
    }
}

#[derive(Default)]
struct Table {
    exprs: Vec<Arc<Expr>>,
    by_expr: HashMap<Expr, u32>,
    /// What a spelling came to, by the text a binding handed in — so the
    /// view that declares `"clamp(400px, 80%, 1000px)"` every frame parses
    /// it once. Bounded with the rest ([`MAX_CALCS`]); past it, a spelling
    /// is parsed each time and not kept.
    by_input: HashMap<String, Norm>,
    /// The same for prefix code, by its slots' bytes: a Node view that
    /// declares `{ clamp: [...] }` every frame builds the tree once.
    by_code: HashMap<Box<[u8]>, Norm>,
}

/// An expression reduced to what it needs to be.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Norm {
    Px(f32),
    Pct(f32),
    Calc(Calc),
}

fn norm(mut e: Expr) -> Result<Norm, String> {
    // Before `relative` and `resolve` walk it: a tree from C's builders
    // or a Rust caller has had no cap on the way in.
    canon(&mut e, 0)?;
    Ok(match e {
        Expr::Pct(f) => Norm::Pct(f),
        e if !e.relative() => Norm::Px(e.resolve(0.0)),
        e => Norm::Calc(intern_checked(e)?),
    })
}

/// A spelling reduced, through the input cache.
fn norm_str(s: &str) -> Result<Norm, String> {
    if let Some(n) = table().read().ok().and_then(|t| t.by_input.get(s).copied()) {
        return Ok(n);
    }
    let n = norm(parse(s)?)?;
    if let Ok(mut t) = table().write()
        && t.by_input.len() < MAX_CALCS
    {
        t.by_input.insert(s.to_string(), n);
    }
    Ok(n)
}

fn norm_sizing(n: Norm) -> crate::spec::Sizing {
    use crate::spec::Sizing;
    match n {
        Norm::Px(px) => Sizing::Fixed(px),
        Norm::Pct(f) => Sizing::Percent(f),
        Norm::Calc(c) => Sizing::Calc(c),
    }
}

fn norm_bound(n: Norm) -> Result<crate::spec::Bound, String> {
    use crate::spec::Bound;
    Ok(match n {
        Norm::Px(px) => Bound::Px(px),
        // A percentage clamp needs the room as much as a calc does.
        Norm::Pct(f) => Bound::Calc(intern(Expr::Pct(f))?),
        Norm::Calc(c) => Bound::Calc(c),
    })
}

/// A size expression as data (see the module's doc): a number, a
/// string, `{ pct }` / `{ percent }` / `{ px }`, or a one-key
/// `{ min | max | clamp = [args] }`.
pub fn from_value(v: &crate::value::Value) -> Result<Expr, String> {
    value_at(v, 0)
}

fn value_at(v: &crate::value::Value, depth: u32) -> Result<Expr, String> {
    use crate::value::Value;
    if depth > MAX_DEPTH {
        return Err(too_deep(""));
    }
    match v {
        Value::Int(_) | Value::Float(_) => {
            Ok(Expr::Px(finite(v.as_float().unwrap_or(0.0) as f32)?))
        }
        Value::Str(s) => parse(s),
        Value::Map(m) => {
            let mut it = m.iter();
            let (Some((k, arg)), None) = (it.next(), it.next()) else {
                return Err(
                    "bad size: a table names one of pct, percent, px, min, max, clamp".into(),
                );
            };
            let num = || {
                arg.as_float()
                    .map(|n| n as f32)
                    .ok_or_else(|| format!("bad size: {k} takes a number"))
                    .and_then(finite)
            };
            let args = || -> Result<Vec<Expr>, String> {
                let Value::List(xs) = arg else {
                    return Err(format!("bad size: {k} takes a list"));
                };
                if xs.is_empty() {
                    return Err(format!("bad size: {k} takes at least one"));
                }
                xs.iter().map(|x| value_at(x, depth + 1)).collect()
            };
            match k.as_str() {
                "pct" | "percent" => Ok(Expr::Pct(finite(num()? / 100.0)?)),
                "px" => Ok(Expr::Px(num()?)),
                "min" => Ok(Expr::Min(args()?)),
                "max" => Ok(Expr::Max(args()?)),
                "clamp" => match <[Expr; 3]>::try_from(args()?) {
                    Ok([a, b, c]) => Ok(Expr::Clamp(Box::new(a), Box::new(b), Box::new(c))),
                    Err(_) => Err("bad size: clamp takes three: clamp(MIN, TARGET, MAX)".into()),
                },
                _ => Err(format!(
                    "bad size: no {k:?} (pct, percent, px, min, max, clamp)"
                )),
            }
        }
        _ => Err("bad size: a number, a string or a table".into()),
    }
}

/// A size expression in prefix code, the form a transport that carries
/// only numbers sends (the Node wire's `SIZE_MODE_TREE`, v19): `1 px`,
/// `2 fraction`, `3 n args…` (min), `4 n args…` (max), `5 a b c`
/// (clamp). The whole slice is one expression.
pub fn from_code(code: &[f64]) -> Result<Expr, String> {
    fn one(code: &[f64], at: &mut usize, depth: u32) -> Result<Expr, String> {
        let mut next = || -> Result<f64, String> {
            let v = code.get(*at).copied().ok_or("bad size code: truncated")?;
            *at += 1;
            Ok(v)
        };
        if depth > MAX_DEPTH {
            return Err(too_deep(" code"));
        }
        Ok(match next()? as u32 {
            1 => Expr::Px(finite(next()? as f32)?),
            2 => Expr::Pct(finite(next()? as f32)?),
            op @ (3 | 4) => {
                let n = next()? as usize;
                if n == 0 || n > code.len() {
                    return Err("bad size code: an argument count out of range".into());
                }
                let args = (0..n)
                    .map(|_| one(code, at, depth + 1))
                    .collect::<Result<Vec<_>, _>>()?;
                if op == 3 {
                    Expr::Min(args)
                } else {
                    Expr::Max(args)
                }
            }
            5 => {
                let a = one(code, at, depth + 1)?;
                let b = one(code, at, depth + 1)?;
                let c = one(code, at, depth + 1)?;
                Expr::Clamp(Box::new(a), Box::new(b), Box::new(c))
            }
            op => return Err(format!("bad size code: no op {op}")),
        })
    }
    let mut at = 0;
    let e = one(code, &mut at, 0)?;
    if at != code.len() {
        return Err("bad size code: slots left over".into());
    }
    Ok(e)
}

/// Prefix code reduced, through the code cache.
fn norm_code(code: &[f64]) -> Result<Norm, String> {
    // SAFETY: an `f64` slice is initialised bytes, and a `u8` view of it
    // has no alignment to keep; the view lives only for the lookup.
    let bytes =
        unsafe { std::slice::from_raw_parts(code.as_ptr().cast::<u8>(), size_of_val(code)) };
    if let Some(n) = table()
        .read()
        .ok()
        .and_then(|t| t.by_code.get(bytes).copied())
    {
        return Ok(n);
    }
    let n = norm(from_code(code)?)?;
    if let Ok(mut t) = table().write()
        && t.by_code.len() < MAX_CALCS
    {
        t.by_code.insert(bytes.into(), n);
    }
    Ok(n)
}

/// A size expression in prefix code, as a sizing.
pub fn sizing_code(code: &[f64]) -> Result<crate::spec::Sizing, String> {
    norm_code(code).map(norm_sizing)
}

/// A size expression in prefix code, as a clamp.
pub fn bound_code(code: &[f64]) -> Result<crate::spec::Bound, String> {
    norm_bound(norm_code(code)?)
}

/// A size expression as data, as a sizing.
pub fn sizing_value(v: &crate::value::Value) -> Result<crate::spec::Sizing, String> {
    match v {
        crate::value::Value::Str(s) => sizing(s),
        v => Ok(norm_sizing(norm(from_value(v)?)?)),
    }
}

/// A size expression as data, as a clamp.
pub fn bound_value(v: &crate::value::Value) -> Result<crate::spec::Bound, String> {
    match v {
        crate::value::Value::Str(s) => bound(s),
        v => norm_bound(norm(from_value(v)?)?),
    }
}

/// An expression tree built by hand, as a sizing: C's builders and a
/// Rust view that composes one.
pub fn sizing_of(e: Expr) -> Result<crate::spec::Sizing, String> {
    Ok(norm_sizing(norm(e)?))
}

fn table() -> &'static RwLock<Table> {
    static TABLE: OnceLock<RwLock<Table>> = OnceLock::new();
    TABLE.get_or_init(Default::default)
}

/// The handle for `expr`: the one an equal expression already has, or a
/// new one.
pub fn intern(mut expr: Expr) -> Result<Calc, String> {
    canon(&mut expr, 0)?;
    intern_checked(expr)
}

/// [`intern`] for a tree [`canon`] has passed.
fn intern_checked(expr: Expr) -> Result<Calc, String> {
    if let Some(&id) = table()
        .read()
        .map_err(|e| e.to_string())?
        .by_expr
        .get(&expr)
    {
        return Ok(Calc(id));
    }
    let mut t = table().write().map_err(|e| e.to_string())?;
    if let Some(&id) = t.by_expr.get(&expr) {
        return Ok(Calc(id));
    }
    if t.exprs.len() >= MAX_CALCS {
        drop(t);
        return Err(refuse(&expr));
    }
    let id = t.exprs.len() as u32;
    t.exprs.push(Arc::new(expr.clone()));
    t.by_expr.insert(expr, id);
    Ok(Calc(id))
}

/// The table is full: `expr` is counted and named, and refused. Out of
/// line and cold, so the path every lookup takes stays as it was.
#[cold]
#[inline(never)]
fn refuse(expr: &Expr) -> String {
    let spelled = expr.to_string();
    REFUSED.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut last) = LAST_REFUSED.lock() {
        last.clone_from(&spelled);
    }
    format!(
        "{FULL} ({MAX_CALCS}): \"{spelled}\" is not kept — declare one per layout, not one per \
         frame"
    )
}

/// Parses a size expression; the public grammar, which a host validating
/// its own settings reuses so what it accepts is what kui draws.
pub fn parse(s: &str) -> Result<Expr, String> {
    let mut p = Parser {
        s: s.as_bytes(),
        at: 0,
    };
    let e = p.expr(0)?;
    p.skip_ws();
    if p.at < p.s.len() {
        return Err(p.error("the end"));
    }
    Ok(e)
}

/// What a spelling is as a sizing: a length, a percentage, or a
/// [`Calc`] for anything else.
pub fn sizing(s: &str) -> Result<crate::spec::Sizing, String> {
    norm_str(s).map(norm_sizing)
}

/// What a spelling is as a clamp: a length, or a [`Calc`] for one that
/// depends on the room.
pub fn bound(s: &str) -> Result<crate::spec::Bound, String> {
    norm_bound(norm_str(s)?)
}

struct Parser<'a> {
    s: &'a [u8],
    at: usize,
}

impl Parser<'_> {
    fn skip_ws(&mut self) {
        while self.s.get(self.at).is_some_and(|c| c.is_ascii_whitespace()) {
            self.at += 1;
        }
    }

    fn error(&self, wanted: &str) -> String {
        let rest = String::from_utf8_lossy(&self.s[self.at.min(self.s.len())..]);
        if rest.is_empty() {
            format!("bad size: {wanted} expected at the end")
        } else {
            format!("bad size: {wanted} expected at {rest:?}")
        }
    }

    fn eat(&mut self, word: &str) -> bool {
        self.skip_ws();
        if self.s[self.at..].starts_with(word.as_bytes()) {
            self.at += word.len();
            true
        } else {
            false
        }
    }

    /// One argument, `depth` functions in: past [`MAX_DEPTH`] it is
    /// refused before it is read, so the recursion is bounded by the cap
    /// and not by the input.
    fn expr(&mut self, depth: u32) -> Result<Expr, String> {
        if depth > MAX_DEPTH {
            return Err(too_deep(""));
        }
        self.skip_ws();
        for name in ["clamp", "min", "max"] {
            // As CSS reads a function: its name in any case, and the
            // parenthesis straight after it — `min (1, 2)` is no call
            //.
            let rest = &self.s[self.at..];
            if rest.len() > name.len()
                && rest[..name.len()].eq_ignore_ascii_case(name.as_bytes())
                && rest[name.len()] == b'('
            {
                self.at += name.len() + 1;
                let mut args = vec![self.expr(depth + 1)?];
                while self.eat(",") {
                    args.push(self.expr(depth + 1)?);
                }
                if !self.eat(")") {
                    return Err(self.error("\",\" or \")\""));
                }
                return match name {
                    "clamp" => match <[Expr; 3]>::try_from(args) {
                        Ok([a, b, c]) => Ok(Expr::Clamp(Box::new(a), Box::new(b), Box::new(c))),
                        Err(_) => {
                            Err("bad size: clamp takes three: clamp(MIN, TARGET, MAX)".into())
                        }
                    },
                    "min" => Ok(Expr::Min(args)),
                    _ => Ok(Expr::Max(args)),
                };
            }
        }
        let start = self.at;
        while self
            .s
            .get(self.at)
            .is_some_and(|c| c.is_ascii_digit() || *c == b'.')
        {
            self.at += 1;
        }
        let n: f32 = std::str::from_utf8(&self.s[start..self.at])
            .ok()
            .and_then(|t| t.parse().ok())
            .ok_or_else(|| {
                self.at = start;
                self.error("a number, \"N%\", \"Npx\", min(…), max(…) or clamp(…)")
            })?;
        // Digits alone can still overflow an `f32` (forty of them do):
        // an infinity is refused as `NaN` is from data.
        let n = finite(n)?;
        // The unit straight after the number, as CSS has it: `80 %` and
        // `100 px` are a number and a stray word.
        let rest = &self.s[self.at..];
        if rest.first() == Some(&b'%') {
            self.at += 1;
            Ok(Expr::Pct(finite(n / 100.0)?))
        } else {
            if rest.len() >= 2 && rest[..2].eq_ignore_ascii_case(b"px") {
                self.at += 2;
            }
            Ok(Expr::Px(n))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::spec::{Bound, Sizing};

    fn px(s: &str, room: f32) -> f32 {
        parse(s).unwrap().resolve(room)
    }

    #[test]
    fn expressions_resolve_against_the_room() {
        let c = "clamp(400px, 80%, 1000px)";
        assert_eq!(px(c, 300.0), 400.0, "the minimum");
        assert_eq!(px(c, 1000.0), 800.0, "the target");
        assert_eq!(px(c, 2000.0), 1000.0, "the maximum");
        assert_eq!(
            px("clamp(500, 10%, 200)", 1000.0),
            500.0,
            "the minimum over the maximum"
        );
        assert_eq!(px("min(720px, 100%)", 500.0), 500.0);
        assert_eq!(px("max(50%, 300)", 400.0), 300.0);
        assert_eq!(px("min(clamp(1, 50%, 900), 30%)", 1000.0), 300.0, "nested");
    }

    #[test]
    fn only_what_depends_on_the_room_is_a_calc() {
        assert_eq!(sizing("720px").unwrap(), Sizing::Fixed(720.0));
        assert_eq!(sizing("min(300px, 400)").unwrap(), Sizing::Fixed(300.0));
        assert_eq!(sizing("50%").unwrap(), Sizing::Percent(0.5));
        let Sizing::Calc(a) = sizing("clamp(400px,80%,1000px)").unwrap() else {
            panic!("a calc");
        };
        let Sizing::Calc(b) = sizing(" clamp( 400 , 80% , 1000px ) ").unwrap() else {
            panic!("a calc");
        };
        assert_eq!(a, b, "one entry per expression, however spelled");
        assert_eq!(a.describe(), "clamp(400px, 80%, 1000px)");
        assert_eq!(bound("300").unwrap(), Bound::Px(300.0));
        assert!(matches!(bound("50%").unwrap(), Bound::Calc(_)));
    }

    #[test]
    fn the_same_expression_as_data() {
        use crate::value::Value;
        let list = |xs: Vec<Value>| Value::List(xs);
        let map = |k: &str, v: Value| Value::Map([(k.to_string(), v)].into_iter().collect());
        let v = map(
            "clamp",
            list(vec![
                Value::Int(400),
                map("pct", Value::Int(80)),
                Value::Str("1000px".into()),
            ]),
        );
        let Sizing::Calc(a) = sizing_value(&v).unwrap() else {
            panic!("a calc");
        };
        assert_eq!(
            Some(a),
            match sizing("clamp(400px, 80%, 1000px)").unwrap() {
                Sizing::Calc(c) => Some(c),
                _ => None,
            },
            "one entry, spelled or built"
        );
        assert_eq!(
            sizing_value(&map("percent", Value::Int(50))).unwrap(),
            Sizing::Percent(0.5)
        );
        assert_eq!(
            sizing_value(&map("min", list(vec![Value::Int(300), Value::Int(400)]))).unwrap(),
            Sizing::Fixed(300.0)
        );
        assert!(
            sizing_value(&map("clamp", list(vec![Value::Int(1)])))
                .unwrap_err()
                .contains("three")
        );
        assert!(
            sizing_value(&map("wide", Value::Int(1)))
                .unwrap_err()
                .contains("no \"wide\"")
        );
    }

    #[test]
    fn the_same_expression_in_prefix_code() {
        let code = [5.0, 1.0, 400.0, 2.0, 0.8, 3.0, 2.0, 1.0, 1000.0, 2.0, 1.0];
        assert_eq!(
            from_code(&code).unwrap().to_string(),
            "clamp(400px, 80%, min(1000px, 100%))"
        );
        assert!(from_code(&code[..4]).unwrap_err().contains("truncated"));
        assert!(
            from_code(&[1.0, 3.0, 9.0])
                .unwrap_err()
                .contains("left over")
        );
        assert!(from_code(&[9.0]).unwrap_err().contains("no op 9"));
    }

    #[test]
    fn a_bad_one_says_where() {
        assert_eq!(
            parse("80%x").unwrap_err(),
            "bad size: the end expected at \"x\""
        );
        // CSS's spacing: the unit and a function's
        // parenthesis sit against what they belong to.
        assert_eq!(
            parse("80 %").unwrap_err(),
            "bad size: the end expected at \"%\""
        );
        assert_eq!(
            parse("100 px").unwrap_err(),
            "bad size: the end expected at \"px\""
        );
        assert!(
            parse("min (1, 2)")
                .unwrap_err()
                .contains("at \"min (1, 2)\"")
        );
        assert!(parse("1.2.3%").is_err());
        assert!(parse("50px%").unwrap_err().contains("at \"%\""));
        // And its case: names and units in any.
        assert_eq!(
            parse("MIN(10PX, 50%)").unwrap(),
            parse("min(10px, 50%)").unwrap()
        );
        assert_eq!(
            parse(" max( 1px ,2% ) ").unwrap(),
            parse("max(1px, 2%)").unwrap()
        );
        assert!(parse("clamp(1, 2)").unwrap_err().contains("three"));
        assert!(parse("wide").unwrap_err().contains("at \"wide\""));
        assert!(parse("min(1, 2").unwrap_err().contains("at the end"));
    }

    /// `n` functions nested, spelled, as data and as prefix code.
    fn nested(n: usize) -> (String, crate::value::Value, Vec<f64>, Expr) {
        use crate::value::Value;
        let spelled = format!("{}50%{}", "min(".repeat(n), ")".repeat(n));
        let mut data = Value::Map(vec![("pct".into(), Value::Int(50))]);
        let mut code = [3.0, 1.0].repeat(n);
        code.extend([2.0, 0.5]);
        let mut built = Expr::Pct(0.5);
        for _ in 0..n {
            data = Value::Map(vec![("min".into(), Value::List(vec![data]))]);
            built = Expr::Min(vec![built]);
        }
        (spelled, data, code, built)
    }

    /// Nesting stops at [`MAX_DEPTH`] whatever builds the tree: the
    /// parser and data recursed as deep as the input went, and `"min("`
    /// a hundred thousand times overflowed the stack.
    #[test]
    fn nesting_stops_at_the_cap() {
        let deep = parse(&"min(".repeat(100_000)).unwrap_err();
        assert_eq!(deep, "bad size: nested past 32");
        let (s, v, code, e) = nested(MAX_DEPTH as usize);
        assert!(parse(&s).is_ok(), "32 is allowed");
        assert!(from_value(&v).is_ok());
        assert!(from_code(&code).is_ok());
        assert!(intern(e).is_ok());
        let (s, v, code, e) = nested(MAX_DEPTH as usize + 1);
        assert_eq!(parse(&s).unwrap_err(), "bad size: nested past 32");
        assert_eq!(from_value(&v).unwrap_err(), "bad size: nested past 32");
        assert_eq!(
            from_code(&code).unwrap_err(),
            "bad size code: nested past 32"
        );
        assert_eq!(intern(e.clone()).unwrap_err(), "bad size: nested past 32");
        assert!(sizing_of(e).is_err(), "a tree built by hand is held to it");
        assert!(sizing(&s).is_err());
    }

    /// `NaN` equals nothing, so an expression holding one was a new entry
    /// each time it was declared — a view declaring it every frame filled
    /// the table — and `-0` was an entry apart from `0`.
    /// Every way in refuses a number that is not finite and reads `-0`
    /// as `0`.
    #[test]
    fn only_finite_numbers_and_one_zero() {
        use crate::value::Value;
        let map = |k: &str, v: Value| Value::Map(vec![(k.to_string(), v)]);
        let with = |n: f64| {
            map(
                "min",
                Value::List(vec![Value::Float(n), map("pct", Value::Int(50))]),
            )
        };
        for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] {
            let e = sizing_value(&with(n)).unwrap_err();
            assert!(e.contains("not a finite number"), "{n}: {e}");
            assert!(sizing_value(&map("px", Value::Float(n))).is_err());
            assert!(sizing_value(&map("pct", Value::Float(n))).is_err());
            assert!(from_code(&[3.0, 2.0, 1.0, n, 2.0, 0.5]).is_err());
            assert!(from_code(&[2.0, n]).is_err());
        }
        assert!(bound_value(&with(f64::NAN)).is_err());
        assert!(intern(Expr::Min(vec![Expr::Px(f32::NAN), Expr::Pct(0.5)])).is_err());
        assert!(sizing_of(Expr::Pct(f32::INFINITY)).is_err());
        let digits = format!("min(1{}px, 50%)", "0".repeat(40));
        assert!(parse(&digits).unwrap_err().contains("not a finite number"));
        assert!(parse(&format!("1{}%", "0".repeat(40))).is_err());

        let zero = sizing_value(&with(0.0)).unwrap();
        assert_eq!(sizing_value(&with(-0.0)).unwrap(), zero, "-0 is 0");
        assert_eq!(
            sizing_of(Expr::Min(vec![Expr::Px(-0.0), Expr::Pct(0.5)])).unwrap(),
            zero
        );
        assert_eq!(sizing_code(&[3.0, 2.0, 1.0, -0.0, 2.0, 0.5]).unwrap(), zero);
        assert_eq!(zero.describe(), "min(0px, 50%)");
    }
}