Skip to main content

atmos/os_lib/web_apis/interp/
reflect.rs

1//! HTML 要素の IDL 属性の「反映」(reflecting)を表で引く実装。HTML Standard §2.6.1。
2//! 型(文字列・URL・列挙・真偽・整数・小数)ごとの取得・代入の規則を 1 か所にまとめ、
3//! 個別の腕を持たない属性(obsolete な `align`・`hspace` など)と、腕が仕様どおりでない属性
4//! (`dir`・`referrerPolicy`・`tabIndex`・`maxLength` など)を表(`reflect_table.rs`、WPT から生成)で扱う。
5//! 表に無い名前は `None`/`false` を返して従来の実装へ進む。二分探索の 1 回分だけが追加の費用。
6
7use super::*;
8use super::reflect_table::TABLE;
9use crate::os_lib::web_apis::dom_bridge::{node_local_name, node_namespace};
10use crate::os_lib::web_apis::builtins::dom_ns::HTML_NS;
11
12pub(super) struct EnumSpec {
13    pub kw: &'static [&'static str],
14    /// 属性が無いときの値(`None` は null)。
15    pub def: Option<&'static str>,
16    /// 属性が不正な値のときの値。
17    pub inv: Option<&'static str>,
18    /// 非正規の綴り → 正規の綴り。
19    pub canon: &'static [(&'static str, &'static str)],
20    pub nullable: bool,
21}
22
23pub(super) enum K {
24    Str,
25    /// `[LegacyNullToEmptyString]` の文字列。
26    StrNe,
27    Url,
28    Enum(&'static EnumSpec),
29    Bool,
30    /// `long`。既定値が `None` のときは、属性が無い・不正な場合は従来の実装へ進む(`tabIndex`)。
31    Long(Option<i32>),
32    LimLong(i32),
33    ULong(u32),
34    LimULong(u32),
35    LimULongFb(u32),
36    Clamped(u32, u32, u32),
37    Double(f64),
38    LimDouble(f64),
39}
40
41pub(super) struct Entry {
42    pub name: &'static str,
43    /// 対象の要素(HTML 名前空間の localName)。`*` は全部。
44    pub tags: &'static [&'static str],
45    pub attr: &'static str,
46    pub kind: K,
47    /// `false` のとき代入だけ反映する(取得は従来の実装。`img.width` など)。
48    pub get: bool,
49}
50
51const MAX_INT: f64 = 2147483647.0;
52const MIN_INT: f64 = -2147483648.0;
53
54fn is_ws(c: char) -> bool {
55    matches!(c, ' ' | '\t' | '\n' | '\u{c}' | '\r')
56}
57
58/// 「整数の解析規則」。失敗は `None`。
59fn parse_int(s: &str) -> Option<f64> {
60    let mut it = s.chars().skip_while(|c| is_ws(*c)).peekable();
61    let mut sign = 1.0;
62    match it.peek() {
63        Some('-') => {
64            sign = -1.0;
65            it.next();
66        }
67        Some('+') => {
68            it.next();
69        }
70        _ => {}
71    }
72    if !it.peek().is_some_and(|c| c.is_ascii_digit()) {
73        return None;
74    }
75    let mut v = 0.0f64;
76    while let Some(c) = it.peek().copied().filter(|c| c.is_ascii_digit()) {
77        v = v * 10.0 + (c as u32 - '0' as u32) as f64;
78        it.next();
79    }
80    Some(if v == 0.0 { 0.0 } else { sign * v })
81}
82
83/// 「浮動小数点数の解析規則」。失敗は `None`。
84fn parse_float(s: &str) -> Option<f64> {
85    let c: Vec<char> = s.chars().collect();
86    let mut p = 0;
87    while p < c.len() && is_ws(c[p]) {
88        p += 1;
89    }
90    if p >= c.len() {
91        return None;
92    }
93    let (mut value, mut divisor, mut exponent) = (1.0f64, 1.0f64, 1.0f64);
94    if c[p] == '-' {
95        value = -1.0;
96        divisor = -1.0;
97        p += 1;
98    } else if c[p] == '+' {
99        p += 1;
100    }
101    if p >= c.len() {
102        return None;
103    }
104    if c[p] == '.' && p + 1 < c.len() && c[p + 1].is_ascii_digit() {
105        value = 0.0;
106    } else if !c[p].is_ascii_digit() {
107        return None;
108    } else {
109        let mut val = 0.0f64;
110        while p < c.len() && c[p].is_ascii_digit() {
111            val = val * 10.0 + (c[p] as u32 - '0' as u32) as f64;
112            p += 1;
113        }
114        value *= val;
115    }
116    if p < c.len() && c[p] == '.' {
117        p += 1;
118        while p < c.len() && c[p].is_ascii_digit() {
119            divisor *= 10.0;
120            value += (c[p] as u32 - '0' as u32) as f64 / divisor;
121            p += 1;
122        }
123    }
124    if p < c.len() && (c[p] == 'e' || c[p] == 'E') {
125        p += 1;
126        if p < c.len() {
127            if c[p] == '-' {
128                exponent = -1.0;
129                p += 1;
130            } else if c[p] == '+' {
131                p += 1;
132            }
133            if p < c.len() && c[p].is_ascii_digit() {
134                let mut exp = 0.0f64;
135                while p < c.len() && c[p].is_ascii_digit() {
136                    exp = exp * 10.0 + (c[p] as u32 - '0' as u32) as f64;
137                    p += 1;
138                }
139                exponent *= exp;
140                value *= pow10(exponent);
141            }
142        }
143    }
144    if !value.is_finite() {
145        return None;
146    }
147    Some(if value == 0.0 { 0.0 } else { value })
148}
149
150fn pow10(e: f64) -> f64 {
151    // `no_std` では `powf` が無い。桁を文字列にして正しく丸める解析に任せる(`1e25` が `9.99…e24` にならない)。
152    if !(-400.0..=400.0).contains(&e) {
153        return if e > 0.0 { f64::INFINITY } else { 0.0 };
154    }
155    alloc::format!("1e{}", e as i32).parse::<f64>().unwrap_or(0.0)
156}
157
158fn to_int32(n: f64) -> i32 {
159    // `no_std` には `floor` が無い。2^63 未満は整数への切り捨てキャスト(0 方向)で足りる。それ以上は 2^32 の倍数なので 0。
160    if !n.is_finite() || n >= 9.0e18 || n <= -9.0e18 {
161        return 0;
162    }
163    (n as i64) as u32 as i32
164}
165
166fn enum_get(sp: &EnumSpec, raw: Option<String>) -> Value {
167    let canon = |s: &'static str| -> &'static str { sp.canon.iter().find(|(a, _)| *a == s).map(|(_, b)| *b).unwrap_or(s) };
168    let out = |s: Option<&'static str>| match s {
169        Some(v) => Value::str(canon(v)),
170        None => Value::Null,
171    };
172    match raw {
173        None => match sp.def {
174            Some(v) => Value::str(v),
175            None => Value::Null,
176        },
177        Some(r) => {
178            for k in sp.kw {
179                if r.eq_ignore_ascii_case(k) {
180                    return Value::str(canon(k));
181                }
182            }
183            out(sp.inv)
184        }
185    }
186}
187
188impl Interp {
189    /// 表の中で、この要素・この名前に当たる行。
190    fn reflect_entry(&self, idx: usize, key: &str) -> Option<&'static Entry> {
191        let lo = TABLE.partition_point(|e| e.name < key);
192        if lo >= TABLE.len() || TABLE[lo].name != key {
193            return None;
194        }
195        let dom = self.dom().borrow();
196        let n = dom.nodes.get(idx)?;
197        if node_namespace(n).as_deref() != Some(HTML_NS) {
198            return None;
199        }
200        let local = node_local_name(n);
201        TABLE[lo..].iter().take_while(|e| e.name == key).find(|e| e.tags.iter().any(|t| *t == "*" || *t == local))
202    }
203
204    /// `el.<key>` の取得。表に無ければ `None`(従来の実装へ)。
205    pub(crate) fn reflect_get(&mut self, idx: usize, key: &str) -> Option<Value> {
206        let e = self.reflect_entry(idx, key)?;
207        if !e.get {
208            return None;
209        }
210        let raw = self.dom().borrow().get_attr(idx, e.attr);
211        Some(match &e.kind {
212            K::Str | K::StrNe => Value::str(raw.unwrap_or_default()),
213            K::Url => {
214                let doc_default = matches!(e.attr, "action" | "formaction") && matches!(self.reflect_local(idx).as_deref(), Some("form" | "button" | "input"));
215                match raw {
216                    Some(r) if !r.is_empty() || !doc_default => Value::str(self.reflect_resolve_url(&r)),
217                    _ if doc_default => Value::str(super::super::builtins::location_href(&self.global).unwrap_or_default()),
218                    _ => Value::str(""),
219                }
220            }
221            K::Enum(sp) => enum_get(sp, raw),
222            K::Bool => Value::Bool(raw.is_some()),
223            K::Long(def) => {
224                let v = raw.and_then(|r| parse_int(&r)).filter(|v| (MIN_INT..=MAX_INT).contains(v));
225                match (v, def) {
226                    (Some(v), _) => Value::Number(v),
227                    (None, Some(d)) => Value::Number(*d as f64),
228                    (None, None) => return None,
229                }
230            }
231            K::LimLong(d) => {
232                let v = raw.and_then(|r| parse_int(&r)).filter(|v| (0.0..=MAX_INT).contains(v));
233                Value::Number(v.unwrap_or(*d as f64))
234            }
235            K::ULong(d) => {
236                let v = raw.and_then(|r| parse_int(&r)).filter(|v| (0.0..=MAX_INT).contains(v));
237                Value::Number(v.unwrap_or(*d as f64))
238            }
239            K::LimULong(d) | K::LimULongFb(d) => {
240                let v = raw.and_then(|r| parse_int(&r)).filter(|v| (1.0..=MAX_INT).contains(v));
241                Value::Number(v.unwrap_or(*d as f64))
242            }
243            K::Clamped(min, max, d) => match raw.and_then(|r| parse_int(&r)).filter(|v| *v >= 0.0) {
244                Some(v) => Value::Number(v.clamp(*min as f64, *max as f64)),
245                None => Value::Number(*d as f64),
246            },
247            K::Double(d) => Value::Number(raw.and_then(|r| parse_float(&r)).unwrap_or(*d)),
248            K::LimDouble(d) => Value::Number(raw.and_then(|r| parse_float(&r)).filter(|v| *v > 0.0).unwrap_or(*d)),
249        })
250    }
251
252    /// 反映する URL 属性の取得: 文書の URL を基準に解析し、できなければ属性値そのまま(空文字列も基準 URL になる)。
253    fn reflect_resolve_url(&self, raw: &str) -> String {
254        use crate::os_lib::web_apis::builtins::url_parser;
255        let base = super::super::builtins::location_href(&self.global).filter(|s| !s.is_empty()).unwrap_or_else(|| self.base_url.clone());
256        match url_parser::parse(raw, if base.is_empty() { None } else { Some(&base) }) {
257            Some(u) => url_parser::serialize(&u, false),
258            None => String::from(raw),
259        }
260    }
261
262    fn reflect_local(&self, idx: usize) -> Option<String> {
263        self.dom().borrow().nodes.get(idx).map(node_local_name)
264    }
265
266    /// `el.<key> = val`。表で処理したら `true`。
267    pub(crate) fn reflect_set(&mut self, idx: usize, key: &str, val: &Value) -> bool {
268        let Some(e) = self.reflect_entry(idx, key) else { return false };
269        let attr = e.attr;
270        let num = |it: &mut Interp| -> f64 {
271            match it.to_primitive(val.clone(), "number") {
272                Ok(p) => p.to_number(),
273                Err(_) => f64::NAN,
274            }
275        };
276        let text = |it: &mut Interp| -> String { it.to_string_value(val.clone()).unwrap_or_default() };
277        match &e.kind {
278            K::Str | K::Url => {
279                let s = text(self);
280                self.dom().borrow_mut().set_attr(idx, attr, &s);
281            }
282            K::StrNe => {
283                let s = if matches!(val, Value::Null) { String::new() } else { text(self) };
284                self.dom().borrow_mut().set_attr(idx, attr, &s);
285            }
286            K::Enum(sp) => {
287                if sp.nullable && matches!(val, Value::Null | Value::Undefined) {
288                    self.dom().borrow_mut().remove_attr(idx, attr);
289                } else {
290                    let s = text(self);
291                    self.dom().borrow_mut().set_attr(idx, attr, &s);
292                }
293            }
294            K::Bool => {
295                if val.truthy() {
296                    self.dom().borrow_mut().set_attr(idx, attr, "");
297                } else {
298                    self.dom().borrow_mut().remove_attr(idx, attr);
299                }
300            }
301            K::Long(_) => {
302                let n = to_int32(num(self));
303                self.dom().borrow_mut().set_attr(idx, attr, &alloc::format!("{}", n));
304            }
305            K::LimLong(_) => {
306                let n = to_int32(num(self));
307                // 負の値は仕様では IndexSizeError。代入の経路に例外を返す口が無いので、属性は変えない。
308                if n >= 0 {
309                    self.dom().borrow_mut().set_attr(idx, attr, &alloc::format!("{}", n));
310                }
311            }
312            K::ULong(d) | K::Clamped(_, _, d) => {
313                let u = to_int32(num(self)) as u32;
314                let v = if (u as f64) <= MAX_INT { u } else { *d };
315                self.dom().borrow_mut().set_attr(idx, attr, &alloc::format!("{}", v));
316            }
317            K::LimULong(_) => {
318                let u = to_int32(num(self)) as u32;
319                if u != 0 {
320                    let v = if (u as f64) <= MAX_INT { u } else { 1 };
321                    self.dom().borrow_mut().set_attr(idx, attr, &alloc::format!("{}", v));
322                }
323            }
324            K::LimULongFb(d) => {
325                let u = to_int32(num(self)) as u32;
326                let v = if u >= 1 && (u as f64) <= MAX_INT { u } else { *d };
327                self.dom().borrow_mut().set_attr(idx, attr, &alloc::format!("{}", v));
328            }
329            K::Double(_) => {
330                let n = num(self);
331                self.dom().borrow_mut().set_attr(idx, attr, &Value::Number(n).to_js_string());
332            }
333            K::LimDouble(_) => {
334                let n = num(self);
335                if n > 0.0 {
336                    self.dom().borrow_mut().set_attr(idx, attr, &Value::Number(n).to_js_string());
337                }
338            }
339        }
340        true
341    }
342
343    /// `<a>`/`<area>` の `href` を、文書の URL を基準に解析した URL(解析できなければ `None`)。
344    pub(crate) fn anchor_url(&self, idx: usize) -> Option<crate::os_lib::web_apis::builtins::url_parser::Url> {
345        use crate::os_lib::web_apis::builtins::url_parser;
346        let raw = self.dom().borrow().get_attr(idx, "href")?;
347        let base = super::super::builtins::location_href(&self.global).filter(|s| !s.is_empty()).unwrap_or_else(|| self.base_url.clone());
348        url_parser::parse(&raw, if base.is_empty() { None } else { Some(&base) })
349    }
350
351    /// `a.protocol` などの取得(URL 分解プロパティ)。
352    pub(crate) fn anchor_get(&self, idx: usize, key: &str) -> String {
353        use crate::os_lib::web_apis::builtins::url_parser;
354        let Some(u) = self.anchor_url(idx) else {
355            return if key == "protocol" { String::from(":") } else { String::new() };
356        };
357        match key {
358            "protocol" => alloc::format!("{}:", u.scheme),
359            "username" => u.username,
360            "password" => u.password,
361            "host" => match (&u.host, u.port) {
362                (Some(h), Some(p)) => alloc::format!("{}:{}", h, p),
363                (Some(h), None) => h.clone(),
364                _ => String::new(),
365            },
366            "hostname" => u.host.unwrap_or_default(),
367            "port" => u.port.map(|p| alloc::format!("{}", p)).unwrap_or_default(),
368            "pathname" => url_parser::path_string(&u),
369            "search" => match &u.query {
370                Some(q) if !q.is_empty() => alloc::format!("?{}", q),
371                _ => String::new(),
372            },
373            "hash" => match &u.fragment {
374                Some(f) if !f.is_empty() => alloc::format!("#{}", f),
375                _ => String::new(),
376            },
377            "origin" => url_parser::origin(&u),
378            _ => String::new(),
379        }
380    }
381
382    /// `a.protocol = v` などの代入。新しい URL を `href` 属性へ書く。
383    pub(crate) fn anchor_set(&mut self, idx: usize, key: &str, v: &str) {
384        use crate::os_lib::web_apis::builtins::url_parser;
385        if let Some(mut u) = self.anchor_url(idx) {
386            url_parser::apply_setter(&mut u, key, v);
387            self.dom().borrow_mut().set_attr(idx, "href", &url_parser::serialize(&u, false));
388        }
389    }
390}