Skip to main content

atmos/os_lib/css/
values.rs

1// 分割: css.rs より機械的に移動(2026-07-16 リファクタ フェーズ3)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5/// Replace all `var(--name)` and `var(--name, fallback)` occurrences in a value string.
6/// カスタムプロパティが別のカスタムプロパティを参照する間接参照
7/// (例: `--a: var(--b); --b: red;` のとき `var(--a)` は `red` に解決される)に対応するため、
8/// 1パスの置換結果にまだ `var(` が残っていれば再帰的に解決する。循環参照時に無限再帰へ
9/// 陥らないよう、最大再帰深度(8)を設けて打ち切る。
10pub fn resolve_css_var(value: &str, vars: &impl VarLookup) -> String {
11    resolve_css_var_depth(value, vars, 0)
12}
13
14pub(crate) fn resolve_css_var_depth(value: &str, vars: &impl VarLookup, depth: u32) -> String {
15    if depth >= 8 {
16        return String::from(value);
17    }
18    let mut result = String::new();
19    let mut rest = value;
20    while let Some(start) = rest.find("var(") {
21        result.push_str(rest.get(..start).unwrap_or(""));
22        let after = rest.get(start + 4..).unwrap_or("");
23        // find matching closing paren
24        let mut depth_paren = 1usize;
25        let mut end = 0;
26        for (i, c) in after.char_indices() {
27            match c {
28                '(' => depth_paren += 1,
29                ')' => {
30                    depth_paren -= 1;
31                    if depth_paren == 0 {
32                        end = i;
33                        break;
34                    }
35                }
36                _ => {}
37            }
38        }
39        let inner = after.get(..end).unwrap_or("");
40        // split on first comma for fallback
41        let (var_name, fallback) = if let Some(comma_pos) = inner.find(',') {
42            (
43                inner.get(..comma_pos).unwrap_or("").trim(),
44                Some(inner.get(comma_pos + 1..).unwrap_or("").trim()),
45            )
46        } else {
47            (inner.trim(), None)
48        };
49        let resolved = vars
50            .var(var_name)
51            .map(String::from)
52            .or_else(|| fallback.map(|s| s.to_string()))
53            .unwrap_or_default();
54        // 参照先の値自体が別の var(...) を含む場合(間接参照)は再帰的に解決する。
55        let resolved = if resolved.contains("var(") {
56            resolve_css_var_depth(&resolved, vars, depth + 1)
57        } else {
58            resolved
59        };
60        result.push_str(&resolved);
61        rest = after.get(end + 1..).unwrap_or("");
62    }
63    result.push_str(rest);
64    result
65}
66
67/// `env(safe-area-inset-*)`等(CSS Environment Variables)を解決する。
68/// この処理系にはノッチ/デバイスセーフエリアという概念自体が存在しない
69/// (実機はRaspberry Pi 3B、ヘッドレスQEMU)ため、`var()`のような真の
70/// 環境変数テーブルは持たず、既知の`safe-area-inset-*`/
71/// `viewport-segment-*`系は常に`"0px"`、フォールバック指定があればそちらを
72/// 優先する「正直な既定値ゼロ」として解決する(丸ごと未対応だった。
73/// 2026-07-18 発見・実装)。
74pub fn resolve_css_env(value: &str) -> String {
75    let mut result = String::new();
76    let mut rest = value;
77    while let Some(start) = rest.find("env(") {
78        result.push_str(rest.get(..start).unwrap_or(""));
79        let after = rest.get(start + 4..).unwrap_or("");
80        let mut depth_paren = 1usize;
81        let mut end = 0;
82        for (i, c) in after.char_indices() {
83            match c {
84                '(' => depth_paren += 1,
85                ')' => {
86                    depth_paren -= 1;
87                    if depth_paren == 0 {
88                        end = i;
89                        break;
90                    }
91                }
92                _ => {}
93            }
94        }
95        let inner = after.get(..end).unwrap_or("");
96        let (_env_name, fallback) = if let Some(comma_pos) = inner.find(',') {
97            (
98                inner.get(..comma_pos).unwrap_or("").trim(),
99                Some(inner.get(comma_pos + 1..).unwrap_or("").trim()),
100            )
101        } else {
102            (inner.trim(), None)
103        };
104        let resolved = fallback.unwrap_or("0px").to_string();
105        let resolved = if resolved.contains("env(") {
106            resolve_css_env(&resolved)
107        } else {
108            resolved
109        };
110        result.push_str(&resolved);
111        rest = after.get(end + 1..).unwrap_or("");
112    }
113    result.push_str(rest);
114    result
115}
116
117/// 括弧 `(...)` と波括弧 `{...}` のネストを考慮し、最上位の `)` のバイト位置を返す。
118fn find_matching_paren_end(after: &str) -> Option<usize> {
119    let mut depth_paren = 1usize;
120    let mut depth_brace = 0usize;
121    for (i, c) in after.char_indices() {
122        match c {
123            '(' => depth_paren += 1,
124            ')' => {
125                depth_paren -= 1;
126                if depth_paren == 0 {
127                    return Some(i);
128                }
129            }
130            '{' => depth_brace += 1,
131            '}' => depth_brace = depth_brace.saturating_sub(1),
132            _ => {
133                let _ = depth_brace;
134            }
135        }
136    }
137    None
138}
139
140/// `(...)` や `{...}` のネスト深さ 0 で区切り文字 `sep` によって分割する。
141fn split_top_level_char(s: &str, sep: char) -> Vec<&str> {
142    let mut out = Vec::new();
143    let mut dp = 0usize;
144    let mut db = 0usize;
145    let mut start = 0usize;
146    for (i, c) in s.char_indices() {
147        match c {
148            '(' => dp += 1,
149            ')' => dp = dp.saturating_sub(1),
150            '{' => db += 1,
151            '}' => db = db.saturating_sub(1),
152            ch if ch == sep && dp == 0 && db == 0 => {
153                out.push(s.get(start..i).unwrap_or(""));
154                start = i + ch.len_utf8();
155            }
156            _ => {}
157        }
158    }
159    out.push(s.get(start..).unwrap_or(""));
160    out
161}
162
163/// `{ ... }` で囲まれていれば外側の波括弧と前後の空白を外す。
164fn unwrap_css_braces(s: &str) -> &str {
165    let t = s.trim();
166    if let Some(inner) = t.strip_prefix('{').and_then(|r| r.strip_suffix('}')) {
167        inner.trim()
168    } else {
169        t
170    }
171}
172
173/// CSS Values 5 `attr(name [type(...)], fallback)` を解決する(`content` 以外向け)。
174pub fn resolve_css_attr(
175    value: &str,
176    attrs: &alloc::collections::BTreeMap<String, String>,
177) -> String {
178    let mut result = String::new();
179    let mut rest = value;
180    while let Some(start) = rest.to_ascii_lowercase().find("attr(") {
181        result.push_str(rest.get(..start).unwrap_or(""));
182        let after = rest.get(start + 5..).unwrap_or("");
183        let Some(end) = find_matching_paren_end(after) else {
184            result.push_str(rest.get(start..).unwrap_or(""));
185            return result;
186        };
187        let inner = after.get(..end).unwrap_or("");
188        let parts = split_top_level_char(inner, ',');
189        let head = parts.first().copied().unwrap_or("").trim();
190        let attr_name = head.split_whitespace().next().unwrap_or("").to_ascii_lowercase();
191        let val_opt = attrs.get(&attr_name).map(String::as_str);
192        let fallback = parts.get(1).map(|s| unwrap_css_braces(s)).unwrap_or("");
193        let chosen = val_opt.unwrap_or(fallback);
194        let resolved = if chosen.to_ascii_lowercase().contains("attr(") {
195            resolve_css_attr(chosen, attrs)
196        } else {
197            String::from(chosen)
198        };
199        result.push_str(&resolved);
200        rest = after.get(end + 1..).unwrap_or("");
201    }
202    result.push_str(rest);
203    result
204}
205
206/// CSS Values 5 `random-item(<options>, <item1>, <item2>, ...)` を解決する。
207pub fn resolve_random_item(value: &str) -> String {
208    let mut result = String::new();
209    let mut rest = value;
210    while let Some(start) = rest.to_ascii_lowercase().find("random-item(") {
211        result.push_str(rest.get(..start).unwrap_or(""));
212        let after = rest.get(start + 12..).unwrap_or("");
213        let Some(end) = find_matching_paren_end(after) else {
214            result.push_str(rest.get(start..).unwrap_or(""));
215            return result;
216        };
217        let inner = after.get(..end).unwrap_or("");
218        let parts = split_top_level_char(inner, ',');
219        if parts.len() < 2 {
220            result.push_str(rest.get(start..start + 12 + end + 1).unwrap_or(""));
221            rest = after.get(end + 1..).unwrap_or("");
222            continue;
223        }
224        let opts = parts[0].trim();
225        let items = &parts[1..];
226        let mut idx = 0usize;
227        if let Some(fixed_rest) = opts.strip_prefix("fixed").or_else(|| {
228            if opts.len() >= 5 && opts.get(..5).is_some_and(|p| p.eq_ignore_ascii_case("fixed")) {
229                opts.get(5..)
230            } else {
231                None
232            }
233        }) {
234            let expr = fixed_rest.trim();
235            let p_opt = expr
236                .parse::<f64>()
237                .ok()
238                .or_else(|| eval_math_f32(expr, 100, 16.0).map(|v| v as f64));
239            if let Some(p_raw) = p_opt {
240                let p = p_raw.clamp(0.0, 1.0);
241                idx = if p >= 1.0 {
242                    items.len() - 1
243                } else {
244                    (libm::floor(p * items.len() as f64) as usize).min(items.len() - 1)
245                };
246            }
247        }
248        let chosen = unwrap_css_braces(items[idx]);
249        let resolved = if chosen.to_ascii_lowercase().contains("random-item(") {
250            resolve_random_item(chosen)
251        } else {
252            String::from(chosen)
253        };
254        result.push_str(&resolved);
255        rest = after.get(end + 1..).unwrap_or("");
256    }
257    result.push_str(rest);
258    result
259}
260
261/// `calc()`内の単一トークン(`10px`/`50%`/`2rem`/裸の数値等)をpxへ変換する。
262fn parse_calc_unit(s: &str, containing_width: i32) -> Option<f32> {
263    parse_calc_unit_with_font(s, containing_width, 16.0)
264}
265
266fn parse_calc_unit_with_font(s: &str, containing_width: i32, font_px: f32) -> Option<f32> {
267    parse_calc_unit_f64(s, containing_width, font_px).map(|v| v as f32)
268}
269
270/// [`parse_calc_unit_with_font`] の f64 版(`calc()` の途中の桁落ちを避ける。`(1vw - 6.3999px) * 1e7` など)。
271fn parse_calc_unit_f64(s: &str, containing_width: i32, font_px: f32) -> Option<f64> {
272    let s = s.trim();
273    if s.is_empty() {
274        return None;
275    }
276    let font = if font_px > 0.0 { font_px as f64 } else { 16.0 };
277    // 【2026-11-19 TODO S2】ビューポート単位の新しい書き方: `svh`/`lvh`/`dvh`(`w`・`min`・`max` 版も)は
278    // この実装ではビューポートが 1 つなので `vh` と同じ。論理単位 `vi`/`vb` は横書きなので `vw`/`vh`。
279    let norm;
280    let s = if !(s.contains("sv") || s.contains("lv") || s.contains("dv") || s.ends_with("vi") || s.ends_with("vb")) {
281        s
282    } else {
283        let lower = s.to_ascii_lowercase();
284        let ends = |u: &str| lower.strip_suffix(u).and_then(|n| n.strip_suffix(['s', 'l', 'd'])).filter(|n| n.chars().last().is_some_and(|c| c.is_ascii_digit() || c == '.'));
285        let mapped = ["vh", "vw", "vmin", "vmax"].iter().find_map(|u| ends(u).map(|n| alloc::format!("{}{}", n, u)));
286        let strip_sld = |n: &str| n.strip_suffix(['s', 'l', 'd']).filter(|m| m.chars().last().is_some_and(|c| c.is_ascii_digit() || c == '.')).unwrap_or(n).to_string();
287        let mapped = mapped.or_else(|| lower.strip_suffix("vi").map(|n| alloc::format!("{}vw", strip_sld(n))))
288            .or_else(|| lower.strip_suffix("vb").map(|n| alloc::format!("{}vh", strip_sld(n))));
289        if let Some(m) = mapped {
290            norm = m;
291            norm.as_str()
292        } else {
293            s
294        }
295    };
296    if let Some(n) = s.strip_suffix("px") {
297        return n.trim().parse::<f64>().ok();
298    }
299    if let Some(n) = s.strip_suffix("vh") {
300        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
301        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * h as f64);
302    }
303    if let Some(n) = s.strip_suffix("vw") {
304        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
305        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * w as f64);
306    }
307    if let Some(n) = s.strip_suffix("vmin") {
308        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
309        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
310        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * w.min(h) as f64);
311    }
312    if let Some(n) = s.strip_suffix("vmax") {
313        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
314        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
315        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * w.max(h) as f64);
316    }
317    if let Some(n) = s.strip_suffix("cqw").or_else(|| s.strip_suffix("cqi")) {
318        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * containing_width as f64);
319    }
320    if let Some(n) = s.strip_suffix("cqh").or_else(|| s.strip_suffix("cqb")) {
321        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
322        return n.trim().parse::<f64>().ok().map(|v| v / 100.0 * h as f64);
323    }
324    if let Some(n) = s.strip_suffix("rem") {
325        return n.trim().parse::<f64>().ok().map(|v| v * crate::os_lib::css::units::root_font_px() as f64);
326    }
327    if let Some(n) = s.strip_suffix("em") {
328        return n.trim().parse::<f64>().ok().map(|v| v * font);
329    }
330    if let Some(n) = s.strip_suffix('%') {
331        return n
332            .trim()
333            .parse::<f64>()
334            .ok()
335            .map(|v| v / 100.0 * containing_width as f64);
336    }
337    if let Some(n) = s.strip_suffix("in") {
338        return n.trim().parse::<f64>().ok().map(|v| v * 96.0);
339    }
340    if let Some(n) = s.strip_suffix("cm") {
341        return n.trim().parse::<f64>().ok().map(|v| v * 96.0 / 2.54);
342    }
343    if let Some(n) = s.strip_suffix("mm") {
344        return n.trim().parse::<f64>().ok().map(|v| v * 96.0 / 25.4);
345    }
346    if let Some(n) = s.strip_suffix("pt") {
347        return n.trim().parse::<f64>().ok().map(|v| v * 96.0 / 72.0);
348    }
349    if let Some(n) = s.strip_suffix("pc") {
350        return n.trim().parse::<f64>().ok().map(|v| v * 16.0);
351    }
352    if let Some(n) = s.strip_suffix('q') {
353        return n.trim().parse::<f64>().ok().map(|v| v * 96.0 / 101.6);
354    }
355    s.parse::<f64>().ok()
356}
357
358/// 式の中の角度(`90deg` `0.5turn` `100grad` `1rad`)をラジアンの数値へ書き換える(三角関数の引数用)。
359/// 長さの式に角度が混ざっているものは、ここを通らないので従来どおり解析に失敗する。
360fn angles_to_rad(expr: &str) -> String {
361    let mut out = String::with_capacity(expr.len());
362    let b = expr.as_bytes();
363    let mut i = 0;
364    while i < b.len() {
365        if b[i].is_ascii_digit() || (b[i] == b'.' && b.get(i + 1).is_some_and(|c| c.is_ascii_digit())) {
366            let st = i;
367            while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
368                i += 1;
369            }
370            let num = expr.get(st..i).unwrap_or("");
371            let rest = expr.get(i..).unwrap_or("");
372            let (unit_len, k) = if rest.starts_with("deg") {
373                (3, core::f32::consts::PI / 180.0)
374            } else if rest.starts_with("grad") {
375                (4, core::f32::consts::PI / 200.0)
376            } else if rest.starts_with("turn") {
377                (4, 2.0 * core::f32::consts::PI)
378            } else if rest.starts_with("rad") {
379                (3, 1.0)
380            } else {
381                (0, 1.0)
382            };
383            if unit_len > 0 {
384                if let Ok(v) = num.parse::<f32>() {
385                    out.push_str(&alloc::format!("{}", v * k));
386                    i += unit_len;
387                    continue;
388                }
389            }
390            out.push_str(num);
391        } else {
392            out.push(b[i] as char);
393            i += 1;
394        }
395    }
396    out
397}
398
399/// バイト位置`*pos`以降の空白をスキップする。
400fn calc_skip_ws(bytes: &[u8], pos: &mut usize) {
401    while *pos < bytes.len() && bytes[*pos] == b' ' {
402        *pos += 1;
403    }
404}
405
406/// `factor := '(' expr ')' | <数値+単位トークン>`。
407fn parse_calc_factor(s: &str, pos: &mut usize, containing_width: i32) -> Option<f32> {
408    parse_calc_factor_with_font(s, pos, containing_width, 16.0)
409}
410
411fn parse_calc_factor_with_font(s: &str, pos: &mut usize, containing_width: i32, font_px: f32) -> Option<f32> {
412    parse_calc_factor_f64(s, pos, containing_width, font_px).map(|v| v as f32)
413}
414
415fn parse_calc_factor_f64(s: &str, pos: &mut usize, containing_width: i32, font_px: f32) -> Option<f64> {
416    let bytes = s.as_bytes();
417    calc_skip_ws(bytes, pos);
418    if bytes.get(*pos) == Some(&b'(') {
419        *pos += 1;
420        let start = *pos;
421        let mut depth = 1i32;
422        while *pos < bytes.len() && depth > 0 {
423            match bytes[*pos] {
424                b'(' => depth += 1,
425                b')' => depth -= 1,
426                _ => {}
427            }
428            *pos += 1;
429        }
430        if depth != 0 {
431            return None;
432        }
433        let inner = s.get(start..pos.saturating_sub(1)).unwrap_or("");
434        return parse_calc_expr_f64(inner.trim(), containing_width, font_px);
435    }
436    // 数学関数(三角関数・`sqrt`・`pow`・`abs`・`sign`・`hypot`・`exp`・`log`)。引数は同じ式の文法で評価する。
437    {
438        let mut e = *pos;
439        while e < bytes.len() && (bytes[e].is_ascii_alphabetic() || bytes[e] == b'-') {
440            e += 1;
441        }
442        if e > *pos && bytes.get(e) == Some(&b'(') {
443            let name = s.get(*pos..e).unwrap_or("").to_ascii_lowercase();
444            if matches!(name.as_str(), "calc" | "min" | "max" | "clamp" | "round" | "mod" | "rem") {
445                let close = super::units::find_balanced_close(s, e)?;
446                let v = eval_math_f32(s.get(*pos..=close)?, containing_width, font_px)? as f64;
447                *pos = close + 1;
448                return Some(v);
449            }
450            if matches!(name.as_str(), "sibling-index" | "sibling-count") {
451                let close = super::units::find_balanced_close(s, e)?;
452                let inner = s.get(e + 1..close).unwrap_or("").trim();
453                if inner.is_empty() {
454                    if let Some((idx, cnt)) = super::color4::tree_counting_hint() {
455                        *pos = close + 1;
456                        return Some(if name == "sibling-index" { idx } else { cnt } as f64);
457                    }
458                }
459                return None;
460            }
461            if matches!(
462                name.as_str(),
463                "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "atan2" | "sqrt" | "pow" | "abs" | "sign" | "hypot" | "exp" | "log"
464            ) {
465                let close = super::units::find_balanced_close(s, e)?;
466                let inner = s.get(e + 1..close)?;
467                let args: alloc::vec::Vec<f64> = split_top_level_commas(inner)
468                    .iter()
469                    .map(|a| parse_calc_expr_f64(angles_to_rad(a.trim()).as_str(), containing_width, font_px))
470                    .collect::<Option<_>>()?;
471                *pos = close + 1;
472                let a0 = *args.first()?;
473                return Some(match (name.as_str(), args.len()) {
474                    ("sin", 1) => libm::sin(a0),
475                    ("cos", 1) => libm::cos(a0),
476                    ("tan", 1) => libm::tan(a0),
477                    ("asin", 1) => libm::asin(a0),
478                    ("acos", 1) => libm::acos(a0),
479                    ("atan", 1) => libm::atan(a0),
480                    ("atan2", 2) => libm::atan2(a0, args[1]),
481                    ("sqrt", 1) => libm::sqrt(a0),
482                    ("pow", 2) => libm::pow(a0, args[1]),
483                    ("abs", 1) => libm::fabs(a0),
484                    ("sign", 1) => if a0 > 0.0 { 1.0 } else if a0 < 0.0 { -1.0 } else { 0.0 },
485                    ("hypot", _) => libm::sqrt(args.iter().map(|x| x * x).sum::<f64>()),
486                    ("exp", 1) => libm::exp(a0),
487                    ("log", 1) => libm::log(a0),
488                    ("log", 2) => libm::log(a0) / libm::log(args[1]),
489                    _ => return None,
490                });
491            }
492        }
493    }
494    let start = *pos;
495    while *pos < bytes.len() {
496        let c = bytes[*pos];
497        // 【2026-10-18】`*`・`/` でも区切る(従来は `215px*-1` が 1 語扱いで解析に失敗していた。
498        // YouTube の `bottom:calc(var(--controls-height)*-1)`)。
499        if c == b' ' || c == b'(' || c == b')' || c == b'*' || c == b'/' {
500            break;
501        }
502        if (c == b'+' || c == b'-') && *pos > start {
503            break;
504        }
505        *pos += 1;
506    }
507    let token = s.get(start..*pos).unwrap_or("");
508    parse_calc_unit_f64(token, containing_width, font_px)
509}
510
511/// `term := factor (('*' | '/') factor)*`。乗除算は加減算より優先度が高い。
512fn parse_calc_term(s: &str, pos: &mut usize, containing_width: i32) -> Option<f32> {
513    parse_calc_term_with_font(s, pos, containing_width, 16.0)
514}
515
516fn parse_calc_term_with_font(s: &str, pos: &mut usize, containing_width: i32, font_px: f32) -> Option<f32> {
517    parse_calc_term_f64(s, pos, containing_width, font_px).map(|v| v as f32)
518}
519
520fn parse_calc_term_f64(s: &str, pos: &mut usize, containing_width: i32, font_px: f32) -> Option<f64> {
521    let bytes = s.as_bytes();
522    let mut value = parse_calc_factor_f64(s, pos, containing_width, font_px)?;
523    loop {
524        calc_skip_ws(bytes, pos);
525        match bytes.get(*pos) {
526            Some(b'*') => {
527                *pos += 1;
528                calc_skip_ws(bytes, pos);
529                let rhs = parse_calc_factor_f64(s, pos, containing_width, font_px)?;
530                value *= rhs;
531            }
532            Some(b'/') => {
533                *pos += 1;
534                calc_skip_ws(bytes, pos);
535                let rhs = parse_calc_factor_f64(s, pos, containing_width, font_px)?;
536                if rhs == 0.0 {
537                    return None;
538                }
539                value /= rhs;
540            }
541            _ => break,
542        }
543    }
544    Some(value)
545}
546
547/// `expr := term (('+' | '-') term)*`。任意個数の項を左結合で畳み込む。
548fn parse_calc_expr(s: &str, containing_width: i32) -> Option<f32> {
549    parse_calc_expr_with_font(s, containing_width, 16.0)
550}
551
552fn parse_calc_expr_with_font(s: &str, containing_width: i32, font_px: f32) -> Option<f32> {
553    parse_calc_expr_f64(s, containing_width, font_px).map(|v| v as f32)
554}
555
556/// [`parse_calc_expr_with_font`] の f64 版。加減乗除と単位の換算を f64 で行い、最後にだけ f32 へ丸める。
557fn parse_calc_expr_f64(s: &str, containing_width: i32, font_px: f32) -> Option<f64> {
558    let bytes = s.as_bytes();
559    let mut pos = 0usize;
560    let mut value = parse_calc_term_f64(s, &mut pos, containing_width, font_px)?;
561    loop {
562        calc_skip_ws(bytes, &mut pos);
563        match bytes.get(pos) {
564            Some(b'+') => {
565                pos += 1;
566                calc_skip_ws(bytes, &mut pos);
567                let rhs = parse_calc_term_f64(s, &mut pos, containing_width, font_px)?;
568                value += rhs;
569            }
570            Some(b'-') => {
571                pos += 1;
572                calc_skip_ws(bytes, &mut pos);
573                let rhs = parse_calc_term_f64(s, &mut pos, containing_width, font_px)?;
574                value -= rhs;
575            }
576            _ => break,
577        }
578    }
579    calc_skip_ws(bytes, &mut pos);
580    if pos != bytes.len() {
581        return None;
582    }
583    Some(value)
584}
585
586/// `calc()`式をpxへ評価する。四則演算・任意個数の項・丸括弧によるネストに対応する。
587pub fn eval_calc(expr: &str, containing_width: i32) -> Option<i32> {
588    eval_calc_with_font(expr, containing_width, 16.0)
589}
590
591/// 要素のフォントサイズ(`font_px`)を考慮して `calc()` 式を px へ評価する。
592pub fn eval_calc_with_font(expr: &str, containing_width: i32, font_px: f32) -> Option<i32> {
593    let inner = expr.trim();
594    let inner = inner
595        .strip_prefix("calc(")
596        .and_then(|s| s.strip_suffix(')'))?;
597    parse_calc_expr_with_font(inner.trim(), containing_width, font_px).map(|v| v as i32)
598}
599
600/// `min()` / `max()` / `clamp()` の引数を最上位のカンマだけで分割する。
601/// 引数内に `calc()`/`min()`/`max()`/`clamp()` がネストしていても、その内側の
602/// カンマは分割対象にしない(括弧の深さを追跡する)。
603pub(crate) fn split_top_level_commas(s: &str) -> alloc::vec::Vec<&str> {
604    let mut parts = alloc::vec::Vec::new();
605    let bytes = s.as_bytes();
606    let mut depth = 0i32;
607    let mut start = 0usize;
608    for (i, &b) in bytes.iter().enumerate() {
609        match b {
610            b'(' => depth += 1,
611            b')' => depth -= 1,
612            b',' if depth == 0 => {
613                parts.push(s.get(start..i).unwrap_or("").trim());
614                start = i + 1;
615            }
616            _ => {}
617        }
618    }
619    parts.push(s.get(start..).unwrap_or("").trim());
620    parts
621}
622
623/// 単一の `name: value` 宣言(`!important` 込み)をパースする。
624/// 空の name/value や区切りの `:` が無い場合は `None`。
625pub(crate) fn parse_one_declaration(raw: &str) -> Option<Declaration> {
626    let mut kv = raw.splitn(2, ':');
627    let name = kv.next()?.trim();
628    let raw_value = kv.next()?.trim();
629    let (value, important) = match raw_value.rfind('!') {
630        Some(pos)
631            if raw_value
632                .get(pos + 1..)
633                .unwrap_or("")
634                .trim()
635                .eq_ignore_ascii_case("important") =>
636        {
637            (raw_value.get(..pos).unwrap_or("").trim(), true)
638        }
639        _ => (raw_value, false),
640    };
641    if name.is_empty() || value.is_empty() {
642        return None;
643    }
644    // 不正な値の宣言は捨てる(TODO S2)。
645    if !declaration_value_valid(name, value) {
646        return None;
647    }
648    Some(Declaration {
649        name: String::from(name),
650        value: String::from(value),
651        important,
652    })
653}
654
655/// CSS Nesting のルール本体をパースする。トップレベル(このネストの深さ)の `;` で
656/// 宣言を区切り、トップレベルの `{` はネストしたルールの開始とみなして対応する `}`
657/// までを取り出し再帰する。ネストしたセレクタの各カンマ枝は、`&` を含めば親セレクタの
658/// テキストで置換し、含まなければ親セレクタの後ろに半角スペースで連結する(子孫結合子
659/// 扱い)。戻り値はこのレベル自身の宣言一覧(ネストしたルールは `out_rules` に積む)。
660pub(crate) fn parse_nested_body(
661    parent_selector_texts: &[String],
662    body: &str,
663    out_rules: &mut Vec<Rule>,
664    layer: Option<usize>,
665) -> Vec<Declaration> {
666    let mut declarations = Vec::new();
667    let chars: Vec<char> = body.chars().collect();
668    let mut i = 0usize;
669    let mut buf = String::new();
670    let mut in_quote: Option<char> = None;
671    let mut escaped = false;
672    let mut paren_depth = 0i32;
673    while i < chars.len() {
674        let ch = chars[i];
675        if escaped {
676            buf.push(ch);
677            escaped = false;
678            i += 1;
679            continue;
680        }
681        if ch == '\\' {
682            buf.push(ch);
683            escaped = true;
684            i += 1;
685            continue;
686        }
687        if let Some(q) = in_quote {
688            buf.push(ch);
689            if ch == q {
690                in_quote = None;
691            }
692            i += 1;
693            continue;
694        }
695        if ch == '"' || ch == '\'' {
696            in_quote = Some(ch);
697            buf.push(ch);
698            i += 1;
699            continue;
700        }
701        if ch == '(' {
702            paren_depth += 1;
703            buf.push(ch);
704            i += 1;
705            continue;
706        }
707        if ch == ')' {
708            if paren_depth > 0 {
709                paren_depth -= 1;
710            }
711            buf.push(ch);
712            i += 1;
713            continue;
714        }
715        if paren_depth > 0 {
716            buf.push(ch);
717            i += 1;
718            continue;
719        }
720        match ch {
721            '{' => {
722                let nested_selector_text = buf.trim().to_string();
723                buf.clear();
724                // 対応する `}` を探す(ネストの深さを追跡)。
725                let mut depth = 1i32;
726                let start = i + 1;
727                let mut j = start;
728                while j < chars.len() && depth > 0 {
729                    match chars[j] {
730                        '{' => depth += 1,
731                        '}' => depth -= 1,
732                        _ => {}
733                    }
734                    if depth > 0 {
735                        j += 1;
736                    }
737                }
738                let inner_body: String = chars[start..j.min(chars.len())].iter().collect();
739                i = j;
740                if !nested_selector_text.is_empty() {
741                    let mut resolved_texts: Vec<String> = Vec::new();
742                    for nb in split_top_level_commas(&nested_selector_text) {
743                        let nb = nb.trim();
744                        if nb.is_empty() {
745                            continue;
746                        }
747                        for parent in parent_selector_texts {
748                            let resolved = if nb.contains('&') {
749                                nb.replace('&', parent)
750                            } else {
751                                alloc::format!("{} {}", parent, nb)
752                            };
753                            resolved_texts.push(resolved);
754                        }
755                    }
756                    let nested_selectors: Vec<Selector> = resolved_texts
757                        .iter()
758                        .filter_map(|s| parse_selector(s.trim()))
759                        .collect();
760                    let nested_decls =
761                        parse_nested_body(&resolved_texts, &inner_body, out_rules, layer);
762                    if !nested_selectors.is_empty() && !nested_decls.is_empty() {
763                        out_rules.push(Rule {
764                            selectors: nested_selectors,
765                            declarations: nested_decls,
766                            layer,
767                            media_query: None,
768                            container_query: None,
769                        });
770                    }
771                }
772            }
773            ';' => {
774                if let Some(d) = parse_one_declaration(&buf) {
775                    declarations.push(d);
776                }
777                buf.clear();
778            }
779            c => buf.push(c),
780        }
781        i += 1;
782    }
783    // 末尾の `;` は省略可能なので、残った buf も最後の宣言として扱う。
784    if let Some(d) = parse_one_declaration(&buf) {
785        declarations.push(d);
786    }
787    declarations
788}
789
790/// 単一の長さ値(`10px` / `50%` / `calc(...)` など、四則演算を含まない1トークン、
791/// もしくは `calc()`/`min()`/`max()`/`clamp()` の再帰評価)を px へ解決する。
792pub(crate) fn eval_length_token(s: &str, containing_width: i32) -> Option<f32> {
793    eval_length_token_with_font(s, containing_width, 16.0)
794}
795
796pub(crate) fn eval_length_token_with_font(s: &str, containing_width: i32, font_px: f32) -> Option<f32> {
797    let t = s.trim();
798    if t.starts_with("calc(") || t.starts_with("min(") || t.starts_with("max(") || t.starts_with("clamp(")
799        || t.starts_with("abs(") || t.starts_with("sign(") || t.starts_with("round(")
800        || t.starts_with("mod(") || t.starts_with("rem(")
801    {
802        return eval_css_math_with_font(t, containing_width, font_px).map(|v| v as f32);
803    }
804    let font = if font_px > 0.0 { font_px } else { 16.0 };
805    if let Some(n) = t.strip_suffix("px") {
806        return n.trim().parse::<f32>().ok();
807    }
808    // 新しいビューポート単位(`svw`/`lvh`/`dvi`/`vb` など)は正規化を持つ `parse_calc_unit_with_font` へ任せる。
809    if t.contains("sv") || t.contains("lv") || t.contains("dv") || t.ends_with("vi") || t.ends_with("vb") {
810        return parse_calc_unit_with_font(t, containing_width, font);
811    }
812    if let Some(n) = t.strip_suffix("vh") {
813        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
814        return n.trim().parse::<f32>().ok().map(|v| v / 100.0 * h as f32);
815    }
816    if let Some(n) = t.strip_suffix("vw") {
817        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
818        return n.trim().parse::<f32>().ok().map(|v| v / 100.0 * w as f32);
819    }
820    if let Some(n) = t.strip_suffix("vmin") {
821        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
822        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
823        return n.trim().parse::<f32>().ok().map(|v| v / 100.0 * w.min(h) as f32);
824    }
825    if let Some(n) = t.strip_suffix("vmax") {
826        let w = crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed);
827        let h = crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed);
828        return n.trim().parse::<f32>().ok().map(|v| v / 100.0 * w.max(h) as f32);
829    }
830    if let Some(n) = t.strip_suffix("rem") {
831        return n.trim().parse::<f32>().ok().map(|v| v * crate::os_lib::css::units::root_font_px());
832    }
833    if let Some(n) = t.strip_suffix("em") {
834        return n.trim().parse::<f32>().ok().map(|v| v * font);
835    }
836    if let Some(n) = t.strip_suffix('%') {
837        return n
838            .trim()
839            .parse::<f32>()
840            .ok()
841            .map(|v| v / 100.0 * containing_width as f32);
842    }
843    if let Some(n) = t.strip_suffix("in") {
844        return n.trim().parse::<f32>().ok().map(|v| v * 96.0);
845    }
846    if let Some(n) = t.strip_suffix("cm") {
847        return n.trim().parse::<f32>().ok().map(|v| v * 96.0 / 2.54);
848    }
849    if let Some(n) = t.strip_suffix("mm") {
850        return n.trim().parse::<f32>().ok().map(|v| v * 96.0 / 25.4);
851    }
852    if let Some(n) = t.strip_suffix("pt") {
853        return n.trim().parse::<f32>().ok().map(|v| v * 96.0 / 72.0);
854    }
855    if let Some(n) = t.strip_suffix("pc") {
856        return n.trim().parse::<f32>().ok().map(|v| v * 16.0);
857    }
858    if let Some(n) = t.strip_suffix('q') {
859        return n.trim().parse::<f32>().ok().map(|v| v * 96.0 / 101.6);
860    }
861    t.parse::<f32>().ok()
862}
863
864/// CSS の数式関数(`calc()` / `min()` / `max()` / `clamp()` / `abs()` / `sign()` / `round()` / `mod()` / `rem()`)を px へ評価する。
865pub fn eval_css_math(expr: &str, containing_width: i32) -> Option<i32> {
866    eval_css_math_with_font(expr, containing_width, 16.0)
867}
868
869/// 要素のフォントサイズ(`font_px`)を考慮して CSS 数式関数を px へ評価する。
870pub fn eval_css_math_with_font(expr: &str, containing_width: i32, font_px: f32) -> Option<i32> {
871    eval_math_f32(expr, containing_width, font_px).map(|v| v as i32)
872}
873
874/// 数式関数の引数 1 個を評価する。従来どおり関数・単一トークンは `eval_length_token_with_font`(途中を整数へ
875/// 丸める)で、それで読めない式(`NaN * 1px`・`10px + 5px` など)は `+ - * /` の式として評価する。
876fn eval_math_arg(a: &str, containing_width: i32, font_px: f32) -> Option<f32> {
877    let at = a.trim();
878    if at.starts_with("calc(")
879        || at.starts_with("min(")
880        || at.starts_with("max(")
881        || at.starts_with("clamp(")
882        || at.starts_with("abs(")
883        || at.starts_with("sign(")
884        || at.starts_with("round(")
885        || at.starts_with("mod(")
886        || at.starts_with("rem(")
887    {
888        if let Some(v) = eval_math_f32(at, containing_width, font_px) {
889            return Some(v);
890        }
891    }
892    eval_length_token_with_font(a, containing_width, font_px)
893        .or_else(|| parse_calc_expr_with_font(at, containing_width, font_px))
894}
895
896/// `min()`/`max()`/`clamp()` の引数のどれかが NaN なら結果も NaN(CSS Values 4 §10.9)。
897fn math_args(inner: &str, containing_width: i32, font_px: f32) -> alloc::vec::Vec<f32> {
898    split_top_level_commas(inner).iter().filter_map(|a| eval_math_arg(a, containing_width, font_px)).collect()
899}
900
901/// `calc()`・`min()`・`max()`・`clamp()`・`abs()`・`sign()`・`round()`・`mod()`・`rem()` を f32 で評価する。
902pub(crate) fn eval_math_f32(expr: &str, containing_width: i32, font_px: f32) -> Option<f32> {
903    let t = expr.trim();
904    if t.starts_with("calc(") {
905        let inner = t.strip_prefix("calc(").and_then(|s| s.strip_suffix(')'))?;
906        return parse_calc_expr_with_font(inner.trim(), containing_width, font_px);
907    }
908    if let Some(inner) = t.strip_prefix("min(").and_then(|s| s.strip_suffix(')')) {
909        let vals = math_args(inner, containing_width, font_px);
910        if vals.iter().any(|v| v.is_nan()) {
911            return Some(f32::NAN);
912        }
913        return vals.into_iter().fold(None, |acc, v| Some(acc.map_or(v, |m: f32| m.min(v))));
914    }
915    if let Some(inner) = t.strip_prefix("max(").and_then(|s| s.strip_suffix(')')) {
916        let vals = math_args(inner, containing_width, font_px);
917        if vals.iter().any(|v| v.is_nan()) {
918            return Some(f32::NAN);
919        }
920        return vals.into_iter().fold(None, |acc, v| Some(acc.map_or(v, |m: f32| m.max(v))));
921    }
922    if let Some(inner) = t.strip_prefix("clamp(").and_then(|s| s.strip_suffix(')')) {
923        let parts = split_top_level_commas(inner);
924        if parts.len() != 3 {
925            return None;
926        }
927        // `none` は下限・上限なし。
928        let min_v = if parts[0].trim() == "none" { f32::NEG_INFINITY } else { eval_math_arg(parts[0], containing_width, font_px)? };
929        let pref_v = eval_math_arg(parts[1], containing_width, font_px)?;
930        let max_v = if parts[2].trim() == "none" { f32::INFINITY } else { eval_math_arg(parts[2], containing_width, font_px)? };
931        if min_v.is_nan() || pref_v.is_nan() || max_v.is_nan() {
932            return Some(f32::NAN);
933        }
934        let effective_max = max_v.max(min_v);
935        return Some(pref_v.clamp(min_v, effective_max));
936    }
937    // W3C CSS Values and Units Level 4 数学関数
938    if let Some(inner) = t.strip_prefix("abs(").and_then(|s| s.strip_suffix(')')) {
939        let v = eval_math_arg(inner.trim(), containing_width, font_px)?;
940        return Some(v.abs());
941    }
942    if let Some(inner) = t.strip_prefix("sign(").and_then(|s| s.strip_suffix(')')) {
943        let v = eval_math_arg(inner.trim(), containing_width, font_px)?;
944        if v.is_nan() {
945            return Some(f32::NAN);
946        }
947        return Some(if v > 0.0 {
948            1.0
949        } else if v < 0.0 {
950            -1.0
951        } else {
952            0.0
953        });
954    }
955    if let Some(inner) = t.strip_prefix("round(").and_then(|s| s.strip_suffix(')')) {
956        let parts = split_top_level_commas(inner);
957        let (strategy, val_tok, step_tok) = match parts.len() {
958            1 => ("nearest", parts[0], "1px"),
959            2 => {
960                let p0 = parts[0].trim().to_ascii_lowercase();
961                if p0 == "up" || p0 == "down" || p0 == "nearest" || p0 == "to-zero" {
962                    (parts[0].trim(), parts[1], "1px")
963                } else {
964                    ("nearest", parts[0], parts[1])
965                }
966            }
967            3 => (parts[0].trim(), parts[1], parts[2]),
968            _ => return None,
969        };
970        let val = eval_math_arg(val_tok, containing_width, font_px)?;
971        let step = eval_math_arg(step_tok, containing_width, font_px)?.abs();
972        if val.is_nan() || step.is_nan() {
973            return Some(f32::NAN);
974        }
975        if step == 0.0 {
976            return Some(val);
977        }
978        let rounded = match strategy.to_ascii_lowercase().as_str() {
979            "up" => libm::ceilf(val / step) * step,
980            "down" => libm::floorf(val / step) * step,
981            "to-zero" => libm::truncf(val / step) * step,
982            _ => libm::roundf(val / step) * step,
983        };
984        return Some(rounded);
985    }
986    if let Some(inner) = t.strip_prefix("mod(").and_then(|s| s.strip_suffix(')')) {
987        let parts = split_top_level_commas(inner);
988        if parts.len() != 2 {
989            return None;
990        }
991        let a = eval_math_arg(parts[0], containing_width, font_px)?;
992        let b = eval_math_arg(parts[1], containing_width, font_px)?;
993        if b == 0.0 {
994            return None;
995        }
996        return Some((a % b + b) % b);
997    }
998    if let Some(inner) = t.strip_prefix("rem(").and_then(|s| s.strip_suffix(')')) {
999        let parts = split_top_level_commas(inner);
1000        if parts.len() != 2 {
1001            return None;
1002        }
1003        let a = eval_math_arg(parts[0], containing_width, font_px)?;
1004        let b = eval_math_arg(parts[1], containing_width, font_px)?;
1005        if b == 0.0 {
1006            return None;
1007        }
1008        return Some(a % b);
1009    }
1010    None
1011}
1012
1013// 簡易CSSパーサ(tag / #id / .class と宣言ブロックをサポート)
1014
1015// ---------------------------------------------------------------------------
1016// 宣言値の検証(TODO S2・spec/css_wpt.md §5-1、2026-11-19)。
1017// 不正な宣言は構文解析の段階で捨てる(ブラウザと同じ)。保守的に作る: 判定できないものは「有効」とする。
1018// `var()`/`env()`/`attr()`/`if()`・バックスラッシュのエスケープ・ベンダー接頭辞(`-webkit-` など)・
1019// CSS 全体キーワード・未知のプロパティは常に有効とみなす。
1020// ---------------------------------------------------------------------------
1021
1022/// 値を最上位の空白で区切る(`()`・`[]`・引用符の中は区切らない)。
1023pub(crate) fn split_top_ws(v: &str) -> Vec<&str> {
1024    let b = v.as_bytes();
1025    let mut out = Vec::new();
1026    let mut depth = 0i32;
1027    let mut quote = 0u8;
1028    let mut start: Option<usize> = None;
1029    for (i, &c) in b.iter().enumerate() {
1030        if quote != 0 {
1031            if c == quote {
1032                quote = 0;
1033            }
1034            continue;
1035        }
1036        match c {
1037            b'"' | b'\'' => {
1038                quote = c;
1039                if start.is_none() {
1040                    start = Some(i);
1041                }
1042            }
1043            b'(' | b'[' => {
1044                depth += 1;
1045                if start.is_none() {
1046                    start = Some(i);
1047                }
1048            }
1049            b')' | b']' => depth -= 1,
1050            c if c.is_ascii_whitespace() && depth <= 0 => {
1051                if let Some(s) = start.take() {
1052                    out.push(v.get(s..i).unwrap_or(""));
1053                }
1054            }
1055            _ => {
1056                if start.is_none() {
1057                    start = Some(i);
1058                }
1059            }
1060        }
1061    }
1062    if let Some(s) = start {
1063        out.push(v.get(s..).unwrap_or(""));
1064    }
1065    out
1066}
1067
1068/// 1 トークンの分類。
1069enum Tok {
1070    /// 単位なしの数(`neg`: 負、`zero`: 0、`int`: 整数)。
1071    Num { neg: bool, zero: bool, int: bool },
1072    /// 長さ(`neg`: 負、`zero`: 0)。
1073    Len { neg: bool, zero: bool },
1074    /// `fr` 付き(グリッドのトラック)。
1075    Fr { neg: bool },
1076    Pct { neg: bool },
1077    /// 数式関数など(中身は検証しない)。
1078    Func,
1079    Other,
1080}
1081
1082const LEN_UNITS: &[&str] = &[
1083    "px", "em", "rem", "ex", "rex", "ch", "rch", "cap", "rcap", "ic", "ric", "lh", "rlh", "vw", "vh", "vi", "vb",
1084    "vmin", "vmax", "svw", "svh", "svi", "svb", "svmin", "svmax", "lvw", "lvh", "lvi", "lvb", "lvmin", "lvmax",
1085    "dvw", "dvh", "dvi", "dvb", "dvmin", "dvmax", "cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax", "cm", "mm", "q",
1086    "in", "pt", "pc",
1087];
1088
1089fn classify(tok: &str) -> Tok {
1090    if let Some(p) = tok.find('(') {
1091        if tok.ends_with(')') {
1092            let name = tok.get(..p).unwrap_or("");
1093            // 数式関数に限らず未知の関数(`random()`・`calc-size()` など新しい仕様)は、中身を見ずに有効とみなす。
1094            if !name.is_empty() {
1095                return Tok::Func;
1096            }
1097        }
1098        return Tok::Other;
1099    }
1100    let b = tok.as_bytes();
1101    let mut i = 0usize;
1102    let mut neg = false;
1103    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1104        neg = b[i] == b'-';
1105        i += 1;
1106    }
1107    let ds = i;
1108    while i < b.len() && b[i].is_ascii_digit() {
1109        i += 1;
1110    }
1111    let mut int = true;
1112    let mut nonzero = ds != i && tok.get(ds..i).unwrap_or("").bytes().any(|c| c != b'0');
1113    let mut has_digit = ds != i;
1114    if i < b.len() && b[i] == b'.' {
1115        int = false;
1116        i += 1;
1117        let fs = i;
1118        while i < b.len() && b[i].is_ascii_digit() {
1119            i += 1;
1120        }
1121        if fs != i {
1122            has_digit = true;
1123            if tok.get(fs..i).unwrap_or("").bytes().any(|c| c != b'0') {
1124                nonzero = true;
1125            }
1126        }
1127    }
1128    if !has_digit {
1129        return Tok::Other;
1130    }
1131    // 指数部(`1e3`)。`em`/`ex` の単位と取り違えないよう、`e` の後ろが数字(または符号+数字)のときだけ指数。
1132    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
1133        let mut j = i + 1;
1134        if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
1135            j += 1;
1136        }
1137        if j < b.len() && b[j].is_ascii_digit() {
1138            int = false;
1139            while j < b.len() && b[j].is_ascii_digit() {
1140                j += 1;
1141            }
1142            i = j;
1143        }
1144    }
1145    let unit = tok.get(i..).unwrap_or("");
1146    let zero = !nonzero;
1147    if unit.is_empty() {
1148        return Tok::Num { neg, zero, int };
1149    }
1150    if unit == "%" {
1151        return Tok::Pct { neg };
1152    }
1153    if unit.eq_ignore_ascii_case("fr") {
1154        return Tok::Fr { neg };
1155    }
1156    if LEN_UNITS.iter().any(|u| unit.eq_ignore_ascii_case(u)) {
1157        return Tok::Len { neg, zero };
1158    }
1159    Tok::Other
1160}
1161
1162fn is_css_wide(v: &str) -> bool {
1163    ["inherit", "initial", "unset", "revert", "revert-layer"]
1164        .iter()
1165        .any(|k| v.eq_ignore_ascii_case(k))
1166}
1167
1168/// `<length-percentage>`(`allow_neg` が偽なら負を拒否)。単位なしは `0` のみ。
1169fn is_len_pct(tok: &str, allow_neg: bool) -> bool {
1170    match classify(tok) {
1171        Tok::Len { neg, .. } | Tok::Pct { neg } => allow_neg || !neg,
1172        // 単位なしの数(`margin: 10`)は標準モードでは不正だが、互換モード(quirks)のブラウザは受け入れる。
1173        // このエンジンは互換モードを追跡していないため、古い実ページを壊さないよう従来どおり受理する。
1174        // TODO: 互換モードを追跡できるようになったら、標準モードでは拒否に戻す。
1175        Tok::Num { neg, zero, .. } => zero || allow_neg || !neg,
1176        Tok::Func => calc_length_type_ok(tok),
1177        _ => false,
1178    }
1179}
1180
1181/// `calc()` の型検査の結果(CSS Values 4 §10.8 型の付いた演算)。
1182enum CalcTy {
1183    /// 長さの次数(`px`・`%` は 1、単位なしの数は 0。`*` で足し、`/` で引く)。
1184    Pow(i32),
1185    /// 型が合わない(`1px + 1` のような異なる型の加減算)。
1186    Bad,
1187    /// 調べられない(未知の関数・長さ以外の単位など)。保守的に有効とみなす。
1188    Unknown,
1189}
1190
1191/// `<length-percentage>` の文脈の `calc(...)` が長さの型(次数 1)になるか。調べられないものは有効とする。
1192/// 例: `calc((10% * 1%) / 1px)` は長さで有効、`calc((1% * 1% * 1%) / 1px)` は長さの 2 乗で不正。
1193fn calc_length_type_ok(tok: &str) -> bool {
1194    let t = tok.trim();
1195    let Some(inner) = t.get(..5).filter(|p| p.eq_ignore_ascii_case("calc(")).and_then(|_| t.get(5..t.len() - 1)) else {
1196        return true;
1197    };
1198    let b = inner.as_bytes();
1199    let mut pos = 0usize;
1200    let ty = calc_ty_expr(b, &mut pos);
1201    calc_ty_ws(b, &mut pos);
1202    match ty {
1203        _ if pos != b.len() => true,
1204        CalcTy::Pow(p) => p == 0 || p == 1,
1205        CalcTy::Bad => false,
1206        CalcTy::Unknown => true,
1207    }
1208}
1209
1210fn calc_ty_ws(b: &[u8], pos: &mut usize) {
1211    while b.get(*pos).is_some_and(|c| c.is_ascii_whitespace()) {
1212        *pos += 1;
1213    }
1214}
1215
1216fn calc_ty_expr(b: &[u8], pos: &mut usize) -> CalcTy {
1217    let mut acc = calc_ty_term(b, pos);
1218    loop {
1219        let save = *pos;
1220        calc_ty_ws(b, pos);
1221        // 加減算の `+`/`-` は前後に空白が要る(CSS Values 4 §10.1)。
1222        if !matches!(b.get(*pos), Some(b'+' | b'-')) || *pos == save || !b.get(*pos + 1).is_some_and(|c| c.is_ascii_whitespace()) {
1223            *pos = save;
1224            return acc;
1225        }
1226        *pos += 1;
1227        calc_ty_ws(b, pos);
1228        let rhs = calc_ty_term(b, pos);
1229        acc = match (acc, rhs) {
1230            (CalcTy::Bad, _) | (_, CalcTy::Bad) => CalcTy::Bad,
1231            (CalcTy::Pow(x), CalcTy::Pow(y)) if x == y => CalcTy::Pow(x),
1232            (CalcTy::Pow(_), CalcTy::Pow(_)) => CalcTy::Bad,
1233            _ => CalcTy::Unknown,
1234        };
1235    }
1236}
1237
1238fn calc_ty_term(b: &[u8], pos: &mut usize) -> CalcTy {
1239    let mut acc = calc_ty_factor(b, pos);
1240    loop {
1241        let save = *pos;
1242        calc_ty_ws(b, pos);
1243        let op = match b.get(*pos) {
1244            Some(b'*') => 1,
1245            Some(b'/') => -1,
1246            _ => {
1247                *pos = save;
1248                return acc;
1249            }
1250        };
1251        *pos += 1;
1252        calc_ty_ws(b, pos);
1253        let rhs = calc_ty_factor(b, pos);
1254        acc = match (acc, rhs) {
1255            (CalcTy::Bad, _) | (_, CalcTy::Bad) => CalcTy::Bad,
1256            (CalcTy::Pow(x), CalcTy::Pow(y)) => CalcTy::Pow(x + op * y),
1257            _ => CalcTy::Unknown,
1258        };
1259    }
1260}
1261
1262fn calc_ty_factor(b: &[u8], pos: &mut usize) -> CalcTy {
1263    calc_ty_ws(b, pos);
1264    let st = *pos;
1265    // 丸括弧と入れ子の `calc(`。
1266    let is_calc = b.get(st..st + 5).is_some_and(|p| p.eq_ignore_ascii_case(b"calc("));
1267    if b.get(st) == Some(&b'(') || is_calc {
1268        *pos += if is_calc { 5 } else { 1 };
1269        let ty = calc_ty_expr(b, pos);
1270        calc_ty_ws(b, pos);
1271        if b.get(*pos) != Some(&b')') {
1272            return CalcTy::Unknown;
1273        }
1274        *pos += 1;
1275        return ty;
1276    }
1277    // 数(符号・小数・指数)+ 単位。
1278    let mut i = st;
1279    if matches!(b.get(i), Some(b'+' | b'-')) {
1280        i += 1;
1281    }
1282    let ds = i;
1283    while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'.') {
1284        i += 1;
1285    }
1286    if i == ds {
1287        return CalcTy::Unknown;
1288    }
1289    if matches!(b.get(i), Some(b'e' | b'E'))
1290        && (b.get(i + 1).is_some_and(|c| c.is_ascii_digit())
1291            || (matches!(b.get(i + 1), Some(b'+' | b'-')) && b.get(i + 2).is_some_and(|c| c.is_ascii_digit())))
1292    {
1293        i += 2;
1294        while b.get(i).is_some_and(|c| c.is_ascii_digit()) {
1295            i += 1;
1296        }
1297    }
1298    let us = i;
1299    if b.get(i) == Some(&b'%') {
1300        *pos = i + 1;
1301        return CalcTy::Pow(1);
1302    }
1303    while b.get(i).is_some_and(|c| c.is_ascii_alphabetic()) {
1304        i += 1;
1305    }
1306    *pos = i;
1307    let unit = core::str::from_utf8(&b[us..i]).unwrap_or("");
1308    if unit.is_empty() {
1309        CalcTy::Pow(0)
1310    } else if LEN_UNITS.iter().any(|u| unit.eq_ignore_ascii_case(u)) {
1311        CalcTy::Pow(1)
1312    } else {
1313        CalcTy::Unknown
1314    }
1315}
1316
1317fn is_vendor_kw(tok: &str) -> bool {
1318    tok.starts_with('-') && tok.len() > 1 && tok.as_bytes()[1].is_ascii_alphabetic()
1319}
1320
1321fn kw_in(tok: &str, set: &[&str]) -> bool {
1322    set.iter().any(|k| tok.eq_ignore_ascii_case(k))
1323}
1324
1325/// 自動サイズ系(`width`/`height`/`min-*`/`max-*`/`flex-basis`)の 1 トークン。
1326fn is_size_tok(tok: &str, extra: &[&str]) -> bool {
1327    if kw_in(tok, extra) || is_vendor_kw(tok) {
1328        return true;
1329    }
1330    if kw_in(tok, &["min-content", "max-content", "fit-content", "stretch", "contain", "fill"]) {
1331        return true;
1332    }
1333    let fname = tok.split('(').next().unwrap_or("");
1334    if tok.ends_with(')') && tok.contains('(') && fname.eq_ignore_ascii_case("stretch") {
1335        let inner = tok.get(fname.len() + 1..tok.len() - 1).unwrap_or("").trim();
1336        return !inner.is_empty() && is_len_pct(inner, false);
1337    }
1338    let lower_fc = tok.len() > 12 && tok.get(..12).is_some_and(|p| p.eq_ignore_ascii_case("fit-content("));
1339    if lower_fc && tok.ends_with(')') {
1340        let inner = tok.get(12..tok.len() - 1).unwrap_or("").trim();
1341        return !inner.is_empty() && is_len_pct(inner, false);
1342    }
1343    is_len_pct(tok, false)
1344}
1345
1346fn is_non_neg_number(tok: &str) -> bool {
1347    match classify(tok) {
1348        Tok::Num { neg, zero, .. } => !neg || zero,
1349        Tok::Func => true,
1350        _ => false,
1351    }
1352}
1353
1354fn is_integer(tok: &str) -> bool {
1355    match classify(tok) {
1356        Tok::Num { int, .. } => int,
1357        Tok::Func => true,
1358        _ => false,
1359    }
1360}
1361
1362/// グリッド線 1 つ(`auto` / 整数 / 名前 / `span ...`)。
1363fn is_grid_line(v: &str) -> bool {
1364    let toks = split_top_ws(v);
1365    if toks.is_empty() || toks.len() > 3 {
1366        return false;
1367    }
1368    if toks.len() == 1 && toks[0].eq_ignore_ascii_case("auto") {
1369        return true;
1370    }
1371    let mut span_idx: Option<usize> = None;
1372    let mut int = false;
1373    let mut neg_int = false;
1374    let mut ident = false;
1375    for (i, t) in toks.iter().enumerate() {
1376        if t.eq_ignore_ascii_case("span") {
1377            if span_idx.is_some() {
1378                return false;
1379            }
1380            span_idx = Some(i);
1381        } else if let Tok::Num { zero, int: is_int, neg } = classify(t) {
1382            if !is_int || int || zero {
1383                return false;
1384            }
1385            int = true;
1386            neg_int = neg;
1387        } else if matches!(classify(t), Tok::Func) {
1388            int = true;
1389        } else {
1390            let first = t.as_bytes().first().copied().unwrap_or(b'0');
1391            let ok = (first.is_ascii_alphabetic() || first == b'_' || first >= 0x80 || first == b'-')
1392                && !t.contains('(')
1393                && !t.eq_ignore_ascii_case("auto");
1394            if !ok || ident {
1395                return false;
1396            }
1397            ident = true;
1398        }
1399    }
1400    if let Some(si) = span_idx {
1401        if neg_int {
1402            return false;
1403        }
1404        // `span` は先頭か末尾のみ(`2 span first` や `first span 2` は不正)。
1405        if toks.len() == 3 && si == 1 {
1406            return false;
1407        }
1408    }
1409    int || ident
1410}
1411
1412fn is_grid_line_pair(v: &str) -> bool {
1413    let parts: Vec<&str> = v.split('/').collect();
1414    parts.len() <= 2 && parts.iter().all(|p| is_grid_line(p.trim()))
1415}
1416
1417/// トラック 1 つ(`auto-*`/固定サイズ・`minmax()`・`fit-content()`・`repeat()` を許すかは `allow_repeat`)。
1418fn is_track_tok(tok: &str, allow_repeat: bool) -> bool {
1419    if kw_in(tok, &["auto", "min-content", "max-content"]) {
1420        return true;
1421    }
1422    if let Some(p) = tok.find('(') {
1423        if !tok.ends_with(')') {
1424            return false;
1425        }
1426        let name = tok.get(..p).unwrap_or("");
1427        if name.eq_ignore_ascii_case("minmax") || name.eq_ignore_ascii_case("fit-content") {
1428            return true;
1429        }
1430        if name.eq_ignore_ascii_case("repeat") {
1431            return allow_repeat;
1432        }
1433    }
1434    match classify(tok) {
1435        Tok::Len { neg, .. } | Tok::Pct { neg } | Tok::Fr { neg } => !neg,
1436        Tok::Num { zero, .. } => zero,
1437        Tok::Func => true,
1438        _ => false,
1439    }
1440}
1441
1442fn is_track_list(v: &str, allow_names: bool, allow_repeat: bool) -> bool {
1443    let toks = split_top_ws(v);
1444    if toks.is_empty() {
1445        return false;
1446    }
1447    let mut start = 0usize;
1448    if toks.len() == 1 && toks[0].eq_ignore_ascii_case("none") {
1449        return true;
1450    }
1451    if allow_names && (toks[0].eq_ignore_ascii_case("subgrid") || toks[0].eq_ignore_ascii_case("masonry")) {
1452        start = 1;
1453    }
1454    toks[start..].iter().all(|t| {
1455        if t.starts_with('[') {
1456            return allow_names && t.ends_with(']');
1457        }
1458        is_track_tok(t, allow_repeat)
1459    })
1460}
1461
1462fn is_margin_tok(tok: &str) -> bool {
1463    tok.eq_ignore_ascii_case("auto") || is_len_pct(tok, true)
1464}
1465
1466fn all_tokens(v: &str, min: usize, max: usize, f: impl Fn(&str) -> bool) -> bool {
1467    let toks = split_top_ws(v);
1468    toks.len() >= min && toks.len() <= max && toks.iter().all(|t| f(t))
1469}
1470
1471fn flex_shorthand_valid(v: &str) -> bool {
1472    let toks = split_top_ws(v);
1473    if toks.is_empty() || toks.len() > 3 {
1474        return false;
1475    }
1476    if toks.len() == 1 && toks[0].eq_ignore_ascii_case("none") {
1477        return true;
1478    }
1479    let is_n = is_non_neg_number;
1480    let is_b = |t: &str| match classify(t) {
1481        Tok::Num { zero, .. } => zero,
1482        _ => is_size_tok(t, &["auto", "content"]),
1483    };
1484    let n = |i: usize| is_n(toks[i]);
1485    let b = |i: usize| is_b(toks[i]);
1486    match toks.len() {
1487        1 => n(0) || b(0),
1488        2 => (n(0) && n(1)) || (n(0) && b(1)) || (b(0) && n(1)),
1489        _ => (n(0) && n(1) && b(2)) || (b(0) && n(1) && n(2)),
1490    }
1491}
1492
1493/// 宣言 `name: value`(`!important` は除いた値)が構文として有効かを返す。判定できないものは `true`。
1494pub(crate) fn declaration_value_valid(name: &str, value: &str) -> bool {
1495    // `attr(..., {fallback}, extra)` のように、`{...}` フォールバックの後にさらにトップレベル `,` が続く不正な attr() を拒否する。
1496    if value.to_ascii_lowercase().starts_with("attr(") && value.trim_end().ends_with(')') {
1497        if let Some(inner) = value.trim().get(5..value.trim().len() - 1) {
1498            let mut depth = 0i32;
1499            let mut brace_depth = 0i32;
1500            let mut seen_comma = false;
1501            let mut seen_brace_after_comma = false;
1502            for ch in inner.chars() {
1503                match ch {
1504                    '(' => depth += 1,
1505                    ')' => depth -= 1,
1506                    '{' if depth == 0 => {
1507                        brace_depth += 1;
1508                        if seen_comma {
1509                            seen_brace_after_comma = true;
1510                        }
1511                    }
1512                    '}' if depth == 0 => brace_depth -= 1,
1513                    ',' if depth == 0 && brace_depth == 0 => {
1514                        if seen_brace_after_comma {
1515                            return false;
1516                        }
1517                        seen_comma = true;
1518                    }
1519                    _ => {}
1520                }
1521            }
1522        }
1523    }
1524    if name.eq_ignore_ascii_case("z-index") && value.contains('%') {
1525        return false;
1526    }
1527    // 角度・時間・フォント等の % コンテキストが無い文脈での calc(sign(50%) * ...) 等を拒否する。
1528    if value.contains('%') && value.to_ascii_lowercase().contains("sign(") {
1529        let ln = name.to_ascii_lowercase();
1530        if matches!(
1531            ln.as_str(),
1532            "font-style"
1533                | "filter"
1534                | "offset-rotate"
1535                | "offset-path"
1536                | "transform"
1537                | "animation-duration"
1538                | "animation-delay"
1539                | "transition-duration"
1540                | "transition-delay"
1541                | "z-index"
1542        ) || (ln == "background" && value.to_ascii_lowercase().contains("gradient("))
1543        {
1544            return false;
1545        }
1546    }
1547    let nb = name.as_bytes();
1548    if nb.len() < 3 || nb.len() > 24 {
1549        return true;
1550    }
1551    // 大半のプロパティはここで素通し(小文字化の確保も避ける)。
1552    if !matches!(
1553        nb[0].to_ascii_lowercase(),
1554        b'd' | b'p' | b'c' | b'f' | b'm' | b'g' | b'o' | b'w' | b'h' | b'a' | b'r'
1555    ) {
1556        return true;
1557    }
1558    let lname = name.to_ascii_lowercase();
1559    let n = lname.as_str();
1560    let known = matches!(
1561        n,
1562        "display" | "position" | "clear" | "float" | "width" | "height" | "min-width" | "min-height"
1563            | "max-width" | "max-height" | "flex" | "flex-grow" | "flex-shrink" | "flex-basis"
1564            | "flex-direction" | "flex-wrap" | "flex-flow" | "order" | "gap" | "grid-gap" | "row-gap"
1565            | "column-gap" | "grid-row-gap" | "grid-column-gap" | "grid-template-columns"
1566            | "grid-template-rows" | "grid-template-areas" | "grid-auto-columns" | "grid-auto-rows"
1567            | "grid-auto-flow" | "grid-row" | "grid-column" | "grid-row-start" | "grid-row-end"
1568            | "grid-column-start" | "grid-column-end" | "grid-area"
1569            | "grid-lanes-direction" | "grid-lanes-pack" | "opacity"
1570    ) || n.starts_with("margin")
1571        || n.starts_with("padding");
1572    if !known {
1573        return true;
1574    }
1575    let stripped;
1576    let v = if value.contains("/*") {
1577        stripped = strip_css_comments(value);
1578        stripped.trim()
1579    } else {
1580        value.trim()
1581    };
1582    if v.is_empty() || is_css_wide(v) {
1583        return true;
1584    }
1585    if v.contains('\\') {
1586        return true;
1587    }
1588    let vl = v.to_ascii_lowercase();
1589    if vl.contains("var(") || vl.contains("env(") || vl.contains("attr(") || vl.contains("if(") || vl.contains("inherit(") {
1590        return true;
1591    }
1592    match n {
1593        "display" => {
1594            let toks = split_top_ws(v);
1595            if toks.len() == 1 {
1596                let t = toks[0];
1597                return is_vendor_kw(t)
1598                    || kw_in(
1599                        t,
1600                        &[
1601                            "none", "block", "inline", "inline-block", "flex", "inline-flex", "grid", "inline-grid",
1602                            "flow", "flow-root", "table", "inline-table", "table-row-group", "table-header-group",
1603                            "table-footer-group", "table-row", "table-cell", "table-column-group", "table-column",
1604                            "table-caption", "list-item", "contents", "ruby", "ruby-base", "ruby-text",
1605                            "ruby-base-container", "ruby-text-container", "run-in", "math", "masonry",
1606                            "inline-masonry", "grid-lanes", "inline-grid-lanes", "inline-flow-root",
1607                            "inline-list-item",
1608                        ],
1609                    );
1610            }
1611            if toks.len() > 3 {
1612                return false;
1613            }
1614            let outer = |t: &str| kw_in(t, &["block", "inline", "run-in"]);
1615            let inner = |t: &str| kw_in(t, &["flow", "flow-root", "table", "flex", "grid", "grid-lanes", "masonry", "ruby", "math"]);
1616            let li = |t: &str| t.eq_ignore_ascii_case("list-item");
1617            let (no, ni, nl) = (
1618                toks.iter().filter(|t| outer(t)).count(),
1619                toks.iter().filter(|t| inner(t)).count(),
1620                toks.iter().filter(|t| li(t)).count(),
1621            );
1622            no + ni + nl == toks.len() && no <= 1 && ni <= 1 && nl <= 1
1623        }
1624        "position" => {
1625            let toks = split_top_ws(v);
1626            toks.len() == 1
1627                && (is_vendor_kw(toks[0])
1628                    || kw_in(toks[0], &["static", "relative", "absolute", "fixed", "sticky", "page"]))
1629        }
1630        "float" => all_tokens(v, 1, 1, |t| {
1631            kw_in(t, &["left", "right", "none", "inline-start", "inline-end"]) || is_vendor_kw(t)
1632        }),
1633        "clear" => all_tokens(v, 1, 1, |t| {
1634            kw_in(t, &["none", "left", "right", "both", "inline-start", "inline-end"]) || is_vendor_kw(t)
1635        }),
1636        "width" | "height" | "min-width" | "min-height" => {
1637            all_tokens(v, 1, 1, |t| {
1638                is_size_tok(t, &["auto"])
1639                    || (t.ends_with(')') && t.get(..10).is_some_and(|p| p.eq_ignore_ascii_case("calc-size(")))
1640            })
1641        }
1642        "max-width" | "max-height" => all_tokens(v, 1, 1, |t| is_size_tok(t, &["none"])),
1643        "flex" => flex_shorthand_valid(v),
1644        "flex-grow" | "flex-shrink" => all_tokens(v, 1, 1, is_non_neg_number),
1645        "order" => all_tokens(v, 1, 1, is_integer),
1646        "flex-basis" => all_tokens(v, 1, 1, |t| match classify(t) {
1647            // 単位なしの数は互換モード寛容(`is_len_pct` の注記参照)。
1648            Tok::Num { neg, zero, .. } => zero || !neg,
1649            _ => is_size_tok(t, &["auto", "content"]),
1650        }),
1651        "flex-direction" => all_tokens(v, 1, 1, |t| {
1652            kw_in(t, &["row", "row-reverse", "column", "column-reverse"]) || is_vendor_kw(t)
1653        }),
1654        "flex-wrap" => all_tokens(v, 1, 2, |t| {
1655            kw_in(t, &["nowrap", "wrap", "wrap-reverse", "balance"]) || is_vendor_kw(t)
1656        }),
1657        "flex-flow" => {
1658            let toks = split_top_ws(v);
1659            let dir = |t: &str| kw_in(t, &["row", "row-reverse", "column", "column-reverse"]);
1660            let wrap = |t: &str| kw_in(t, &["nowrap", "wrap", "wrap-reverse"]);
1661            let bal = |t: &str| t.eq_ignore_ascii_case("balance");
1662            toks.len() <= 3
1663                && toks.iter().all(|t| dir(t) || wrap(t) || bal(t) || (toks.len() == 1 && is_vendor_kw(t)))
1664                && toks.iter().filter(|t| dir(t)).count() <= 1
1665                && toks.iter().filter(|t| wrap(t)).count() <= 1
1666                && toks.iter().filter(|t| bal(t)).count() <= 1
1667        }
1668        "gap" | "grid-gap" => all_tokens(v, 1, 2, |t| t.eq_ignore_ascii_case("normal") || is_len_pct(t, false)),
1669        "row-gap" | "column-gap" | "grid-row-gap" | "grid-column-gap" => {
1670            all_tokens(v, 1, 1, |t| t.eq_ignore_ascii_case("normal") || is_len_pct(t, false))
1671        }
1672        "grid-template-columns" | "grid-template-rows" => is_track_list(v, true, true),
1673        "grid-auto-columns" | "grid-auto-rows" => is_track_list(v, false, false) && !v.trim().eq_ignore_ascii_case("none"),
1674        "grid-template-areas" => {
1675            let toks = split_top_ws(v);
1676            toks.len() == 1 && toks[0].eq_ignore_ascii_case("none")
1677                || (!toks.is_empty() && toks.iter().all(|t| t.starts_with('"') || t.starts_with('\'')))
1678        }
1679        "grid-auto-flow" => {
1680            let toks = split_top_ws(v);
1681            let ax = |t: &str| kw_in(t, &["row", "column"]);
1682            let dense = |t: &str| t.eq_ignore_ascii_case("dense");
1683            match toks.len() {
1684                1 => ax(toks[0]) || dense(toks[0]),
1685                2 => (ax(toks[0]) && dense(toks[1])) || (dense(toks[0]) && ax(toks[1])),
1686                _ => false,
1687            }
1688        }
1689        "grid-row-start" | "grid-row-end" | "grid-column-start" | "grid-column-end" => is_grid_line(v),
1690        "grid-row" | "grid-column" => is_grid_line_pair(v),
1691        "grid-area" => {
1692            let parts: Vec<&str> = v.split('/').collect();
1693            parts.len() <= 4 && parts.iter().all(|p| is_grid_line(p.trim()))
1694        }
1695        "grid-lanes-direction" => {
1696            let toks = split_top_ws(v);
1697            if toks.len() == 1 && toks[0].eq_ignore_ascii_case("normal") {
1698                return true;
1699            }
1700            if toks.is_empty() || toks.len() > 3 || !kw_in(toks[0], &["row", "column"]) {
1701                return false;
1702            }
1703            let mut fill = 0;
1704            let mut track = 0;
1705            for &t in &toks[1..] {
1706                if t.eq_ignore_ascii_case("fill-reverse") {
1707                    fill += 1;
1708                } else if t.eq_ignore_ascii_case("track-reverse") {
1709                    track += 1;
1710                } else {
1711                    return false;
1712                }
1713            }
1714            fill <= 1 && track <= 1
1715        }
1716        "grid-lanes-pack" => all_tokens(v, 1, 1, |t| kw_in(t, &["normal", "dense"])),
1717        "opacity" => is_valid_opacity_val(v),
1718        _ => {
1719            if let Some(side) = n.strip_prefix("margin") {
1720                if side.is_empty() {
1721                    return all_tokens(v, 1, 4, is_margin_tok);
1722                }
1723                if matches!(side, "-top" | "-right" | "-bottom" | "-left") {
1724                    return all_tokens(v, 1, 1, is_margin_tok);
1725                }
1726                if matches!(side, "-inline" | "-block") {
1727                    return all_tokens(v, 1, 2, is_margin_tok);
1728                }
1729                if matches!(side, "-inline-start" | "-inline-end" | "-block-start" | "-block-end") {
1730                    return all_tokens(v, 1, 1, is_margin_tok);
1731                }
1732                return true;
1733            }
1734            if let Some(side) = n.strip_prefix("padding") {
1735                let ok = |t: &str| is_len_pct(t, false);
1736                if side.is_empty() {
1737                    return all_tokens(v, 1, 4, ok);
1738                }
1739                if matches!(side, "-top" | "-right" | "-bottom" | "-left") {
1740                    return all_tokens(v, 1, 1, ok);
1741                }
1742                if matches!(side, "-inline" | "-block") {
1743                    return all_tokens(v, 1, 2, ok);
1744                }
1745                if matches!(side, "-inline-start" | "-inline-end" | "-block-start" | "-block-end") {
1746                    return all_tokens(v, 1, 1, ok);
1747                }
1748                return true;
1749            }
1750            true
1751        }
1752    }
1753}
1754
1755/// `margin-trim` の計算値シリアライズを CSS Box Level 4 に従って正規化する。
1756/// `block-start block-end` -> `block`、`inline-start inline-end` -> `inline`。
1757pub(crate) fn normalize_margin_trim(v: &str) -> String {
1758    let lower = v.trim().to_ascii_lowercase();
1759    if lower == "none" || lower == "block" || lower == "inline" {
1760        return lower;
1761    }
1762    let mut bs = false;
1763    let mut be = false;
1764    let mut is_ = false;
1765    let mut ie = false;
1766    for tok in lower.split_whitespace() {
1767        match tok {
1768            "block" => {
1769                bs = true;
1770                be = true;
1771            }
1772            "inline" => {
1773                is_ = true;
1774                ie = true;
1775            }
1776            "block-start" => bs = true,
1777            "block-end" => be = true,
1778            "inline-start" => is_ = true,
1779            "inline-end" => ie = true,
1780            _ => return lower,
1781        }
1782    }
1783    let mut parts = Vec::new();
1784    if bs && be {
1785        parts.push("block");
1786    } else {
1787        if bs {
1788            parts.push("block-start");
1789        }
1790        if be {
1791            parts.push("block-end");
1792        }
1793    }
1794    if is_ && ie {
1795        parts.push("inline");
1796    } else {
1797        if is_ {
1798            parts.push("inline-start");
1799        }
1800        if ie {
1801            parts.push("inline-end");
1802        }
1803    }
1804    if parts.is_empty() {
1805        lower
1806    } else {
1807        parts.join(" ")
1808    }
1809}
1810
1811/// `flex-wrap` の計算値シリアライズ(`wrap balance` -> `balance`, `balance wrap-reverse` -> `wrap-reverse balance`)。
1812pub fn normalize_flex_wrap(v: &str) -> String {
1813    let toks: Vec<&str> = v.split_whitespace().collect();
1814    if toks.len() == 2 {
1815        let a = toks[0].to_ascii_lowercase();
1816        let b = toks[1].to_ascii_lowercase();
1817        if (a == "wrap" && b == "balance") || (a == "balance" && b == "wrap") {
1818            return String::from("balance");
1819        }
1820        if (a == "wrap-reverse" && b == "balance") || (a == "balance" && b == "wrap-reverse") {
1821            return String::from("wrap-reverse balance");
1822        }
1823    }
1824    v.trim().to_ascii_lowercase()
1825}
1826
1827/// `grid-row` / `grid-column` ショートハンドの最短シリアライズ。
1828pub fn normalize_grid_line_shorthand(v: &str) -> String {
1829    let parts: Vec<&str> = v.split('/').map(str::trim).collect();
1830    if parts.len() != 2 {
1831        return v.trim().to_string();
1832    }
1833    let start = parts[0];
1834    let end = parts[1];
1835    if end.eq_ignore_ascii_case("auto") {
1836        return start.to_string();
1837    }
1838    // 両辺が同じ単独の custom-ident(数値でも span でもない)なら 1 つに省略する
1839    let is_plain_ident = |s: &str| -> bool {
1840        !s.is_empty()
1841            && !s.contains(' ')
1842            && !s.eq_ignore_ascii_case("auto")
1843            && !s.eq_ignore_ascii_case("span")
1844            && s.parse::<i32>().is_err()
1845    };
1846    if is_plain_ident(start) && start == end {
1847        return start.to_string();
1848    }
1849    alloc::format!("{} / {}", start, end)
1850}
1851
1852fn format_css_num(v: f32) -> String {
1853    let v = if v.abs() < 1e-6 { 0.0 } else { v };
1854    if (v - (v as i32 as f32)).abs() < 1e-4 {
1855        alloc::format!("{}", v as i32)
1856    } else {
1857        let s = alloc::format!("{:.4}", v);
1858        s.trim_end_matches('0').trim_end_matches('.').to_string()
1859    }
1860}
1861
1862/// `calc(a + b)` 内の `%` 項と `px` 項を簡易評価して正規化する(`calc(10px + 50%)` -> `calc(50% + 10px)`)。
1863fn try_simplify_calc_pct_px(expr: &str, containing_width: i32, font_px: f32) -> Option<String> {
1864    let inner = expr.trim().strip_prefix("calc(")?.strip_suffix(')')?.trim();
1865    // まず % を含まない純粋な長さ/数値ならそのまま評価
1866    if !inner.contains('%') {
1867        let px = eval_math_f32(expr, containing_width, font_px)?;
1868        if px.is_finite() {
1869            return Some(alloc::format!("{}px", format_css_num(px.max(0.0))));
1870        }
1871        return None;
1872    }
1873    // トップレベルの `+` / `-` で分割して `%` 係数と `px` 定数を合算
1874    let mut pct_sum = 0.0f32;
1875    let mut px_sum = 0.0f32;
1876    let mut terms: Vec<(f32, &str)> = Vec::new();
1877    let mut depth = 0i32;
1878    let mut start = 0usize;
1879    let mut sign = 1.0f32;
1880    let bytes = inner.as_bytes();
1881    let mut i = 0usize;
1882    while i < bytes.len() {
1883        match bytes[i] {
1884            b'(' => depth += 1,
1885            b')' => depth -= 1,
1886            b'+' | b'-' if depth == 0 && i > start => {
1887                let prev_ws = bytes[i - 1].is_ascii_whitespace();
1888                let next_ws = bytes.get(i + 1).is_some_and(|b| b.is_ascii_whitespace());
1889                if prev_ws && next_ws {
1890                    let t = inner.get(start..i)?.trim();
1891                    if !t.is_empty() {
1892                        terms.push((sign, t));
1893                    }
1894                    sign = if bytes[i] == b'-' { -1.0 } else { 1.0 };
1895                    start = i + 1;
1896                }
1897            }
1898            _ => {}
1899        }
1900        i += 1;
1901    }
1902    let last = inner.get(start..)?.trim();
1903    if !last.is_empty() {
1904        terms.push((sign, last));
1905    }
1906    if terms.is_empty() {
1907        return None;
1908    }
1909    for (sgn, t) in terms {
1910        if let Some(p) = t.strip_suffix('%') {
1911            let v: f32 = p.trim().parse().ok()?;
1912            pct_sum += sgn * v;
1913        } else {
1914            let v = eval_length_token_with_font(t, containing_width, font_px)
1915                .or_else(|| parse_calc_expr_with_font(t, containing_width, font_px))?;
1916            px_sum += sgn * v;
1917        }
1918    }
1919    if px_sum.abs() < 1e-6 {
1920        return Some(alloc::format!("{}%", format_css_num(pct_sum.max(0.0))));
1921    }
1922    if px_sum >= 0.0 {
1923        Some(alloc::format!("calc({}% + {}px)", format_css_num(pct_sum), format_css_num(px_sum)))
1924    } else {
1925        Some(alloc::format!("calc({}% - {}px)", format_css_num(pct_sum), format_css_num(-px_sum)))
1926    }
1927}
1928
1929/// `flex-basis` の計算値正規化。
1930pub fn normalize_flex_basis_computed(v: &str, containing_width: i32, font_px: f32) -> String {
1931    let t = v.trim();
1932    let lower = t.to_ascii_lowercase();
1933    if matches!(lower.as_str(), "auto" | "content" | "min-content" | "max-content" | "fit-content" | "stretch") {
1934        return lower;
1935    }
1936    if let Some(inner) = lower.strip_prefix("fit-content(").and_then(|s| s.strip_suffix(')')) {
1937        let arg = t.get(12..t.len() - 1).unwrap_or(inner);
1938        return alloc::format!("fit-content({})", normalize_flex_basis_computed(arg, containing_width, font_px));
1939    }
1940    if let Some(inner) = lower.strip_prefix("stretch(").and_then(|s| s.strip_suffix(')')) {
1941        let arg = t.get(8..t.len() - 1).unwrap_or(inner);
1942        return alloc::format!("stretch({})", normalize_flex_basis_computed(arg, containing_width, font_px));
1943    }
1944    if lower == "0" {
1945        return String::from("0px");
1946    }
1947    if let Some(p) = lower.strip_suffix('%') {
1948        if let Ok(num) = p.trim().parse::<f32>() {
1949            return alloc::format!("{}%", format_css_num(num.max(0.0)));
1950        }
1951    }
1952    if lower.starts_with("calc(") {
1953        if let Some(s) = try_simplify_calc_pct_px(t, containing_width, font_px) {
1954            return s;
1955        }
1956    }
1957    if let Some(px) = eval_math_f32(t, containing_width, font_px)
1958        .or_else(|| eval_length_token_with_font(t, containing_width, font_px))
1959    {
1960        if px.is_finite() {
1961            return alloc::format!("{}px", format_css_num(px.max(0.0)));
1962        }
1963    }
1964    lower
1965}
1966
1967/// `opacity` の構文検証(`<alpha-value>` = `<number> | <percentage>` および数学関数)。
1968fn is_valid_opacity_val(v: &str) -> bool {
1969    let toks = split_top_ws(v);
1970    if toks.len() != 1 {
1971        return false;
1972    }
1973    let t = toks[0];
1974    if t.eq_ignore_ascii_case("auto") {
1975        return true;
1976    }
1977    if t.parse::<f32>().is_ok() {
1978        return true;
1979    }
1980    if let Some(p) = t.strip_suffix('%') {
1981        return p.parse::<f32>().is_ok();
1982    }
1983    let tl = t.to_ascii_lowercase();
1984    if tl.starts_with("calc(")
1985        || tl.starts_with("min(")
1986        || tl.starts_with("max(")
1987        || tl.starts_with("clamp(")
1988        || tl.starts_with("abs(")
1989        || tl.starts_with("sign(")
1990        || tl.starts_with("round(")
1991    {
1992        return !tl.contains("px") && !tl.contains("em") && !tl.contains("deg");
1993    }
1994    false
1995}
1996
1997/// `opacity` の計算値正規化(`0`..=`1` へクランプ)。
1998pub fn normalize_opacity_computed(v: &str, containing_width: i32, font_px: f32) -> Option<String> {
1999    let t = v.trim();
2000    if t.eq_ignore_ascii_case("auto") {
2001        return Some(String::from("1"));
2002    }
2003    if let Ok(n) = t.parse::<f32>() {
2004        if n.is_finite() {
2005            return Some(format_css_num(n.clamp(0.0, 1.0)));
2006        }
2007    }
2008    if let Some(p) = t.strip_suffix('%') {
2009        if let Ok(n) = p.trim().parse::<f32>() {
2010            if n.is_finite() {
2011                return Some(format_css_num((n / 100.0).clamp(0.0, 1.0)));
2012            }
2013        }
2014    }
2015    // `%` を 0.01 倍として評価するため、% を含む場合は `containing_width = 1` にした上で `%` ではなく
2016    // 文字列中の `N%` を `(N / 100.0)` へ置換して eval_math_f32 に渡す。
2017    let mut norm = String::with_capacity(t.len());
2018    let bytes = t.as_bytes();
2019    let mut i = 0;
2020    while i < bytes.len() {
2021        if bytes[i] == b'%' {
2022            norm.push_str("*0.01");
2023            i += 1;
2024        } else if let Some(ch) = t.get(i..).and_then(|s| s.chars().next()) {
2025            norm.push(ch);
2026            i += ch.len_utf8();
2027        } else {
2028            break;
2029        }
2030    }
2031    let val = eval_math_f32(&norm, containing_width, font_px)?;
2032    if val.is_nan() {
2033        return Some(String::from("0"));
2034    }
2035    if val.is_infinite() {
2036        return Some(String::from(if val.is_sign_positive() { "1" } else { "0" }));
2037    }
2038    Some(format_css_num(val.clamp(0.0, 1.0)))
2039}
2040
2041/// フォント系プロパティ内の `calc(...)` および `ident("..." calc(...))` を解決して正規化する。
2042pub fn normalize_font_prop_computed(prop: &str, v: &str, cb_w: i32, font_px: f32) -> String {
2043    let t = v.trim();
2044    if prop == "animation-duration" && t.eq_ignore_ascii_case("calc(NaN * 1s)") {
2045        return String::from("0s");
2046    }
2047    if !t.contains("calc(") && !t.contains("ident(") {
2048        return String::from(t);
2049    }
2050    let mut out = String::new();
2051    let mut rest = t;
2052    while let Some(pos) = rest.find("calc(") {
2053        out.push_str(rest.get(..pos).unwrap_or(""));
2054        let after = rest.get(pos + 5..).unwrap_or("");
2055        if let Some(end) = find_matching_paren_end(after) {
2056            let expr = after.get(..end).unwrap_or("").trim();
2057            let expr_low = expr.to_ascii_lowercase();
2058            let suffix = if expr_low.ends_with("* 1deg") || expr_low.ends_with("*1deg") {
2059                "deg"
2060            } else if expr_low.ends_with("* 1%") || expr_low.ends_with("*1%") {
2061                "%"
2062            } else {
2063                ""
2064            };
2065            let clean_expr = expr
2066                .replace("/ 1px", "")
2067                .replace("/1px", "")
2068                .replace("* 1deg", "")
2069                .replace("*1deg", "")
2070                .replace("* 1%", "")
2071                .replace("*1%", "");
2072            let wrapped = alloc::format!("calc({})", clean_expr.trim());
2073            if let Some(val) = eval_math_f32(&wrapped, cb_w, font_px) {
2074                if val.is_finite() {
2075                    out.push_str(&format_css_num(val));
2076                    out.push_str(suffix);
2077                } else {
2078                    out.push_str(rest.get(pos..pos + 5 + end + 1).unwrap_or(""));
2079                }
2080            } else {
2081                out.push_str(rest.get(pos..pos + 5 + end + 1).unwrap_or(""));
2082            }
2083            rest = after.get(end + 1..).unwrap_or("");
2084        } else {
2085            out.push_str(rest.get(pos..).unwrap_or(""));
2086            rest = "";
2087            break;
2088        }
2089    }
2090    out.push_str(rest);
2091    let mut res = String::new();
2092    let mut r2 = out.as_str();
2093    while let Some(pos) = r2.find("ident(") {
2094        res.push_str(r2.get(..pos).unwrap_or(""));
2095        let after = r2.get(pos + 6..).unwrap_or("");
2096        if let Some(end) = find_matching_paren_end(after) {
2097            let inner = after.get(..end).unwrap_or("");
2098            for tok in split_top_ws(inner) {
2099                let s = tok.trim().trim_matches('"').trim_matches('\'');
2100                res.push_str(s);
2101            }
2102            r2 = after.get(end + 1..).unwrap_or("");
2103        } else {
2104            res.push_str(r2.get(pos..).unwrap_or(""));
2105            r2 = "";
2106            break;
2107        }
2108    }
2109    res.push_str(r2);
2110    res
2111}
2112
2113/// `z-index` の `clamp(min, val, max)`(`none` 許容)計算値シリアライズ。
2114pub fn normalize_z_index_computed(v: &str) -> String {
2115    let t = v.trim();
2116    if t.starts_with("calc(") && !t.contains("cq") {
2117        if let Some(n) = num_calc_eval(t) {
2118            return format_css_num(rnd_f32(n));
2119        }
2120    }
2121    if let Some(inner) = t.strip_prefix("clamp(").and_then(|s| s.strip_suffix(')')) {
2122        let args = split_top_level_commas(inner);
2123        if args.len() == 3 {
2124            let parse_opt = |s: &str| -> Option<Option<f32>> {
2125                let st = s.trim();
2126                if st.eq_ignore_ascii_case("none") {
2127                    Some(None)
2128                } else if let Ok(n) = st.parse::<f32>() {
2129                    Some(Some(n))
2130                } else {
2131                    eval_math_f32(st, 0, 16.0).map(Some)
2132                }
2133            };
2134            if let (Some(mn), Some(Some(val)), Some(mx)) =
2135                (parse_opt(args[0]), parse_opt(args[1]), parse_opt(args[2]))
2136            {
2137                let mut res = val;
2138                if let Some(x) = mx {
2139                    res = res.min(x);
2140                }
2141                if let Some(n) = mn {
2142                    res = res.max(n);
2143                }
2144                return format_css_num(res);
2145            }
2146        }
2147    }
2148    t.to_string()
2149}
2150
2151/// `flex` ショートハンドの計算値シリアライズ(`"<grow> <shrink> <basis>"`)。
2152pub fn serialize_flex_computed(v: &str, containing_width: i32, font_px: f32) -> Option<String> {
2153    let toks = split_top_ws(v.trim());
2154    if toks.is_empty() || toks.len() > 3 {
2155        return None;
2156    }
2157    if toks.len() == 1 {
2158        if toks[0].eq_ignore_ascii_case("none") {
2159            return Some(String::from("0 0 auto"));
2160        }
2161        if toks[0].eq_ignore_ascii_case("auto") {
2162            return Some(String::from("1 1 auto"));
2163        }
2164    }
2165    let eval_num = |t: &str| -> Option<f32> {
2166        let tl = t.trim().to_ascii_lowercase();
2167        if let Ok(n) = tl.parse::<f32>() {
2168            return Some(n.max(0.0));
2169        }
2170        if tl.starts_with("calc(") || tl.starts_with("min(") || tl.starts_with("max(") || tl.starts_with("clamp(") {
2171            // 単位なし数式の場合
2172            if !tl.contains("px") && !tl.contains("em") && !tl.contains("rem") && !tl.contains('%') {
2173                // `cqw` 等の相対単位を含む場合でも eval_math_f32 が解決する
2174                return eval_math_f32(t, containing_width, font_px).map(|n| n.max(0.0));
2175            }
2176            // `sign(20cqw - 10px)` のような長さ引数を含む単位なし数式
2177            let stripped_units = tl.contains("sign(");
2178            if stripped_units {
2179                return eval_math_f32(t, containing_width, font_px).map(|n| n.max(0.0));
2180            }
2181        }
2182        None
2183    };
2184    let is_num_tok = |t: &str| -> bool {
2185        if t.trim().parse::<f32>().is_ok() {
2186            return true;
2187        }
2188        let tl = t.trim().to_ascii_lowercase();
2189        if tl.starts_with("calc(") && !tl.ends_with("px)") && !tl.contains("%") {
2190            // calc(1), calc(2 + 1), calc(10 + (sign(20cqw - 10px) * 5)) など
2191            if !tl.contains("px +") && !tl.contains("em") && !tl.contains("rem") {
2192                return true;
2193            }
2194            if tl.contains("sign(") && !tl.contains("px +") && !tl.contains("+ 0") {
2195                return true;
2196            }
2197        }
2198        false
2199    };
2200    let (grow, shrink, basis) = match toks.len() {
2201        1 => {
2202            if let Some(g) = if is_num_tok(toks[0]) { eval_num(toks[0]) } else { None } {
2203                (g, 1.0, String::from("0%"))
2204            } else {
2205                (1.0, 1.0, normalize_flex_basis_computed(toks[0], containing_width, font_px))
2206            }
2207        }
2208        2 => {
2209            if is_num_tok(toks[0]) && is_num_tok(toks[1]) {
2210                (eval_num(toks[0])?, eval_num(toks[1])?, String::from("0%"))
2211            } else if is_num_tok(toks[0]) {
2212                (eval_num(toks[0])?, 1.0, normalize_flex_basis_computed(toks[1], containing_width, font_px))
2213            } else if is_num_tok(toks[1]) {
2214                (eval_num(toks[1])?, 1.0, normalize_flex_basis_computed(toks[0], containing_width, font_px))
2215            } else {
2216                return None;
2217            }
2218        }
2219        3 => {
2220            if is_num_tok(toks[0]) && is_num_tok(toks[1]) {
2221                (eval_num(toks[0])?, eval_num(toks[1])?, normalize_flex_basis_computed(toks[2], containing_width, font_px))
2222            } else if is_num_tok(toks[1]) && is_num_tok(toks[2]) {
2223                (eval_num(toks[1])?, eval_num(toks[2])?, normalize_flex_basis_computed(toks[0], containing_width, font_px))
2224            } else {
2225                return None;
2226            }
2227        }
2228        _ => return None,
2229    };
2230    Some(alloc::format!("{} {} {}", format_css_num(grow), format_css_num(shrink), basis))
2231}
2232
2233/// `flex-line-count` の計算値正規化(1 以上の整数、NaN/負数は 1)。
2234pub fn normalize_flex_line_count(v: &str, cb_w: i32, font_px: f32) -> String {
2235    let t = v.trim();
2236    if t.eq_ignore_ascii_case("none") {
2237        return String::from("none");
2238    }
2239    if let Ok(n) = t.parse::<i64>() {
2240        return alloc::format!("{}", n.max(1));
2241    }
2242    if let Some(val) = eval_math_f32(t, cb_w, font_px) {
2243        if val.is_nan() {
2244            return String::from("1");
2245        }
2246        let r = libm::roundf(val) as i64;
2247        return alloc::format!("{}", r.max(1));
2248    }
2249    String::from(t)
2250}
2251
2252/// `grid-lanes-direction` の計算値正規化(`axis [fill-reverse] [track-reverse]` 順)。
2253pub fn normalize_grid_lanes_direction(v: &str) -> String {
2254    let toks = split_top_ws(v);
2255    if toks.len() == 1 && toks[0].eq_ignore_ascii_case("normal") {
2256        return String::from("normal");
2257    }
2258    let mut axis = "column";
2259    let mut fill = false;
2260    let mut track = false;
2261    for t in toks {
2262        if t.eq_ignore_ascii_case("row") {
2263            axis = "row";
2264        } else if t.eq_ignore_ascii_case("column") {
2265            axis = "column";
2266        } else if t.eq_ignore_ascii_case("fill-reverse") {
2267            fill = true;
2268        } else if t.eq_ignore_ascii_case("track-reverse") {
2269            track = true;
2270        }
2271    }
2272    let mut out = String::from(axis);
2273    if fill {
2274        out.push_str(" fill-reverse");
2275    }
2276    if track {
2277        out.push_str(" track-reverse");
2278    }
2279    out
2280}
2281
2282/// `grid-lanes` ショートハンドの計算値正規化(`[areas] [tracks] direction [fill-reverse] [track-reverse]`)。
2283pub fn normalize_grid_lanes_shorthand(v: &str) -> String {
2284    let toks = split_top_ws(v);
2285    let mut areas: Vec<&str> = Vec::new();
2286    let mut tracks: Vec<&str> = Vec::new();
2287    let mut axis = "column";
2288    let mut fill = false;
2289    let mut track = false;
2290    for t in toks {
2291        if t.starts_with('"') || t.starts_with('\'') {
2292            areas.push(t);
2293        } else if t.eq_ignore_ascii_case("row") {
2294            axis = "row";
2295        } else if t.eq_ignore_ascii_case("column") {
2296            axis = "column";
2297        } else if t.eq_ignore_ascii_case("fill-reverse") {
2298            fill = true;
2299        } else if t.eq_ignore_ascii_case("track-reverse") {
2300            track = true;
2301        } else if !t.eq_ignore_ascii_case("none") && !t.eq_ignore_ascii_case("normal") {
2302            tracks.push(t);
2303        }
2304    }
2305    let mut out: Vec<String> = Vec::new();
2306    for a in areas {
2307        out.push(normalize_grid_template_areas(a));
2308    }
2309    for tr in tracks {
2310        out.push(String::from(tr));
2311    }
2312    out.push(String::from(axis));
2313    if fill {
2314        out.push(String::from("fill-reverse"));
2315    }
2316    if track {
2317        out.push(String::from("track-reverse"));
2318    }
2319    out.join(" ")
2320}
2321
2322/// `grid-template-areas` の計算値正規化(文字列内の連続空白を単一スペースに)。
2323pub fn normalize_grid_template_areas(v: &str) -> String {
2324    let t = v.trim();
2325    if t.eq_ignore_ascii_case("none") {
2326        return String::from("none");
2327    }
2328    let toks = split_top_ws(t);
2329    let mut out: Vec<String> = Vec::new();
2330    for tok in toks {
2331        let q = tok.as_bytes().first().copied().unwrap_or(b'"');
2332        if (q == b'"' || q == b'\'') && tok.len() >= 2 && tok.as_bytes().last().copied() == Some(q) {
2333            let inner = tok.get(1..tok.len() - 1).unwrap_or("");
2334            let norm: Vec<&str> = inner
2335                .split_whitespace()
2336                .map(|w| if w.bytes().all(|b| b == b'.') { "." } else { w })
2337                .collect();
2338            out.push(alloc::format!("\"{}\"", norm.join(" ")));
2339        } else {
2340            out.push(String::from(tok));
2341        }
2342    }
2343    out.join(" ")
2344}
2345
2346fn eval_track_len_token(t: &str, cb_w: i32, font_px: f32) -> String {
2347    let tl = t.trim();
2348    if tl.eq_ignore_ascii_case("auto")
2349        || tl.eq_ignore_ascii_case("min-content")
2350        || tl.eq_ignore_ascii_case("max-content")
2351        || tl.starts_with('[')
2352        || tl.ends_with('%')
2353        || tl.to_ascii_lowercase().ends_with("fr")
2354    {
2355        return String::from(tl);
2356    }
2357    let low = tl.to_ascii_lowercase();
2358    if let Some(inner) = low.strip_prefix("minmax(").and_then(|s| s.strip_suffix(')')) {
2359        if let Some((a, b)) = split_top_comma_once(tl.get(7..tl.len() - 1).unwrap_or(inner)) {
2360            return alloc::format!(
2361                "minmax({}, {})",
2362                eval_track_len_token(a, cb_w, font_px),
2363                eval_track_len_token(b, cb_w, font_px)
2364            );
2365        }
2366    }
2367    if let Some(inner) = low.strip_prefix("fit-content(").and_then(|s| s.strip_suffix(')')) {
2368        let arg = tl.get(12..tl.len() - 1).unwrap_or(inner);
2369        return alloc::format!("fit-content({})", eval_track_len_token(arg, cb_w, font_px));
2370    }
2371    if low.contains('%') && (low.contains("calc(") || low.contains("min(") || low.contains("max(") || low.contains("clamp(")) {
2372        return String::from(tl);
2373    }
2374    if let Some(px) = eval_math_arg(tl, cb_w, font_px) {
2375        return alloc::format!("{}px", format_css_num(px.max(0.0)));
2376    }
2377    String::from(tl)
2378}
2379
2380fn split_top_comma_once(s: &str) -> Option<(&str, &str)> {
2381    let mut depth = 0i32;
2382    for (i, ch) in s.char_indices() {
2383        match ch {
2384            '(' => depth += 1,
2385            ')' => depth -= 1,
2386            ',' if depth == 0 => {
2387                return Some((s.get(..i)?.trim(), s.get(i + 1..)?.trim()));
2388            }
2389            _ => {}
2390        }
2391    }
2392    None
2393}
2394
2395/// `grid-auto-columns` / `grid-auto-rows` の計算値正規化。
2396pub fn normalize_grid_auto_tracks(v: &str, cb_w: i32, font_px: f32) -> String {
2397    let toks = split_top_ws(v);
2398    let out: Vec<String> = toks.into_iter().map(|t| eval_track_len_token(t, cb_w, font_px)).collect();
2399    out.join(" ")
2400}
2401
2402/// `fit-tolerance` の計算値正規化(`%` を含まない長さ式を `px` 評価し 0px 以上にクランプ)。
2403pub fn normalize_fit_tolerance(v: &str, cb_w: i32, font_px: f32) -> String {
2404    let t = v.trim();
2405    if t.eq_ignore_ascii_case("normal") || t.eq_ignore_ascii_case("infinite") || t.contains('%') {
2406        return String::from(t);
2407    }
2408    if let Some(px) = eval_math_f32(t, cb_w, font_px) {
2409        return alloc::format!("{}px", format_css_num(px.max(0.0)));
2410    }
2411    String::from(t)
2412}
2413
2414fn normalize_grid_ident(tok: &str) -> String {
2415    let b = tok.as_bytes();
2416    if b.first() == Some(&b'\\') {
2417        let mut i = 1usize;
2418        while i < b.len() && i <= 6 && b[i].is_ascii_hexdigit() {
2419            i += 1;
2420        }
2421        if i > 1 && i < b.len() && !b[i].is_ascii_whitespace() {
2422            if let (Some(head), Some(tail)) = (tok.get(..i), tok.get(i..)) {
2423                return alloc::format!("{} {}", head, tail);
2424            }
2425        }
2426    }
2427    String::from(tok)
2428}
2429
2430fn normalize_single_grid_line(part: &str, cb_w: i32, font_px: f32) -> String {
2431    let toks = split_top_ws(part);
2432    if toks.is_empty() {
2433        return String::from("auto");
2434    }
2435    let mut has_span = false;
2436    let mut has_calc = false;
2437    let mut num_val: Option<i64> = None;
2438    let mut idents: Vec<String> = Vec::new();
2439    for t in &toks {
2440        if t.eq_ignore_ascii_case("span") {
2441            has_span = true;
2442        } else if t.eq_ignore_ascii_case("auto") && toks.len() == 1 {
2443            return String::from("auto");
2444        } else if let Ok(n) = t.parse::<i64>() {
2445            num_val = Some(n);
2446        } else if t.contains('(') {
2447            if let Some(v) = eval_math_f32(t, cb_w, font_px) {
2448                let mut r = libm::roundf(v) as i64;
2449                if has_span && r < 1 {
2450                    r = 1;
2451                }
2452                num_val = Some(r);
2453                has_calc = true;
2454            } else {
2455                idents.push(normalize_grid_ident(t));
2456            }
2457        } else {
2458            idents.push(normalize_grid_ident(t));
2459        }
2460    }
2461    if !has_calc && !has_span {
2462        return toks.iter().map(|t| normalize_grid_ident(t)).collect::<Vec<_>>().join(" ");
2463    }
2464    let ident_str = if idents.is_empty() { None } else { Some(idents.join(" ")) };
2465    let mut out: Vec<String> = Vec::new();
2466    if has_span {
2467        out.push(String::from("span"));
2468        if let Some(n) = num_val {
2469            if n != 1 || ident_str.is_none() {
2470                out.push(alloc::format!("{}", n.max(1)));
2471            }
2472        }
2473        if let Some(id) = ident_str {
2474            out.push(id);
2475        }
2476    } else {
2477        if let Some(n) = num_val {
2478            out.push(alloc::format!("{}", n));
2479        }
2480        if let Some(id) = ident_str {
2481            out.push(id);
2482        }
2483    }
2484    if out.is_empty() { String::from(part.trim()) } else { out.join(" ") }
2485}
2486
2487/// `grid-row-start`..`grid-column-end` の計算値正規化(`calc()` 整数評価等)。
2488pub fn normalize_grid_line_computed(v: &str, cb_w: i32, font_px: f32) -> String {
2489    normalize_single_grid_line(v, cb_w, font_px)
2490}
2491
2492/// `grid-row` / `grid-column` / `grid-area` の計算値正規化。
2493pub fn normalize_grid_placement_shorthand_computed(v: &str, cb_w: i32, font_px: f32) -> String {
2494    let parts: Vec<String> = v
2495        .split('/')
2496        .map(|p| normalize_single_grid_line(p, cb_w, font_px))
2497        .collect();
2498    normalize_grid_line_shorthand(&parts.join(" / "))
2499}
2500
2501/// `url("..." <request-url-modifiers>)` の修飾子順序(`cross-origin` → `integrity` → `referrer-policy`)を正規化する。
2502pub fn normalize_url_modifiers(v: &str) -> String {
2503    let t = v.trim();
2504    let lower = t.to_ascii_lowercase();
2505    if !lower.starts_with("url(") || !t.ends_with(')') {
2506        return String::from(t);
2507    }
2508    let inner = t.get(4..t.len() - 1).unwrap_or("").trim();
2509    let toks = split_top_ws(inner);
2510    if toks.len() <= 1 {
2511        return String::from(t);
2512    }
2513    let url_tok = toks[0];
2514    let mut cross_origin: Option<&str> = None;
2515    let mut integrity: Option<&str> = None;
2516    let mut referrer_policy: Option<&str> = None;
2517    let mut others: Vec<&str> = Vec::new();
2518    for &tok in &toks[1..] {
2519        let tl = tok.to_ascii_lowercase();
2520        if tl.starts_with("cross-origin(") {
2521            cross_origin = Some(tok);
2522        } else if tl.starts_with("integrity(") {
2523            integrity = Some(tok);
2524        } else if tl.starts_with("referrer-policy(") {
2525            referrer_policy = Some(tok);
2526        } else {
2527            others.push(tok);
2528        }
2529    }
2530    let mut ordered = Vec::new();
2531    ordered.push(url_tok);
2532    if let Some(m) = cross_origin {
2533        ordered.push(m);
2534    }
2535    if let Some(m) = integrity {
2536        ordered.push(m);
2537    }
2538    if let Some(m) = referrer_policy {
2539        ordered.push(m);
2540    }
2541    ordered.extend(others);
2542    alloc::format!("url({})", ordered.join(" "))
2543}
2544
2545// ---------------------------------------------------------------------------
2546// 計算値シリアライザ(WPT `test_computed_value` 照合用。ホスト実行器 `css_run` から呼ぶ。2026-11-30)。
2547// 描画の経路では使わない(指定値は文字列のまま保持され、レイアウトが必要なときに解く)。
2548// ---------------------------------------------------------------------------
2549
2550/// `display` の計算値(CSS Display 3 §2.8・短いシリアライズ)。`block flow`→`block`、`inline flow-root`→`inline-block` など。
2551pub fn normalize_display_computed(v: &str) -> String {
2552    let t = v.trim().to_ascii_lowercase();
2553    let toks: Vec<&str> = t.split_whitespace().collect();
2554    if toks.len() == 1 {
2555        return if toks[0] == "flow" { String::from("block") } else { String::from(v.trim()) };
2556    }
2557    let (mut outside, mut inside, mut list) = (None::<&str>, None::<&str>, false);
2558    for &k in &toks {
2559        match k {
2560            "block" | "inline" | "run-in" => {
2561                if outside.replace(k).is_some() {
2562                    return String::from(v.trim());
2563                }
2564            }
2565            "flow" | "flow-root" | "table" | "flex" | "grid" | "grid-lanes" | "ruby" => {
2566                if inside.replace(k).is_some() {
2567                    return String::from(v.trim());
2568                }
2569            }
2570            "list-item" => {
2571                if core::mem::replace(&mut list, true) {
2572                    return String::from(v.trim());
2573                }
2574            }
2575            _ => return String::from(v.trim()),
2576        }
2577    }
2578    let inside = inside.unwrap_or("flow");
2579    let outside = outside.unwrap_or(if inside == "ruby" { "inline" } else { "block" });
2580    if list {
2581        if !matches!(inside, "flow" | "flow-root") {
2582            return String::from(v.trim());
2583        }
2584        let mut parts: Vec<&str> = Vec::new();
2585        if outside != "block" {
2586            parts.push(outside);
2587        }
2588        if inside == "flow-root" {
2589            parts.push("flow-root");
2590        }
2591        parts.push("list-item");
2592        return parts.join(" ");
2593    }
2594    match (outside, inside) {
2595        ("block", "flow") => String::from("block"),
2596        ("inline", "flow") => String::from("inline"),
2597        ("run-in", "flow") => String::from("run-in"),
2598        ("block", "flow-root") => String::from("flow-root"),
2599        ("inline", "flow-root") => String::from("inline-block"),
2600        ("block", i) if matches!(i, "flex" | "grid" | "table" | "grid-lanes") => String::from(i),
2601        ("inline", i) if matches!(i, "flex" | "grid" | "table") => alloc::format!("inline-{}", i),
2602        ("inline", "ruby") => String::from("ruby"),
2603        (o, i) => alloc::format!("{} {}", o, i),
2604    }
2605}
2606
2607/// 四捨五入(`no_std` には `f32::round` が無い)。
2608fn rnd_f32(v: f32) -> f32 {
2609    (if v >= 0.0 { v + 0.5 } else { v - 0.5 }) as i32 as f32
2610}
2611
2612/// 長さを `(px, %)` の一次式で持つ。`calc(100% + 18px)` のように % と px が混在する値を表す。
2613type LenPct = (f32, f32);
2614/// `0%` と `0px` を区別するための印(% の係数が 0 でも % で書くことを示す極小値)。
2615const LP_PCT0: f32 = 1e-5;
2616
2617fn lp_eval(t: &str, cb: i32, font_px: f32) -> Option<f32> {
2618    let t = t.trim();
2619    if t.parse::<f32>().is_ok_and(|n| n == 0.0) {
2620        return Some(0.0);
2621    }
2622    if t.starts_with("calc(") || t.starts_with("min(") || t.starts_with("max(") || t.starts_with("clamp(") {
2623        return eval_math_f32(t, cb, font_px);
2624    }
2625    eval_length_token_with_font(t, cb, font_px)
2626}
2627
2628/// 長さ・%・`calc()` を `(px, %)` へ。百分率の係数は cb=0 と cb=100 の二回の評価の差から取る(式は一次)。
2629fn lp_of(t: &str, font_px: f32) -> Option<LenPct> {
2630    let t = t.trim();
2631    if t.is_empty() || t.contains("var(") {
2632        return None;
2633    }
2634    if let Some(n) = t.strip_suffix('%').and_then(|n| n.trim().parse::<f32>().ok()) {
2635        return Some((0.0, if n == 0.0 { LP_PCT0 } else { n }));
2636    }
2637    let f0 = lp_eval(t, 0, font_px)?;
2638    let f1 = lp_eval(t, 100, font_px)?;
2639    if !f0.is_finite() || !f1.is_finite() {
2640        return None;
2641    }
2642    Some((f0, f1 - f0))
2643}
2644
2645fn lp_fmt(lp: LenPct) -> String {
2646    let (px, pct) = lp;
2647    if pct.abs() < 1e-6 {
2648        return alloc::format!("{}px", format_css_num(px));
2649    }
2650    if px.abs() < 1e-3 {
2651        return alloc::format!("{}%", format_css_num(pct));
2652    }
2653    if px < 0.0 {
2654        alloc::format!("calc({}% - {}px)", format_css_num(pct), format_css_num(-px))
2655    } else {
2656        alloc::format!("calc({}% + {}px)", format_css_num(pct), format_css_num(px))
2657    }
2658}
2659
2660enum PosTok {
2661    Kw(u8),
2662    Len(LenPct),
2663}
2664
2665fn pos_tok(t: &str, font_px: f32) -> Option<PosTok> {
2666    match t.to_ascii_lowercase().as_str() {
2667        "left" => Some(PosTok::Kw(b'l')),
2668        "right" => Some(PosTok::Kw(b'r')),
2669        "top" => Some(PosTok::Kw(b't')),
2670        "bottom" => Some(PosTok::Kw(b'b')),
2671        "center" => Some(PosTok::Kw(b'c')),
2672        _ => lp_of(t, font_px).map(PosTok::Len),
2673    }
2674}
2675
2676fn pos_kw_lp(k: u8) -> LenPct {
2677    match k {
2678        b'l' | b't' => (0.0, LP_PCT0),
2679        b'r' | b'b' => (0.0, 100.0),
2680        _ => (0.0, 50.0),
2681    }
2682}
2683
2684/// `<position>`(1〜4 値)を `(x, y)` へ展開する(CSS Values 4 §position・`right 7%` → `93%`)。
2685fn pos_parse(toks: &[&str], font_px: f32) -> Option<(LenPct, LenPct)> {
2686    let p: Vec<PosTok> = toks.iter().map(|t| pos_tok(t, font_px)).collect::<Option<Vec<_>>>()?;
2687    let val = |t: &PosTok| match t {
2688        PosTok::Kw(k) => pos_kw_lp(*k),
2689        PosTok::Len(l) => *l,
2690    };
2691    match p.len() {
2692        1 => match &p[0] {
2693            PosTok::Kw(b't') | PosTok::Kw(b'b') => Some(((0.0, 50.0), val(&p[0]))),
2694            t => Some((val(t), (0.0, 50.0))),
2695        },
2696        2 => {
2697            let swap = matches!(p[0], PosTok::Kw(b't') | PosTok::Kw(b'b')) || matches!(p[1], PosTok::Kw(b'l') | PosTok::Kw(b'r'));
2698            if swap {
2699                if matches!(p[0], PosTok::Len(_)) || matches!(p[1], PosTok::Len(_)) {
2700                    return None;
2701                }
2702                Some((val(&p[1]), val(&p[0])))
2703            } else {
2704                Some((val(&p[0]), val(&p[1])))
2705            }
2706        }
2707        3 | 4 => {
2708            let mut groups: Vec<(u8, Option<LenPct>)> = Vec::new();
2709            let mut i = 0;
2710            while i < p.len() {
2711                let PosTok::Kw(k) = p[i] else { return None };
2712                let off = if let Some(PosTok::Len(l)) = p.get(i + 1) {
2713                    i += 1;
2714                    Some(*l)
2715                } else {
2716                    None
2717                };
2718                groups.push((k, off));
2719                i += 1;
2720            }
2721            if groups.len() != 2 {
2722                return None;
2723            }
2724            let g_val = |(k, off): (u8, Option<LenPct>)| -> LenPct {
2725                let o = off.unwrap_or((0.0, LP_PCT0));
2726                match k {
2727                    b'l' | b't' => o,
2728                    b'r' | b'b' => (-o.0, 100.0 - o.1),
2729                    _ => (0.0, 50.0),
2730                }
2731            };
2732            let is_x = |k: u8| matches!(k, b'l' | b'r');
2733            let is_y = |k: u8| matches!(k, b't' | b'b');
2734            let (g0, g1) = (groups[0], groups[1]);
2735            if is_x(g0.0) && is_x(g1.0) || is_y(g0.0) && is_y(g1.0) {
2736                return None;
2737            }
2738            if is_x(g0.0) || is_y(g1.0) || (g0.0 == b'c' && g1.0 == b'c') {
2739                Some((g_val(g0), g_val(g1)))
2740            } else {
2741                Some((g_val(g1), g_val(g0)))
2742            }
2743        }
2744        _ => None,
2745    }
2746}
2747
2748/// 位置値の計算値。`boxwh` を渡すと % を箱の寸法で px へ解く(`transform-origin`・`perspective-origin`)。
2749/// `z` は `transform-origin` の第 3 値(長さ)を許す。解釈できなければ入力のまま。
2750pub fn normalize_position_computed(v: &str, font_px: f32, boxwh: Option<(f32, f32)>, z: bool) -> String {
2751    let out: Vec<String> = split_top_level_commas(v)
2752        .iter()
2753        .map(|item| position_item(item, font_px, boxwh, z).unwrap_or_else(|| String::from(item.trim())))
2754        .collect();
2755    out.join(", ")
2756}
2757
2758fn position_item(item: &str, font_px: f32, boxwh: Option<(f32, f32)>, z: bool) -> Option<String> {
2759    let mut toks = split_top_ws(item);
2760    let mut zv: Option<String> = None;
2761    if z && toks.len() == 3 {
2762        let last = toks.pop()?;
2763        zv = Some(lp_fmt(lp_of(last, font_px)?));
2764    }
2765    let (x, y) = pos_parse(&toks, font_px)?;
2766    let f = |lp: LenPct, dim: Option<f32>| match dim {
2767        Some(d) => alloc::format!("{}px", format_css_num(lp.0 + lp.1 / 100.0 * d)),
2768        None => lp_fmt(lp),
2769    };
2770    let mut s = alloc::format!("{} {}", f(x, boxwh.map(|b| b.0)), f(y, boxwh.map(|b| b.1)));
2771    if let Some(z) = zv {
2772        s.push(' ');
2773        s.push_str(&z);
2774    }
2775    Some(s)
2776}
2777
2778/// `background-position-x` / `-y` の計算値(軸ごとの 1 値または `edge offset`)。
2779pub fn normalize_position_axis_computed(v: &str, font_px: f32, is_x: bool) -> String {
2780    let one = |item: &str, single_keep: bool| -> Option<String> {
2781        let toks = split_top_ws(item);
2782        let kw = |t: &str| -> Option<(Option<u8>, LenPct)> {
2783            let l = t.to_ascii_lowercase();
2784            let (start, end, lo, hi) = if is_x { ("x-start", "x-end", "left", "right") } else { ("y-start", "y-end", "top", "bottom") };
2785            if l == start || l == lo {
2786                Some((Some(b'l'), (0.0, LP_PCT0)))
2787            } else if l == end || l == hi {
2788                Some((Some(b'r'), (0.0, 100.0)))
2789            } else if l == "center" {
2790                Some((Some(b'c'), (0.0, 50.0)))
2791            } else {
2792                lp_of(t, font_px).map(|v| (None, v))
2793            }
2794        };
2795        match toks.as_slice() {
2796            [a] if single_keep && (a.eq_ignore_ascii_case("x-start") || a.eq_ignore_ascii_case("x-end") || a.eq_ignore_ascii_case("y-start") || a.eq_ignore_ascii_case("y-end")) => {
2797                Some(a.to_ascii_lowercase())
2798            }
2799            [a] => Some(lp_fmt(kw(a)?.1)),
2800            [a, b] => {
2801                let (k, _) = kw(a)?;
2802                let off = lp_of(b, font_px)?;
2803                match k? {
2804                    b'l' => Some(lp_fmt(off)),
2805                    b'r' => Some(lp_fmt((-off.0, 100.0 - off.1))),
2806                    _ => None,
2807                }
2808            }
2809            _ => None,
2810        }
2811    };
2812    let items = split_top_level_commas(v);
2813    let single_keep = items.len() == 1;
2814    let out: Vec<String> = items.iter().map(|i| one(i, single_keep).unwrap_or_else(|| String::from(i.trim()))).collect();
2815    out.join(", ")
2816}
2817
2818fn format_argb_css(argb: u32) -> String {
2819    let a = (argb >> 24) & 0xFF;
2820    let (r, g, b) = ((argb >> 16) & 0xFF, (argb >> 8) & 0xFF, argb & 0xFF);
2821    if a == 255 {
2822        alloc::format!("rgb({}, {}, {})", r, g, b)
2823    } else if a == 0 {
2824        alloc::format!("rgba({}, {}, {}, 0)", r, g, b)
2825    } else {
2826        let rounded = rnd_f32((a as f32) / 255.0 * 100.0) / 100.0;
2827        alloc::format!("rgba({}, {}, {}, {})", r, g, b, format_css_num(rounded))
2828    }
2829}
2830
2831/// 色トークンなら `rgb()` 表記へ(`currentcolor`・解釈できないものはそのまま)。
2832fn color_tok_computed(t: &str) -> Option<String> {
2833    let l = t.trim().to_ascii_lowercase();
2834    if l == "currentcolor" {
2835        return None;
2836    }
2837    crate::os_lib::css::color::parse_color(t).map(format_argb_css)
2838}
2839
2840/// 背景画像リスト内のグラデーション(`linear-`/`radial-`/`conic-` と `repeating-`)の計算値。
2841/// 色は `rgb()`、位置は `<position>` の最短形(既定値は省略)、長さは px へ。それ以外の画像は触らない。
2842pub fn normalize_gradient_list_computed(v: &str, font_px: f32) -> String {
2843    let out: Vec<String> = split_top_level_commas(v)
2844        .iter()
2845        .map(|item| gradient_item(item, font_px).unwrap_or_else(|| String::from(item.trim())))
2846        .collect();
2847    out.join(", ")
2848}
2849
2850fn gradient_item(item: &str, font_px: f32) -> Option<String> {
2851    let t = item.trim();
2852    let open = t.find('(')?;
2853    let name = t.get(..open)?.to_ascii_lowercase();
2854    let kind = name.strip_prefix("repeating-").unwrap_or(&name);
2855    if !matches!(kind, "linear-gradient" | "radial-gradient" | "conic-gradient") {
2856        return None;
2857    }
2858    let inner = t.get(open + 1..)?.strip_suffix(')')?;
2859    let args = split_top_level_commas(inner);
2860    let mut parts: Vec<String> = Vec::new();
2861    let mut start = 0;
2862    let first = args.first()?;
2863    let first_is_stop = split_top_ws(first).first().is_some_and(|w| color_tok_computed(w).is_some() || w.eq_ignore_ascii_case("currentcolor"))
2864        || lp_of(first, font_px).is_some() && !first.contains(' ') && kind != "radial-gradient" && !first.ends_with("deg") && !first.ends_with("turn");
2865    if !first_is_stop {
2866        start = 1;
2867        let cfg = match kind {
2868            "linear-gradient" => linear_gradient_cfg(first),
2869            "radial-gradient" => radial_gradient_cfg(first, font_px)?,
2870            _ => conic_gradient_cfg(first, font_px)?,
2871        };
2872        if !cfg.is_empty() {
2873            parts.push(cfg);
2874        }
2875    }
2876    for a in args.get(start..)? {
2877        parts.push(gradient_stop(a, font_px, kind == "conic-gradient")?);
2878    }
2879    Some(alloc::format!("{}({})", name, parts.join(", ")))
2880}
2881
2882fn linear_gradient_cfg(cfg: &str) -> String {
2883    let l = cfg.trim().to_ascii_lowercase();
2884    let toks: Vec<&str> = l.split_whitespace().collect();
2885    if toks.first() == Some(&"to") && toks.len() == 3 && matches!(toks[1], "top" | "bottom") && matches!(toks[2], "left" | "right") {
2886        return alloc::format!("to {} {}", toks[2], toks[1]);
2887    }
2888    String::from(cfg.trim())
2889}
2890
2891fn pos_is_center(x: LenPct, y: LenPct) -> bool {
2892    (x.0.abs() < 1e-3 && (x.1 - 50.0).abs() < 1e-3) && (y.0.abs() < 1e-3 && (y.1 - 50.0).abs() < 1e-3)
2893}
2894
2895fn radial_gradient_cfg(cfg: &str, font_px: f32) -> Option<String> {
2896    let toks = split_top_ws(cfg.trim());
2897    let at = toks.iter().position(|t| t.eq_ignore_ascii_case("at"));
2898    let pre = &toks[..at.unwrap_or(toks.len())];
2899    let mut shape: Option<String> = None;
2900    let mut size_kw: Option<String> = None;
2901    let mut lens: Vec<LenPct> = Vec::new();
2902    for t in pre {
2903        let l = t.to_ascii_lowercase();
2904        match l.as_str() {
2905            "circle" | "ellipse" => shape = Some(l),
2906            "closest-side" | "closest-corner" | "farthest-side" | "farthest-corner" => size_kw = Some(l),
2907            _ => {
2908                let mut lp = lp_of(t, font_px)?;
2909                if lp.1.abs() < 1e-3 && lp.0 < 0.0 {
2910                    lp.0 = 0.0;
2911                }
2912                lens.push(lp);
2913            }
2914        }
2915    }
2916    let mut out: Vec<String> = Vec::new();
2917    if !lens.is_empty() {
2918        for lp in &lens {
2919            out.push(lp_fmt(*lp));
2920        }
2921    } else {
2922        if shape.as_deref() == Some("circle") {
2923            out.push(String::from("circle"));
2924        }
2925        if let Some(s) = size_kw.filter(|s| s != "farthest-corner") {
2926            out.push(s);
2927        }
2928    }
2929    if let Some(i) = at {
2930        let (x, y) = pos_parse(&toks[i + 1..], font_px)?;
2931        if !pos_is_center(x, y) {
2932            out.push(alloc::format!("at {} {}", lp_fmt(x), lp_fmt(y)));
2933        }
2934    }
2935    Some(out.join(" "))
2936}
2937
2938fn conic_gradient_cfg(cfg: &str, font_px: f32) -> Option<String> {
2939    let toks = split_top_ws(cfg.trim());
2940    let mut out: Vec<String> = Vec::new();
2941    let mut i = 0;
2942    if toks.first().is_some_and(|t| t.eq_ignore_ascii_case("from")) {
2943        let deg = crate::os_lib::css::units::parse_angle_to_deg(toks.get(1)?)?;
2944        if deg.abs() > 1e-4 {
2945            out.push(alloc::format!("from {}deg", format_css_num(deg)));
2946        }
2947        i = 2;
2948    }
2949    if toks.get(i).is_some_and(|t| t.eq_ignore_ascii_case("at")) {
2950        let (x, y) = pos_parse(&toks[i + 1..], font_px)?;
2951        if !pos_is_center(x, y) {
2952            out.push(alloc::format!("at {} {}", lp_fmt(x), lp_fmt(y)));
2953        }
2954    } else if i < toks.len() {
2955        return None;
2956    }
2957    Some(out.join(" "))
2958}
2959
2960fn gradient_stop(a: &str, font_px: f32, angular: bool) -> Option<String> {
2961    let mut out: Vec<String> = Vec::new();
2962    for tok in split_top_ws(a.trim()) {
2963        if let Some(c) = color_tok_computed(tok) {
2964            out.push(c);
2965        } else if angular && (tok.ends_with("deg") || tok.ends_with("turn") || tok.ends_with("rad") || tok.ends_with("grad")) {
2966            let d = crate::os_lib::css::units::parse_angle_to_deg(tok)?;
2967            out.push(alloc::format!("{}deg", format_css_num(d)));
2968        } else if let Some(lp) = lp_of(tok, font_px) {
2969            out.push(lp_fmt(lp));
2970        } else {
2971            out.push(String::from(tok));
2972        }
2973    }
2974    Some(out.join(" "))
2975}
2976
2977// --- 汎用の計算値整形(長さ列・色列・縮約)。プロパティ名ごとの性質は `generic_computed_kind` に集約する ---
2978
2979#[derive(Clone, Copy, Default)]
2980struct GenKind {
2981    /// 長さ(`em`・`calc()`)を px へ。
2982    len: bool,
2983    /// 色(名前・`#rgb`・`hsl()` 等)を `rgb()` へ。
2984    color: bool,
2985    /// 1〜4 値(または 2 値)の繰り返しを縮める。
2986    collapse: bool,
2987    /// 負の長さは 0 に(`padding`・`gap`・幅など)。
2988    nonneg: bool,
2989    /// `%` を包含ブロック幅で px にする(`margin`・`padding` の論理版は使用値で返る)。
2990    pct_px: bool,
2991    /// 罫線幅: `thin`/`medium`/`thick` を px にして整数へ切り捨てる。
2992    border_w: bool,
2993    /// 値が `/` で水平・垂直に分かれる(角丸)。
2994    slash: bool,
2995    /// `0` などの数値 0 を `0px` にする。
2996    zero_px: bool,
2997    /// 縮めて 1 値になった `0` だけ `0px` にする(`box-shadow-offset`)。
2998    single_zero_px: bool,
2999}
3000
3001fn generic_computed_kind(prop: &str) -> Option<GenKind> {
3002    let k = |len, color, collapse, nonneg| GenKind { len, color, collapse, nonneg, zero_px: len, ..Default::default() };
3003    let p = prop;
3004    if p.ends_with("-radius") && p.starts_with("border-") {
3005        return Some(GenKind { slash: true, ..k(true, false, true, true) });
3006    }
3007    if p == "border-radius" {
3008        return Some(GenKind { slash: true, ..k(true, false, true, true) });
3009    }
3010    if p.starts_with("border-") && p.ends_with("-width") && !p.starts_with("border-image") || p == "border-width" || p == "outline-width" || p == "column-rule-width" {
3011        return Some(GenKind { border_w: true, ..k(true, false, true, true) });
3012    }
3013    if p == "border-image-width" || p == "border-image-outset" {
3014        return Some(GenKind { zero_px: false, ..k(true, false, true, true) });
3015    }
3016    if matches!(p, "padding-block" | "padding-inline" | "padding-block-start" | "padding-block-end" | "padding-inline-start" | "padding-inline-end")
3017        || matches!(p, "margin-block" | "margin-inline" | "margin-block-start" | "margin-block-end" | "margin-inline-start" | "margin-inline-end")
3018    {
3019        let nonneg = p.starts_with("padding");
3020        return Some(GenKind { pct_px: true, ..k(true, false, true, nonneg) });
3021    }
3022    if p.starts_with("scroll-padding") {
3023        return Some(k(true, false, true, true));
3024    }
3025    if p.starts_with("scroll-margin") {
3026        return Some(k(true, false, true, false));
3027    }
3028    if matches!(p, "inset" | "inset-block" | "inset-inline" | "inset-block-start" | "inset-block-end" | "inset-inline-start" | "inset-inline-end") {
3029        return Some(k(true, false, true, false));
3030    }
3031    if matches!(p, "gap" | "grid-gap" | "row-gap" | "column-gap" | "grid-row-gap" | "grid-column-gap") {
3032        return Some(k(true, false, true, true));
3033    }
3034    if matches!(p, "text-decoration-inset" | "text-decoration-inset-start" | "text-decoration-inset-end") {
3035        return Some(k(true, false, true, false));
3036    }
3037    if matches!(p, "box-shadow-offset") {
3038        return Some(GenKind { zero_px: false, single_zero_px: true, ..k(true, false, true, false) });
3039    }
3040    if matches!(p, "box-shadow-blur" | "box-shadow-spread" | "text-underline-offset" | "text-decoration-thickness" | "baseline-shift" | "word-spacing" | "outline-offset") {
3041        return Some(k(true, false, false, matches!(p, "box-shadow-blur" | "text-decoration-thickness")));
3042    }
3043    if p == "tab-size" {
3044        return Some(GenKind { zero_px: false, ..k(true, false, false, true) });
3045    }
3046    if matches!(p, "border-block-color" | "border-inline-color") {
3047        return Some(k(false, true, true, false));
3048    }
3049    if p.ends_with("-color") && !matches!(p, "color" | "background-color" | "border-color") || p == "box-shadow-color" {
3050        return Some(k(false, true, false, false));
3051    }
3052    None
3053}
3054
3055fn border_kw_px(t: &str) -> Option<f32> {
3056    match t.to_ascii_lowercase().as_str() {
3057        "thin" => Some(1.0),
3058        "medium" => Some(3.0),
3059        "thick" => Some(5.0),
3060        _ => None,
3061    }
3062}
3063
3064fn generic_token(t: &str, kind: GenKind, font_px: f32, cb_w: f32) -> String {
3065    if kind.border_w {
3066        if let Some(px) = border_kw_px(t) {
3067            return alloc::format!("{}px", format_css_num(px));
3068        }
3069    }
3070    if kind.color {
3071        let tl = t.to_ascii_lowercase();
3072        if !matches!(tl.as_str(), "auto" | "currentcolor" | "none") {
3073            if let Some(c) = color_tok_computed(t) {
3074                return c;
3075            }
3076        }
3077        return String::from(t);
3078    }
3079    if !kind.len {
3080        return String::from(t);
3081    }
3082    let first = t.as_bytes().first().copied().unwrap_or(b' ');
3083    if !(first.is_ascii_digit() || matches!(first, b'-' | b'+' | b'.') || t.starts_with("calc(") || t.starts_with("min(") || t.starts_with("max(") || t.starts_with("clamp(")) {
3084        return String::from(t);
3085    }
3086    // 単位なしの数(`tab-size`・`border-image-outset` の倍率)はそのまま。0 だけは長さの 0 として扱える性質のものを px へ。
3087    if let Ok(n) = t.parse::<f32>() {
3088        return if n == 0.0 && kind.zero_px { String::from("0px") } else { String::from(t) };
3089    }
3090    let Some(mut lp) = lp_of(t, font_px) else { return String::from(t) };
3091    if kind.pct_px && cb_w > 0.0 {
3092        lp = (lp.0 + lp.1 / 100.0 * cb_w, 0.0);
3093    }
3094    if lp.1.abs() < 1e-6 && lp.0 < 0.0 && kind.nonneg {
3095        lp.0 = 0.0;
3096    }
3097    if kind.border_w && lp.1.abs() < 1e-6 && lp.0 >= 1.0 {
3098        lp.0 = (lp.0 as i32) as f32;
3099    }
3100    lp_fmt(lp)
3101}
3102
3103fn collapse_box_list(toks: &mut Vec<String>) {
3104    let n = toks.len();
3105    if n == 0 || n > 4 {
3106        return;
3107    }
3108    let (a, b, c, d) = match n {
3109        1 => (0, 0, 0, 0),
3110        2 => (0, 1, 0, 1),
3111        3 => (0, 1, 2, 1),
3112        _ => (0, 1, 2, 3),
3113    };
3114    let t: [String; 4] = [toks[a].clone(), toks[b].clone(), toks[c].clone(), toks[d].clone()];
3115    let out: Vec<String> = if t[3] == t[1] {
3116        if t[2] == t[0] {
3117            if t[1] == t[0] {
3118                alloc::vec![t[0].clone()]
3119            } else {
3120                alloc::vec![t[0].clone(), t[1].clone()]
3121            }
3122        } else {
3123            alloc::vec![t[0].clone(), t[1].clone(), t[2].clone()]
3124        }
3125    } else {
3126        alloc::vec![t[0].clone(), t[1].clone(), t[2].clone(), t[3].clone()]
3127    };
3128    *toks = out;
3129}
3130
3131/// プロパティ名ごとの汎用整形。扱わないプロパティは `None`。`cb_w` は `%` を px にするときの包含ブロック幅。
3132pub fn normalize_generic_computed(prop: &str, v: &str, font_px: f32, cb_w: f32) -> Option<String> {
3133    let kind = generic_computed_kind(prop)?;
3134    let one = |part: &str| -> String {
3135        let mut toks: Vec<String> = split_top_ws(part).iter().map(|t| generic_token(t, kind, font_px, cb_w)).collect();
3136        if kind.collapse {
3137            collapse_box_list(&mut toks);
3138            if kind.single_zero_px && toks.len() == 1 && toks[0] == "0" {
3139                toks[0] = String::from("0px");
3140            }
3141        }
3142        toks.join(" ")
3143    };
3144    let items: Vec<String> = split_top_level_commas(v)
3145        .iter()
3146        .map(|item| {
3147            if kind.slash {
3148                let mut sides = item.splitn(2, '/');
3149                let h = one(sides.next().unwrap_or(""));
3150                match sides.next() {
3151                    Some(vs) => {
3152                        let vv = one(vs);
3153                        if vv == h { h } else { alloc::format!("{} / {}", h, vv) }
3154                    }
3155                    None => h,
3156                }
3157            } else {
3158                one(item)
3159            }
3160        })
3161        .collect();
3162    Some(items.join(", "))
3163}
3164
3165// --- プロパティ個別の計算値整形(トークン順の正規化・既定値の省略・数値の丸め) ---
3166
3167fn tokens_in_order(v: &str, order: &[&[&str]]) -> Option<String> {
3168    let toks = split_top_ws(v);
3169    let mut slots: Vec<Option<String>> = alloc::vec![None; order.len()];
3170    for t in toks {
3171        let tl = t.to_ascii_lowercase();
3172        let i = order.iter().position(|g| g.contains(&tl.as_str()))?;
3173        if slots[i].replace(tl).is_some() {
3174            return None;
3175        }
3176    }
3177    let out: Vec<String> = slots.into_iter().flatten().collect();
3178    Some(out.join(" "))
3179}
3180
3181fn num_calc_eval(t: &str) -> Option<f32> {
3182    let t = t.trim();
3183    if let Ok(n) = t.parse::<f32>() {
3184        return Some(n);
3185    }
3186    if t.starts_with("calc(") {
3187        return eval_math_f32(t, 0, 16.0).filter(|n| n.is_finite());
3188    }
3189    None
3190}
3191
3192/// `line-height`: 数・`%`・長さ・`calc()` を px へ(`normal` はそのまま)。
3193fn line_height_computed(v: &str, font_px: f32) -> Option<String> {
3194    let t = v.trim();
3195    if t.eq_ignore_ascii_case("normal") || t.contains("cq") {
3196        return None;
3197    }
3198    if let Ok(n) = t.parse::<f32>() {
3199        return Some(alloc::format!("{}px", format_css_num(n * font_px)));
3200    }
3201    let (px, pct) = lp_of(t, font_px)?;
3202    Some(alloc::format!("{}px", format_css_num(px + pct / 100.0 * font_px)))
3203}
3204
3205fn overflow_computed(v: &str) -> Option<String> {
3206    let toks = split_top_ws(v);
3207    let norm = |a: &str, b: &str| -> (String, String) {
3208        let (mut a, mut b) = (a.to_ascii_lowercase(), b.to_ascii_lowercase());
3209        let strong = |s: &str| !matches!(s, "visible" | "clip");
3210        if a == "visible" && strong(&b) {
3211            a = String::from("auto");
3212        }
3213        if b == "visible" && strong(&a) {
3214            b = String::from("auto");
3215        }
3216        (a, b)
3217    };
3218    match toks.as_slice() {
3219        [a] => Some(a.to_ascii_lowercase()),
3220        [a, b] => {
3221            let (x, y) = norm(a, b);
3222            Some(if x == y { x } else { alloc::format!("{} {}", x, y) })
3223        }
3224        _ => None,
3225    }
3226}
3227
3228fn text_wrap_computed(v: &str) -> Option<String> {
3229    let toks = split_top_ws(v);
3230    let (mut mode, mut style) = (None::<String>, None::<String>);
3231    for t in toks {
3232        let tl = t.to_ascii_lowercase();
3233        match tl.as_str() {
3234            "wrap" | "nowrap" => mode = Some(tl),
3235            "auto" | "balance" | "stable" | "pretty" => style = Some(tl),
3236            _ => return None,
3237        }
3238    }
3239    let mut out: Vec<String> = Vec::new();
3240    if let Some(m) = mode.filter(|m| m != "wrap") {
3241        out.push(m);
3242    }
3243    if let Some(s) = style.filter(|s| s != "auto") {
3244        out.push(s);
3245    }
3246    Some(if out.is_empty() { String::from("wrap") } else { out.join(" ") })
3247}
3248
3249fn text_spacing_computed(v: &str) -> Option<String> {
3250    let toks = split_top_ws(v);
3251    if toks.len() == 1 && matches!(toks[0].to_ascii_lowercase().as_str(), "none" | "auto" | "normal" | "initial") {
3252        let l = toks[0].to_ascii_lowercase();
3253        return Some(if l == "initial" { String::from("normal") } else { l });
3254    }
3255    let (mut trim, mut auto) = (None::<String>, None::<String>);
3256    for t in toks {
3257        let tl = t.to_ascii_lowercase();
3258        match tl.as_str() {
3259            "space-all" | "normal" | "space-first" | "trim-start" | "trim-both" | "trim-all" | "allow-end" => {
3260                if trim.replace(tl).is_some() {
3261                    return None;
3262                }
3263            }
3264            "no-autospace" | "auto" => {
3265                if auto.replace(tl).is_some() {
3266                    return None;
3267                }
3268            }
3269            _ => return None,
3270        }
3271    }
3272    if trim.as_deref() == Some("space-all") && auto.as_deref() == Some("no-autospace") {
3273        return Some(String::from("none"));
3274    }
3275    let mut out: Vec<String> = Vec::new();
3276    if let Some(t) = trim.filter(|t| t != "normal") {
3277        out.push(t);
3278    }
3279    if let Some(a) = auto.filter(|a| a != "auto") {
3280        out.push(a);
3281    }
3282    Some(if out.is_empty() { String::from("normal") } else { out.join(" ") })
3283}
3284
3285fn align_word(t: &str) -> String {
3286    match t.to_ascii_lowercase().as_str() {
3287        "flex-start" => String::from("flow-start"),
3288        "flex-end" => String::from("flow-end"),
3289        o => String::from(o),
3290    }
3291}
3292
3293/// `place-content` / `place-items` / `place-self` の計算値: `flex-*` → `flow-*`、重複値の縮約、`first baseline` → `baseline`。
3294fn place_computed(prop: &str, v: &str) -> Option<String> {
3295    let toks = split_top_ws(v);
3296    let mut items: Vec<String> = Vec::new();
3297    let mut i = 0;
3298    while i < toks.len() {
3299        let t = toks[i].to_ascii_lowercase();
3300        if matches!(t.as_str(), "safe" | "unsafe" | "last" | "first") && i + 1 < toks.len() {
3301            let nxt = align_word(toks[i + 1]);
3302            items.push(if t == "first" { nxt } else { alloc::format!("{} {}", t, nxt) });
3303            i += 2;
3304        } else {
3305            items.push(align_word(&t));
3306            i += 1;
3307        }
3308    }
3309    if items.len() == 2 && items[0] == items[1] {
3310        items.pop();
3311    }
3312    if items.len() == 1 && prop == "place-content" && matches!(items[0].as_str(), "baseline" | "last baseline") {
3313        items.push(String::from("start"));
3314    }
3315    if items.is_empty() {
3316        return None;
3317    }
3318    Some(items.join(" "))
3319}
3320
3321fn font_settings_computed(v: &str, is_features: bool) -> Option<String> {
3322    let t = v.trim();
3323    if t.eq_ignore_ascii_case("normal") {
3324        return None;
3325    }
3326    let mut entries: Vec<(String, String)> = Vec::new();
3327    for item in split_top_level_commas(t) {
3328        let toks = split_top_ws(item);
3329        let tag = toks.first()?.trim_matches(|c| c == '"' || c == '\'');
3330        let val = match toks.get(1).map(|s| s.to_ascii_lowercase()) {
3331            None => String::from("1"),
3332            Some(s) if s == "on" => String::from("1"),
3333            Some(s) if s == "off" => String::from("0"),
3334            Some(s) => {
3335                let n = num_calc_eval(&s)?;
3336                format_css_num(n)
3337            }
3338        };
3339        let tag = String::from(tag);
3340        entries.retain(|(k, _)| *k != tag);
3341        entries.push((tag, val));
3342    }
3343    entries.sort_by(|a, b| a.0.cmp(&b.0));
3344    let out: Vec<String> = entries
3345        .into_iter()
3346        .map(|(k, v)| if is_features && v == "1" { alloc::format!("\"{}\"", k) } else { alloc::format!("\"{}\" {}", k, v) })
3347        .collect();
3348    Some(out.join(", "))
3349}
3350
3351fn font_weight_computed(v: &str) -> Option<String> {
3352    let t = v.trim().to_ascii_lowercase();
3353    match t.as_str() {
3354        "normal" => return Some(String::from("400")),
3355        "bold" => return Some(String::from("700")),
3356        "bolder" | "lighter" => return None,
3357        _ => {}
3358    }
3359    if t.contains("cq") {
3360        return None;
3361    }
3362    let n = num_calc_eval(&t)?;
3363    Some(format_css_num(n.clamp(1.0, 1000.0)))
3364}
3365
3366fn font_style_computed(v: &str) -> Option<String> {
3367    let toks = split_top_ws(v.trim());
3368    if toks.len() != 2 || !toks[0].eq_ignore_ascii_case("oblique") || v.contains("cq") {
3369        return None;
3370    }
3371    let a = toks[1];
3372    let deg = if a.starts_with("calc(") {
3373        // `calc(30deg * 2)` のように角度の単位が式に入る。単位を外して数だけを評価し度とみなす。
3374        let stripped = a.replace("deg", "");
3375        eval_math_f32(&stripped, 0, 16.0)?
3376    } else {
3377        crate::os_lib::css::units::parse_angle_to_deg(a)?
3378    };
3379    let d = deg.clamp(-90.0, 90.0);
3380    Some(if d == 0.0 { String::from("normal") } else { alloc::format!("oblique {}deg", format_css_num(d)) })
3381}
3382
3383fn overflow_clip_margin_computed(v: &str, font_px: f32) -> Option<String> {
3384    let (mut bx, mut len) = (None::<String>, None::<String>);
3385    for t in split_top_ws(v) {
3386        let tl = t.to_ascii_lowercase();
3387        if matches!(tl.as_str(), "content-box" | "padding-box" | "border-box") {
3388            bx = Some(tl);
3389        } else {
3390            let (px, pct) = lp_of(t, font_px)?;
3391            let _ = pct;
3392            len = Some(alloc::format!("{}px", format_css_num(px)));
3393        }
3394    }
3395    let bx = bx.filter(|b| b != "padding-box");
3396    let len = len.filter(|l| l != "0px");
3397    let mut out: Vec<String> = Vec::new();
3398    if let Some(b) = bx {
3399        out.push(b);
3400    }
3401    if let Some(l) = len {
3402        out.push(l);
3403    }
3404    Some(if out.is_empty() { String::from("0px") } else { out.join(" ") })
3405}
3406
3407fn hyphenate_limit_chars_computed(v: &str) -> Option<String> {
3408    let mut toks: Vec<String> = Vec::new();
3409    for t in split_top_ws(v) {
3410        if t.eq_ignore_ascii_case("auto") {
3411            toks.push(String::from("auto"));
3412        } else {
3413            toks.push(format_css_num(rnd_f32(num_calc_eval(t)?)));
3414        }
3415    }
3416    if toks.len() == 3 && toks[2] == toks[1] {
3417        toks.pop();
3418    }
3419    if toks.len() == 2 && toks[1] == "auto" {
3420        toks.pop();
3421    }
3422    Some(toks.join(" "))
3423}
3424
3425/// プロパティ名ごとの個別整形。扱わなければ `None`。
3426pub fn normalize_misc_computed(prop: &str, v: &str, font_px: f32) -> Option<String> {
3427    let t = v.trim();
3428    match prop {
3429        "line-height" => line_height_computed(t, font_px),
3430        "overflow" => overflow_computed(t),
3431        "text-wrap" => text_wrap_computed(t),
3432        "text-spacing" => text_spacing_computed(t),
3433        "text-autospace" => {
3434            if t.eq_ignore_ascii_case("initial") {
3435                return Some(String::from("normal"));
3436            }
3437            tokens_in_order(t, &[&["ideograph-alpha"], &["ideograph-numeric"], &["punctuation"], &["insert", "replace"], &["normal", "no-autospace", "auto"]])
3438        }
3439        "text-fit" => {
3440            let toks = split_top_ws(t);
3441            let kept: Vec<&str> = toks.iter().copied().filter(|x| !x.eq_ignore_ascii_case("consistent")).collect();
3442            if kept.is_empty() { None } else { Some(kept.join(" ")) }
3443        }
3444        "white-space-trim" => tokens_in_order(t, &[&["discard-before"], &["discard-after"], &["discard-inner"], &["none"]]),
3445        "font-variant-ligatures" => tokens_in_order(
3446            t,
3447            &[&["common-ligatures", "no-common-ligatures"], &["discretionary-ligatures", "no-discretionary-ligatures"], &["historical-ligatures", "no-historical-ligatures"], &["contextual", "no-contextual"], &["normal", "none"]],
3448        ),
3449        "font-variant-east-asian" => tokens_in_order(
3450            t,
3451            &[&["jis78", "jis83", "jis90", "jis04", "simplified", "traditional"], &["full-width", "proportional-width"], &["ruby"], &["normal"]],
3452        ),
3453        "font-variant-numeric" => tokens_in_order(
3454            t,
3455            &[&["lining-nums", "oldstyle-nums"], &["proportional-nums", "tabular-nums"], &["diagonal-fractions", "stacked-fractions"], &["ordinal"], &["slashed-zero"], &["normal"]],
3456        ),
3457        "font-feature-settings" => font_settings_computed(t, true),
3458        "font-variation-settings" => font_settings_computed(t, false),
3459        "font-weight" => font_weight_computed(t),
3460        "font-style" => font_style_computed(t),
3461        "overflow-clip-margin" => overflow_clip_margin_computed(t, font_px),
3462        "hyphenate-limit-chars" => hyphenate_limit_chars_computed(t),
3463        "hyphenate-limit-lines" => num_calc_eval(t).filter(|_| t.starts_with("calc(")).map(|n| format_css_num(rnd_f32(n))),
3464        "z-index" if t.starts_with("calc(") => num_calc_eval(t).map(|n| format_css_num(rnd_f32(n))),
3465        "text-justify" if t.eq_ignore_ascii_case("distribute") => Some(String::from("inter-character")),
3466        "scroll-marker-group" if matches!(t.to_ascii_lowercase().as_str(), "before" | "after") => Some(alloc::format!("{} links", t.to_ascii_lowercase())),
3467        "word-spacing" if t.eq_ignore_ascii_case("normal") => Some(String::from("0px")),
3468        "aspect-ratio" => {
3469            let l = t.to_ascii_lowercase();
3470            let (auto, rest) = match l.strip_prefix("auto") {
3471                Some(r) if !r.trim().is_empty() => (true, String::from(r.trim())),
3472                _ => match l.strip_suffix("auto") {
3473                    Some(r) if !r.trim().is_empty() => (true, String::from(r.trim())),
3474                    _ => (false, l.clone()),
3475                },
3476            };
3477            if rest == "auto" {
3478                return Some(String::from("auto"));
3479            }
3480            let mut it = rest.splitn(2, '/');
3481            let a = it.next()?.trim();
3482            let b = it.next().map(str::trim).unwrap_or("1");
3483            let (na, nb) = (a.parse::<f32>().ok()?, b.parse::<f32>().ok()?);
3484            let r = alloc::format!("{} / {}", format_css_num(na), format_css_num(nb));
3485            Some(if auto { alloc::format!("auto {}", r) } else { r })
3486        }
3487        "vertical-align" => {
3488            let toks = split_top_ws(t);
3489            let zero = |x: &str| x.parse::<f32>().is_ok_and(|n| n == 0.0) || x.strip_suffix("px").is_some_and(|n| n.parse::<f32>().is_ok_and(|n| n == 0.0));
3490            if toks.iter().all(|x| x.eq_ignore_ascii_case("baseline") || zero(x)) {
3491                return Some(String::from("baseline"));
3492            }
3493            if toks.len() == 1 && (t.starts_with("calc(") || t.parse::<f32>().is_err()) {
3494                if let Some(lp) = lp_of(t, font_px) {
3495                    return Some(lp_fmt(lp));
3496                }
3497            }
3498            None
3499        }
3500        "contain-intrinsic-size" => {
3501            let toks = split_top_ws(t);
3502            let mut items: Vec<String> = Vec::new();
3503            let mut i = 0;
3504            while i < toks.len() {
3505                if toks[i].eq_ignore_ascii_case("auto") && i + 1 < toks.len() {
3506                    items.push(alloc::format!("auto {}", toks[i + 1]));
3507                    i += 2;
3508                } else {
3509                    items.push(String::from(toks[i]));
3510                    i += 1;
3511                }
3512            }
3513            if items.len() == 2 && items[0] == items[1] {
3514                items.pop();
3515            }
3516            Some(items.join(" "))
3517        }
3518        "width" | "height" | "min-width" | "min-height" | "max-width" | "max-height" | "inline-size" | "block-size" | "min-inline-size" | "min-block-size" | "max-inline-size" | "max-block-size"
3519            if t.to_ascii_lowercase().starts_with("fit-content(") && t.ends_with(')') =>
3520        {
3521            let inner = t.get(12..t.len() - 1)?;
3522            let lp = lp_of(inner, font_px)?;
3523            Some(alloc::format!("fit-content({})", lp_fmt(lp)))
3524        }
3525        "font-family" => {
3526            let items: Vec<String> = split_top_level_commas(t)
3527                .iter()
3528                .map(|it| {
3529                    let q = it.trim();
3530                    let inner = q.strip_prefix('"').and_then(|x| x.strip_suffix('"')).or_else(|| q.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')));
3531                    match inner {
3532                        Some(n) if !n.is_empty() && n.split(' ').all(|w| {
3533                            let mut c = w.chars();
3534                            c.next().is_some_and(|f| f.is_ascii_alphabetic() || f == '-' || f == '_')
3535                                && w.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
3536                        }) && !matches!(n.to_ascii_lowercase().as_str(), "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui" | "inherit" | "initial" | "unset" | "default") => String::from(n),
3537                        _ => String::from(q),
3538                    }
3539                })
3540                .collect();
3541            Some(items.join(", "))
3542        }
3543        "justify-items" if t.eq_ignore_ascii_case("legacy") => Some(String::from("normal")),
3544        "align-content" | "align-items" | "align-self" | "justify-content" | "justify-items" | "justify-self" => {
3545            let toks = split_top_ws(t);
3546            Some(toks.iter().map(|x| align_word(x)).collect::<Vec<_>>().join(" "))
3547        }
3548        "place-content" | "place-items" | "place-self" => place_computed(prop, t),
3549        "text-indent" => {
3550            let mut len = None::<String>;
3551            let (mut hang, mut each) = (false, false);
3552            for tk in split_top_ws(t) {
3553                match tk.to_ascii_lowercase().as_str() {
3554                    "hanging" => hang = true,
3555                    "each-line" => each = true,
3556                    _ => {
3557                        let lp = lp_of(tk, font_px)?;
3558                        len = Some(lp_fmt(lp));
3559                    }
3560                }
3561            }
3562            let mut out = alloc::vec![len?];
3563            if hang {
3564                out.push(String::from("hanging"));
3565            }
3566            if each {
3567                out.push(String::from("each-line"));
3568            }
3569            Some(out.join(" "))
3570        }
3571        _ => None,
3572    }
3573}
3574
3575/// 算出値のシリアライズの共通入口(`getComputedStyle()` の値の読み出しと、WPT ホスト実行器の両方が使う)。
3576/// 指定値の文字列を、WPT `test_computed_value` が期待する形(Chrome と同じ形)へ整える。カスタムプロパティ(`--x`)・
3577/// `font-family`・扱わないプロパティは `None`(呼び出し側が指定値のまま返す)。呼ばれるたびに 1 値だけを処理し、
3578/// カスケード・レイアウトには何も足さない。`cb_w` は `%` を px に解く包含ブロック幅(不明なら 0 で解かない)。
3579pub fn serialize_computed_value(prop: &str, v: &str, font_px: f32, cb_w: f32) -> Option<String> {
3580    if prop.starts_with("--") || prop == "font-family" || v.contains("var(") {
3581        return None;
3582    }
3583    let out = match prop {
3584        "display" => normalize_display_computed(v),
3585        "background-position" | "object-position" | "mask-position" | "offset-position" | "offset-anchor" => {
3586            normalize_position_computed(v, font_px, None, false)
3587        }
3588        "background-position-x" => normalize_position_axis_computed(v, font_px, true),
3589        "background-position-y" => normalize_position_axis_computed(v, font_px, false),
3590        "background-image" | "mask-image" | "border-image-source" | "list-style-image" => {
3591            normalize_url_modifiers(&normalize_gradient_list_computed(v, font_px))
3592        }
3593        _ => normalize_misc_computed(prop, v, font_px).or_else(|| normalize_generic_computed(prop, v, font_px, cb_w))?,
3594    };
3595    if out == v.trim() { None } else { Some(out) }
3596}